载入中...
搜索中...
未找到
JoltState.cpp
浏览该文件的文档.
1// eve-hot-path
2// Jolt requires its platform header before any other native header.
3#include <Jolt/Jolt.h>
4
5// Provider implementation dependencies.
6#include <Jolt/Core/Factory.h>
7#include <Jolt/Physics/Collision/CollideShape.h>
8#include <Jolt/RegisterTypes.h>
9#include <cstdarg>
10#include <cstdio>
14namespace eve::physics::jolt {
15namespace {
16void trace(const char* format, ...) {
17 va_list arguments;
18 va_start(arguments, format);
19 std::fputs("[Jolt] ", stderr);
20 std::vfprintf(stderr, format, arguments);
21 std::fputc('\n', stderr);
22 va_end(arguments);
23}
24struct Runtime {
25 Runtime() {
26 JPH::RegisterDefaultAllocator();
27 JPH::Trace = &trace;
28#ifdef JPH_ENABLE_ASSERTS
29 JPH::AssertFailed = [](const char* expression, const char* message, const char* file, JPH::uint line) {
30 std::fprintf(stderr, "[Jolt] assertion %s at %s:%u: %s\n", expression, file, line, message ? message : "");
31 return true;
32 };
33#endif
34 JPH::Factory::sInstance = new JPH::Factory;
35 JPH::RegisterTypes();
36 }
37 ~Runtime() {
38 JPH::UnregisterTypes();
39 delete JPH::Factory::sInstance;
40 JPH::Factory::sInstance = nullptr;
41 }
42};
43float combine(float a, float b, uint64_t policyA, uint64_t policyB, int shift, bool friction) {
44 switch (std::max((policyA >> shift) & 7, (policyB >> shift) & 7)) {
45 case 1: return .5f * (a + b);
46 case 2: return std::min(a, b);
47 case 3: return a * b;
48 case 4: return std::max(a, b);
49 default: return friction ? std::sqrt(a * b) : std::max(a, b);
50 }
51}
52void configure(const JPH::Body& a, const JPH::Body& b, const JPH::ContactManifold& m, JPH::ContactSettings& settings) {
53 auto* sa = child(a, m.mSubShapeID1);
54 auto* sb = child(b, m.mSubShapeID2);
55 if (!sa || !sb) return;
56 const auto ma = contactMaterial(a, m.mSubShapeID1, *sa);
57 const auto mb = contactMaterial(b, m.mSubShapeID2, *sb);
58 auto velocity = [](const JPH::Body& body, const ShapeState& shape, const SurfaceMaterial3D& material) {
59 const auto& g = shape.geometry;
60 return body.GetRotation() *
61 (JPH::Quat(g.localQx, g.localQy, g.localQz, g.localQw).Normalized() *
62 JPH::Vec3(material.tangentVelocity.x, material.tangentVelocity.y, material.tangentVelocity.z));
63 };
64 settings.mRelativeLinearSurfaceVelocity = velocity(b, *sb, mb) - velocity(a, *sa, ma);
65 const auto point = m.GetWorldSpaceContactPointOn1(0);
66 const auto normal = m.mWorldSpaceNormal;
67 settings.mIsSensor = sa->sensor || sb->sensor || !sa->owner || !sb->owner ||
68 !WorldBackend::isContactAllowed(*sa->owner, *sb->owner, point.GetX(), point.GetY(),
69 point.GetZ(), normal.GetX(), normal.GetY(), normal.GetZ());
70 settings.mCombinedFriction = combine(ma.friction, mb.friction, ma.userMaterialId, mb.userMaterialId, 32, true);
71 settings.mCombinedRestitution =
72 combine(ma.restitution, mb.restitution, ma.userMaterialId, mb.userMaterialId, 35, false);
73 const auto radius = [](const ShapeState& shape) {
74 if (shape.geometry.kind == ShapeKind3D::Sphere) return shape.geometry.a;
75 if (shape.geometry.kind == ShapeKind3D::Capsule) return shape.geometry.b;
76 if (shape.geometry.kind == ShapeKind3D::Box || shape.geometry.kind == ShapeKind3D::ConvexHull)
77 return .25f * shape.native->GetInnerRadius();
78 return 0.f;
79 };
80 settings.mCombinedRollingResistance =
81 std::max(ma.rollingResistance, mb.rollingResistance) * std::max(radius(*sa), radius(*sb));
82}
83} // namespace
84void initializeRuntime() { static Runtime runtime; }
85State::State(float x, float y, float z, bool allowSleep) : sleep(allowSleep) {
86 system.Init(16384, 0, 65536, 16384, layers, layers, layers);
87 system.SetGravity({x, y, z});
88 listener = std::make_unique<Listener>();
89 listener->state = this;
90 system.SetContactListener(listener.get());
91 system.AddStepListener(listener.get());
92}
94 system.RemoveStepListener(listener.get());
95 system.SetContactListener(nullptr);
96}
97void Listener::OnStep(const JPH::PhysicsStepListenerContext&) {
98 ++substep;
99 // Jolt owns all body/constraint locks here. Never call the locking BodyInterface.
100 for (const auto& weak : state->joints)
101 if (auto joint = weak.lock(); joint && joint->alive && joint->native &&
102 (joint->kind == JointKind3D::Motor || joint->kind == JointKind3D::Spherical)) {
103 auto& constraint = joint->velocity ? *joint->velocity : static_cast<JPH::SixDOFConstraint&>(*joint->native);
104 const auto frame =
105 constraint.GetBody1()->GetCenterOfMassTransform() * constraint.GetConstraintToBody1Matrix();
106 constraint.SetTargetAngularVelocityCS(frame.Multiply3x3Transposed(joint->worldAngularVelocity));
107 if (joint->kind == JointKind3D::Motor)
108 constraint.SetTargetVelocityCS(frame.Multiply3x3Transposed(joint->worldLinearVelocity));
109 }
110}
111JPH::ValidateResult Listener::OnContactValidate(const JPH::Body& a, const JPH::Body& b, JPH::RVec3Arg,
112 const JPH::CollideShapeResult& result) {
113 if (state->suppressedPairs.contains(pairKey(a.GetID(), b.GetID())))
114 return JPH::ValidateResult::RejectAllContactsForThisBodyPair;
115 const auto* sa = child(a, result.mSubShapeID1);
116 const auto* sb = child(b, result.mSubShapeID2);
117 if (!sa || !sb || !sa->owner || !sb->owner || !WorldBackend::isPairAllowed(*sa->owner, *sb->owner))
118 return JPH::ValidateResult::RejectContact;
119 const auto& fa = sa->filter;
120 const auto& fb = sb->filter;
121 bool accept = fa.groupIndex && fa.groupIndex == fb.groupIndex
122 ? fa.groupIndex > 0
123 : (fa.maskBits & fb.categoryBits) && (fb.maskBits & fa.categoryBits);
124 return accept ? JPH::ValidateResult::AcceptContact : JPH::ValidateResult::RejectContact;
125}
126void Listener::OnContactAdded(const JPH::Body& a, const JPH::Body& b, const JPH::ContactManifold& m,
127 JPH::ContactSettings& settings) {
128 configure(a, b, m, settings);
129 auto* sa = child(a, m.mSubShapeID1);
130 auto* sb = child(b, m.mSubShapeID2);
131 if (!sa || !sb || !sa->owner || !sb->owner) return;
132 auto ba = sa->body.lock();
133 auto bb = sb->body.lock();
134 if (!ba || !bb || !ba->owner || !bb->owner || (settings.mIsSensor && !sa->sensor && !sb->sensor)) return;
135 ContactPair pair{ba->owner->getId(), sa->owner->getId(), sa->owner->getTag(), bb->owner->getId(),
136 sb->owner->getId(), sb->owner->getTag(), sa->sensor, sb->sensor};
137 contacts.insert_or_assign(JPH::SubShapeIDPair(a.GetID(), m.mSubShapeID1, b.GetID(), m.mSubShapeID2), pair);
138 begins.push_back(pair);
139}
140void Listener::OnContactPersisted(const JPH::Body& a, const JPH::Body& b, const JPH::ContactManifold& m,
141 JPH::ContactSettings& settings) {
142 const JPH::SubShapeIDPair key(a.GetID(), m.mSubShapeID1, b.GetID(), m.mSubShapeID2);
143 configure(a, b, m, settings);
144 const auto* sa = child(a, m.mSubShapeID1);
145 const auto* sb = child(b, m.mSubShapeID2);
146 if (settings.mIsSensor && sa && sb && !sa->sensor && !sb->sensor) {
148 } else if (!contacts.contains(key)) {
150 }
151}
152void Listener::OnContactRemoved(const JPH::SubShapeIDPair& key) {
153 auto i = contacts.find(key);
154 if (i != contacts.end()) {
155 ends.push_back(i->second);
156 contacts.erase(i);
157 }
158}
159} // namespace eve::physics::jolt
double z
double y
double m[16]
double x
Trace trace
Definition Agent.cpp:50
SQObjectPtr key
Definition ECS.cpp:155
float friction
std::string message
tensor::Graph g
Definition GpuGraph.cpp:7
ShaderImageInput shape
Poco::JSON::Object::Ptr result
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
Texture * normal
OceanWakeSettings settings
ssq::Object frame
glm::dvec3 velocity
std::array< uint32_t, 16 > material
std::string file
std::string body
SceneSpatialConstraint constraint
unsigned line
glm::vec3 point
static bool isPairAllowed(const Shape3D &, const Shape3D &)
Reads explicit body/shape pair exclusions for solid and sensor contacts without callbacks.
static bool isContactAllowed(const Shape3D &, const Shape3D &, double, double, double, float, float, float)
Reads built-in pair overrides and prepared one-way planes synchronously; no user callbacks or locks.
void initializeRuntime()
Initializes the process-owned allocator and type factory before constructing any native members.
Definition JoltState.cpp:84
SurfaceMaterial3D contactMaterial(const JPH::Body &, const JPH::SubShapeID &, const ShapeState &)
Definition JoltMesh.cpp:96
ShapeState * child(const JPH::Body &body, const JPH::SubShapeID &id)
Resolves a native child record for a synchronous callback or query. @ownership Borrowed from the worl...
JPH::uint64 pairKey(JPH::BodyID a, JPH::BodyID b)
Counts suppression references for one native pair; sequence numbers prevent reuse aliases.
Definition JoltJoint.cpp:8
std::unordered_map< JPH::SubShapeIDPair, ContactPair > contacts
JPH::ValidateResult OnContactValidate(const JPH::Body &, const JPH::Body &, JPH::RVec3Arg, const JPH::CollideShapeResult &) override
void OnContactAdded(const JPH::Body &, const JPH::Body &, const JPH::ContactManifold &, JPH::ContactSettings &) override
std::vector< ContactPair > begins
std::vector< ContactPair > ends
void OnContactRemoved(const JPH::SubShapeIDPair &) override
void OnStep(const JPH::PhysicsStepListenerContext &) override
Definition JoltState.cpp:97
void OnContactPersisted(const JPH::Body &, const JPH::Body &, const JPH::ContactManifold &, JPH::ContactSettings &) override
std::unordered_map< JPH::uint64, int > suppressedPairs
JPH::PhysicsSystem system
State(float, float, float, bool)
Definition JoltState.cpp:85
std::unique_ptr< Listener > listener
std::vector< std::weak_ptr< JointState > > joints