载入中...
搜索中...
未找到
VehicleTires3D.cpp
浏览该文件的文档.
1// eve-hot-path
2#include <box3d/box3d.h>
3#include <algorithm>
4#include <array>
5#include <cmath>
6#include <limits>
7#include "physics/Body3D.h"
8#include "physics/Shape3D.h"
9#include "physics/World3D.h"
14
16namespace {
17using V = physics::ForceVector;
18template <class T>
19V vec(T v) {
20 return {v.x, v.y, v.z};
21}
22V add(V a, V b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
23V scale(V a, double k) { return {a.x * k, a.y * k, a.z * k}; }
24double dot(V a, V b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
25V cross(V a, V b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }
26double length(V a) { return std::hypot(a.x, a.y, a.z); }
27bool finite(V a) { return std::isfinite(a.x) && std::isfinite(a.y) && std::isfinite(a.z); }
28bool positive(double x) { return std::isfinite(x) && x > 0; }
29bool nonnegative(double x) { return std::isfinite(x) && x >= 0; }
30bool fits(V a) {
31 const double limit = std::numeric_limits<float>::max();
32 return finite(a) && std::abs(a.x) <= limit && std::abs(a.y) <= limit && std::abs(a.z) <= limit;
33}
34b3Vec3 native(V v) { return {float(v.x), float(v.y), float(v.z)}; }
35V multiply(b3Matrix3 m, V a) {
36 return {m.cx.x * a.x + m.cy.x * a.y + m.cz.x * a.z, m.cx.y * a.x + m.cy.y * a.y + m.cz.y * a.z,
37 m.cx.z * a.x + m.cy.z * a.y + m.cz.z * a.z};
38}
39Result<VehiclePhysicsStatus> reject(std::string message) {
41 Diagnostic::error(DiagnosticCode::InvalidArgument, std::move(message), "vehicle.tires3d"));
42}
43struct Contact {
44 physics::Body3D* ground = nullptr;
45 V point{}, normal{};
46 b3SurfaceMaterial material{};
47 float fraction = 1;
48 int shapeId = 0;
49};
50struct RayContext {
51 physics::Body3D& chassis;
52 V up;
53 Contact contact;
54 // Only this synchronous native callback sees the borrowed wrappers. No user callbacks or query-cache mutation.
55 static float collect(b3ShapeId id, b3Pos point, b3Vec3 normal, float fraction, uint64_t, int triangle, int,
56 void* opaque) {
57 auto& context = *static_cast<RayContext*>(opaque);
58 if (b3Shape_IsSensor(id)) return -1;
59 auto* shape = static_cast<physics::Shape3D*>(b3Shape_GetUserData(id));
60 auto* ground = static_cast<physics::Body3D*>(b3Body_GetUserData(b3Shape_GetBody(id)));
61 if (!shape || !ground || ground == &context.chassis || !ground->isValid() || !shape->isValid()) return -1;
62 const auto n = vec(normal);
63 if (dot(n, context.up) <= 1e-4) return -1;
64 auto& hit = context.contact;
65 if (!hit.ground || fraction < hit.fraction || (fraction == hit.fraction && shape->getId() < hit.shapeId)) {
66 auto material = b3Shape_GetSurfaceMaterial(id);
67 if (triangle >= 0 && triangle < shape->getTriangleMeshTriangleCount()) {
68 const int slot = shape->getTriangleMeshMaterialIndex(triangle);
69 if (slot >= 0 && slot < b3Shape_GetMeshMaterialCount(id))
70 material = b3Shape_GetMeshSurfaceMaterial(id, slot);
71 }
72 // Conveyor velocity is local to the shape, then projected onto the hit plane.
73 const b3Quat local{shape->getLocalRotX(), shape->getLocalRotY(), shape->getLocalRotZ(),
74 shape->getLocalRotW()};
75 material.tangentVelocity = b3Body_GetWorldVector(eve::physics::box3d::Access::bodyId(*ground),
76 b3RotateVector(local, material.tangentVelocity));
77 hit = {ground, vec(point), n, material, fraction, shape->getId()};
78 }
79 return hit.fraction;
80 }
81};
82double response(physics::Body3D& body, V point, V a, V b) {
83 if (b3Body_GetType(eve::physics::box3d::Access::bodyId(body)) != b3_dynamicBody) return 0;
84 const auto r = add(point, scale(vec(b3Body_GetWorldCenterOfMass(eve::physics::box3d::Access::bodyId(body))), -1));
85 const auto inertia = b3Body_GetWorldInverseRotationalInertia(eve::physics::box3d::Access::bodyId(body));
86 return b3Body_GetInverseMass(eve::physics::box3d::Access::bodyId(body)) * dot(a, b) +
87 dot(cross(r, a), multiply(inertia, cross(r, b)));
88}
89// Numeric predictor is local to one submission; backend bodies are never mutated here.
90struct PredictedBody {
91 physics::Body3D* body;
93 b3Matrix3 inverseInertia;
95 V velocity(V point) const { return add(linear, cross(angular, add(point, scale(center, -1)))); }
96 void impulse(V point, V impulse) {
97 linear = add(linear, scale(impulse, inverseMass));
98 angular = add(angular, multiply(inverseInertia, cross(add(point, scale(center, -1)), impulse)));
99 }
100};
101struct PreparedWheel {
102 Contact contact;
104 std::size_t ground = 0;
105 std::array<double, 3> diagonal{}, impulse{};
106 double compression = 0, spring = 0, gain = 0;
107 physics::TireInput input;
108 physics::TireModel model;
109};
110} // namespace
112 std::shared_ptr<VehicleWheelRuntime>& runtime, const SimulationStep& step) {
113 using namespace physics;
114 auto pending = submissionState(runtime, step);
115 if (!pending || pending.value() != VehiclePhysicsStatus::Unavailable) return pending;
116 const auto* definition = vehicle.definition()->def;
117 auto* world = body.getWorld();
118 if (!definition || !world || !body.isValid()) return reject("Vehicle definition or spatial body is unavailable");
119 auto phase = ForceBatch::prepare(*world, {});
121 if (world->rigidBackendKind() != physics::RigidBackend3D::Box3D)
124 "Ray tire contact integration currently requires the Box3D backend", "vehicle.tires3d"));
125 const auto& config = definition->suspension;
126 const auto input = *vehicle.input();
127 const double dt = step.delta.seconds(), mass = body.getMass();
128 if (!positive(dt) || dt > .05 || !positive(mass) || !nonnegative(definition->maxSpeed) ||
129 !nonnegative(definition->accel) || !nonnegative(config.maxTravel) || !nonnegative(config.driveForce) ||
130 !nonnegative(config.brakeTorque) || !nonnegative(config.maxSteerAngle) || config.maxSteerAngle > 1.4 ||
131 !std::isfinite(input.throttle) || !std::isfinite(input.steer) || !std::isfinite(input.brake))
132 return reject("Invalid spatial tire input, suspension travel or fixed duration");
133 auto wheels = config.wheels;
134 if (wheels.empty()) {
135 if (!positive(definition->radius))
136 return reject("Default spatial wheel layout requires a positive chassis size");
137 for (int x : {-1, 1})
138 for (int z : {-1, 1}) {
139 SuspensionWheel wheel;
140 wheel.x = float(x) * definition->radius * .45f;
141 wheel.z = float(z) * definition->radius * .6f;
142 wheel.y = -.175f;
143 wheel.steer = z > 0;
144 wheels.push_back(wheel);
145 }
146 }
147 std::vector<VehicleEntity::SuspensionState::WheelState> candidate(wheels.size());
148 if (vehicle.suspension()->wheels.size() == wheels.size()) candidate = vehicle.suspension()->wheels;
149 const double count = static_cast<double>(wheels.size());
150 const auto driven =
151 static_cast<std::size_t>(std::count_if(wheels.begin(), wheels.end(), [](const auto& w) { return w.drive; }));
152 const auto up = vec(b3Body_GetWorldVector(eve::physics::box3d::Access::bodyId(body), {0, 1, 0}));
153 if (!finite(up)) return reject("Invalid suspension orientation");
154 auto chassisLink = PhysicsLink::fromBody(body);
155 if (!chassisLink) return Result<VehiclePhysicsStatus>::failure(chassisLink.status());
156 std::vector<ForceLoad> loads;
157 loads.reserve(wheels.size() * 2);
158 std::vector<PredictedBody> predicted;
159 auto predict = [&](physics::Body3D& source) {
160 for (std::size_t i = 0; i < predicted.size(); ++i)
161 if (predicted[i].body == &source) return i;
163 const bool dynamic = b3Body_GetType(raw) == b3_dynamicBody;
164 const V center = vec(b3Body_GetWorldCenterOfMass(raw));
165 V linear = vec(b3Body_GetLinearVelocity(raw)), angular = vec(b3Body_GetAngularVelocity(raw));
166 if (dynamic)
167 linear = add(linear, scale(V{world->getGravityX(), world->getGravityY(), world->getGravityZ()},
168 dt * source.getGravityScale()));
169 predicted.push_back({&source, center, linear, angular, linear, angular,
170 dynamic ? b3Body_GetWorldInverseRotationalInertia(raw) : b3Matrix3{},
171 dynamic ? b3Body_GetInverseMass(raw) : 0});
172 return predicted.size() - 1;
173 };
174 predict(body);
175 std::vector<PreparedWheel> contacts;
176 contacts.reserve(wheels.size());
177 for (std::size_t i = 0; i < wheels.size(); ++i) {
178 const auto& wheel = wheels[i];
179 const V localMount{wheel.x, double(wheel.y) + wheel.restLength, wheel.z};
180 const double rayLength = double(wheel.restLength) + wheel.radius + config.maxTravel;
181 if (!fits(localMount) || !positive(wheel.radius) || !nonnegative(wheel.restLength) ||
182 !nonnegative(wheel.stiffness) || !nonnegative(wheel.damping) || !positive(rayLength))
183 return reject("Invalid spatial wheel geometry or spring parameters");
184 const auto mount = b3Body_GetWorldPoint(eve::physics::box3d::Access::bodyId(body), native(localMount));
185 const auto translation = scale(up, -rayLength);
186 if (!fits(vec(mount)) || !fits(translation) || !fits(add(vec(mount), translation)))
187 return reject("Suspension ray exceeds supported coordinate range");
188 RayContext ray{body, up, {}};
189 b3World_CastRay(eve::physics::box3d::Access::worldId(*world), mount, native(translation),
190 b3DefaultQueryFilter(), &RayContext::collect, &ray);
191 const auto& contact = ray.contact;
192 const double steer = wheel.steer ? std::clamp(double(input.steer), -1.0, 1.0) * config.maxSteerAngle : 0;
193 auto forward = vec(b3Body_GetWorldVector(eve::physics::box3d::Access::bodyId(body),
194 {float(std::sin(steer)), 0, float(std::cos(steer))}));
195 V normal = contact.ground ? contact.normal : up;
196 forward = add(forward, scale(normal, -dot(forward, normal)));
197 const double norm = length(forward);
198 if (!positive(norm) || norm < 1e-6) return reject("Wheel heading is perpendicular to the contact plane");
199 forward = scale(forward, 1 / norm);
200 const auto lateral = cross(normal, forward);
201 const V point = contact.ground ? contact.point : vec(mount);
202 auto relative = vec(b3Body_GetWorldPointVelocity(eve::physics::box3d::Access::bodyId(body),
203 {float(point.x), float(point.y), float(point.z)}));
204 if (contact.ground) {
205 relative = add(relative,
206 scale(vec(b3Body_GetWorldPointVelocity(eve::physics::box3d::Access::bodyId(*contact.ground),
207 {float(point.x), float(point.y), float(point.z)})),
208 -1));
209 const auto conveyor = vec(contact.material.tangentVelocity);
210 relative = add(relative, scale(add(conveyor, scale(normal, -dot(conveyor, normal))), -1));
211 }
212 std::array<V, 3> axes{forward, lateral, normal};
213 double matrix[3][3]{};
214 for (int a = 0; a < 3; ++a)
215 for (int b = 0; b < 3; ++b) {
216 matrix[a][b] = response(body, point, axes[a], axes[b]);
217 if (contact.ground) matrix[a][b] += response(*contact.ground, point, axes[a], axes[b]);
218 if (!std::isfinite(matrix[a][b])) return reject("Invalid spatial contact inertia");
219 }
220 double diagonal[3]{};
221 for (int a = 0; a < 3; ++a) {
222 diagonal[a] = matrix[a][a];
223 for (int b = 0; b < 3; ++b)
224 if (b != a) diagonal[a] += std::abs(matrix[a][b]);
225 diagonal[a] *= count;
226 if (!nonnegative(diagonal[a])) return reject("Invalid contact response bound");
227 }
228 PreparedWheel prepared;
229 prepared.contact = contact;
230 prepared.point = point;
231 prepared.forward = forward;
232 prepared.lateral = lateral;
233 prepared.normal = normal;
234 prepared.diagonal = {diagonal[0], diagonal[1], diagonal[2]};
235 if (contact.ground) {
236 prepared.ground = predict(*contact.ground);
237 const auto conveyor = vec(contact.material.tangentVelocity);
238 prepared.conveyor = add(conveyor, scale(normal, -dot(conveyor, normal)));
239 prepared.compression = std::clamp(double(wheel.restLength) - (contact.fraction * rayLength - wheel.radius),
240 0.0, double(config.maxTravel));
241 const double alpha = dot(normal, up);
242 prepared.spring = wheel.stiffness * prepared.compression / alpha;
243 prepared.gain = (wheel.damping + wheel.stiffness * dt) / (alpha * alpha);
244 }
245 prepared.input.angularVelocity = candidate[i].angularVelocity;
246 prepared.input.longitudinalVelocity = dot(relative, forward);
247 prepared.input.lateralVelocity = dot(relative, lateral);
248 prepared.input.longitudinalInverseMass = diagonal[0];
249 prepared.input.lateralInverseMass = diagonal[1];
250 driveInputs(prepared.input, config, input, wheel, driven, definition->maxSpeed,
251 std::min(double(config.driveForce), mass * definition->accel));
252 prepared.model = model(config, wheel.radius);
253 if (contact.ground)
254 prepared.model.friction = std::min(prepared.model.friction, double(contact.material.friction));
255 contacts.push_back(prepared);
256 }
257 // Bounded Jacobi iterations use the diagonal majorant as a preconditioner.
258 // Every sample starts with the original wheel speed: drive/brake torque is integrated once.
259 for (int iteration = 0; iteration < 64; ++iteration) {
260 for (std::size_t i = 0; i < contacts.size(); ++i) {
261 auto& c = contacts[i];
262 V relative = predicted[0].velocity(c.point);
263 if (c.contact.ground) relative = add(relative, scale(predicted[c.ground].velocity(c.point), -1));
264 relative = add(relative, scale(c.conveyor, -1));
265 const double vn = dot(relative, c.normal) - c.diagonal[2] * c.impulse[2];
266 const double load =
267 c.contact.ground ? std::max(0.0, (c.spring - c.gain * vn) / (1 + dt * c.gain * c.diagonal[2])) : 0;
268 if (!nonnegative(load)) return reject("Suspension force is not representable");
269 auto ti = c.input;
270 ti.longitudinalVelocity = dot(relative, c.forward) - c.diagonal[0] * c.impulse[0];
271 ti.lateralVelocity = dot(relative, c.lateral) - c.diagonal[1] * c.impulse[1];
272 ti.normalLoad = load;
273 auto sampled = ForceModels::tire(c.model, ti, dt);
274 if (!sampled) return Result<VehiclePhysicsStatus>::failure(sampled.status());
275 const auto& value = sampled.value();
276 c.impulse = {value.longitudinalForce * dt, value.lateralForce * dt, load * dt};
277 auto& state = candidate[i];
278 state.angularVelocity = value.angularVelocity;
279 state.longitudinalForce = value.longitudinalForce;
280 state.lateralForce = value.lateralForce;
281 state.slipRatio = value.slipRatio;
282 state.slipAngle = value.slipAngle;
283 state.normalLoad = load;
284 state.prevCompression = float(c.compression);
285 state.grounded = load > 0;
286 }
287 for (auto& value : predicted) {
288 value.linear = value.freeLinear;
289 value.angular = value.freeAngular;
290 }
291 for (const auto& c : contacts) {
292 const auto impulse =
293 add(scale(c.normal, c.impulse[2]), add(scale(c.forward, c.impulse[0]), scale(c.lateral, c.impulse[1])));
294 predicted[0].impulse(c.point, impulse);
295 if (c.contact.ground) predicted[c.ground].impulse(c.point, scale(impulse, -1));
296 }
297 }
298 for (const auto& c : contacts) {
299 const auto force = scale(
300 add(scale(c.normal, c.impulse[2]), add(scale(c.forward, c.impulse[0]), scale(c.lateral, c.impulse[1]))),
301 1 / dt);
302 loads.push_back({chassisLink.value(), force, c.point, {}});
303 if (c.contact.ground && predicted[c.ground].inverseMass > 0) {
304 auto link = PhysicsLink::fromBody(*c.contact.ground);
305 if (!link) return Result<VehiclePhysicsStatus>::failure(link.status());
306 loads.push_back({link.value(), scale(force, -1), c.point, {}});
307 }
308 }
309 auto batch = ForceBatch::prepare(*world, loads);
310 if (!batch) return Result<VehiclePhysicsStatus>::failure(batch.status());
311 return commit(*world, batch.value(), runtime, std::move(candidate), step);
312}
313} // namespace eve::vehicle::tire_detail
double z
double m[16]
double x
float w
Definition AnimClip.cpp:738
Vec3 relative
Definition AnimSmr.cpp:164
double lateral
std::vector< QuestEvent > pending
b3Matrix3 inverseInertia
b3Vec3 angular
bool dynamic
float inverseMass
double raw
EvpackChunkInput input
Definition Evpack.cpp:170
int triangle
Definition FluidSdf.cpp:554
ForceVector force
float inertia
float linear
std::string message
ShaderImageInput shape
glm::vec3 n
Definition Grass.cpp:63
double r
float v
HexVec3 up
std::int32_t c
float length
PhysicsJointLink link
std::string local
std::array< float, 3 > scale
std::string response
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
Texture * normal
glm::dvec2 center
glm::dvec3 velocity
double dt
bool finite
std::array< uint32_t, 16 > material
bool diagonal
bool hit
std::string body
Object::Ptr value
std::string slot
glm::mat4 model
Heightmap ground
glm::dmat4 matrix
std::array< std::array< double, 3 >, 3 > axes
std::string_view source
int count
float phase
int limit
Definition TreeMesh.cpp:166
float step
Definition TreeMesh.cpp:451
const VegetationPresetContext & context
V freeAngular
float fraction
V conveyor
Contact contact
V forward
int shapeId
std::array< double, 3 > impulse
double spring
double compression
double gain
physics::Body3D & chassis
V freeLinear
glm::vec3 point
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
Backend-neutral 3D rigid body in meter-space coordinates (+Y up by convention). Owned by a World3D; c...
Definition Body3D.h:31
载具实体:数据全部在组件里,行为在 VehicleSystem。
ForceVector add(ForceVector a, ForceVector b)
Definition ForceMath.h:13
double dot(ForceVector a, ForceVector b)
Definition ForceMath.h:14
V3 cross(V3 a, V3 b)
Module-private road bake implementation helper.
Definition RoadBake.cpp:29
Result< VehiclePhysicsStatus > submissionState(const std::shared_ptr< VehicleWheelRuntime > &runtime, const SimulationStep &step)
Result< VehiclePhysicsStatus > commit(physics::World &world, physics::ForceBatch &batch, std::shared_ptr< VehicleWheelRuntime > &runtime, std::vector< VehicleEntity::SuspensionState::WheelState > candidate, const SimulationStep &step)
Result< VehiclePhysicsStatus > submit3D(VehicleEntity &vehicle, physics::Body3D &body, std::shared_ptr< VehicleWheelRuntime > &runtime, const SimulationStep &step)
void driveInputs(physics::TireInput &target, const SuspensionConfig &config, const VehicleEntity::Input &input, const SuspensionWheel &wheel, std::size_t driven, double maximumSpeed, double traction)
@ Unavailable
No physics module or no attached body.
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
static b3BodyId bodyId(const Body3D &body)
Borrows the native identifier synchronously; facade must belong to a Box3D world.
static b3WorldId worldId(const World3D &world)
Internal checked Box3D world ID; fails for another backend.
Wheel mount for 3D ray suspension or 2D top-down tire contact.
float x
Local mount in meters: 3D uses +Y up; top-down 2D uses XY with z = 0.