Debian Codegraph @

thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/TriangleShape.cpp

raw symbols SCIP
1 // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
2 // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
3 // SPDX-License-Identifier: MIT
4
5 #include <Jolt/Jolt.h>
6
7 #include <Jolt/Physics/Collision/Shape/TriangleShape.h>
8 #include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
9 #include <Jolt/Physics/Collision/Shape/GetTrianglesContext.h>
10 #include <Jolt/Physics/Collision/RayCast.h>
11 #include <Jolt/Physics/Collision/ShapeCast.h>
12 #include <Jolt/Physics/Collision/CastResult.h>
13 #include <Jolt/Physics/Collision/CollidePointResult.h>
14 #include <Jolt/Physics/Collision/TransformedShape.h>
15 #include <Jolt/Physics/Collision/CastConvexVsTriangles.h>
16 #include <Jolt/Physics/Collision/CastSphereVsTriangles.h>
17 #include <Jolt/Physics/Collision/CollideConvexVsTriangles.h>
18 #include <Jolt/Physics/Collision/CollideSphereVsTriangles.h>
19 #include <Jolt/Physics/Collision/CollisionDispatch.h>
20 #include <Jolt/Physics/Collision/CollideSoftBodyVerticesVsTriangles.h>
21 #include <Jolt/Geometry/ConvexSupport.h>
22 #include <Jolt/Geometry/RayTriangle.h>
23 #include <Jolt/Geometry/ClosestPoint.h>
24 #include <Jolt/ObjectStream/TypeDeclarations.h>
25 #include <Jolt/Core/StreamIn.h>
26 #include <Jolt/Core/StreamOut.h>
27 #ifdef JPH_DEBUG_RENDERER
28 #include <Jolt/Renderer/DebugRenderer.h>
29 #endif // JPH_DEBUG_RENDERER
30
31 JPH_NAMESPACE_BEGIN
32
33 JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(TriangleShapeSettings)
34 {
35 JPH_ADD_BASE_CLASS(TriangleShapeSettings, ConvexShapeSettings)
36
37 JPH_ADD_ATTRIBUTE(TriangleShapeSettings, mV1)
38 JPH_ADD_ATTRIBUTE(TriangleShapeSettings, mV2)
39 JPH_ADD_ATTRIBUTE(TriangleShapeSettings, mV3)
40 JPH_ADD_ATTRIBUTE(TriangleShapeSettings, mConvexRadius)
41 }
42
43 ShapeSettings::ShapeResult TriangleShapeSettings::Create() const
44 {
45 if (mCachedResult.IsEmpty())
46 Ref<Shape> shape = new TriangleShape(*this, mCachedResult);
47 return mCachedResult;
48 }
49
50 TriangleShape::TriangleShape(const TriangleShapeSettings &inSettings, ShapeResult &outResult) :
51 ConvexShape(EShapeSubType::Triangle, inSettings, outResult),
52 mV1(inSettings.mV1),
53 mV2(inSettings.mV2),
54 mV3(inSettings.mV3),
55 mConvexRadius(inSettings.mConvexRadius)
56 {
57 if (inSettings.mConvexRadius < 0.0f)
58 {
59 outResult.SetError("Invalid convex radius");
60 return;
61 }
62
63 outResult.Set(this);
64 }
65
66 AABox TriangleShape::GetLocalBounds() const
67 {
68 AABox bounds(mV1, mV1);
69 bounds.Encapsulate(mV2);
70 bounds.Encapsulate(mV3);
71 bounds.ExpandBy(Vec3::sReplicate(mConvexRadius));
72 return bounds;
73 }
74
75 AABox TriangleShape::GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
76 {
77 JPH_ASSERT(IsValidScale(inScale));
78
79 Vec3 v1 = inCenterOfMassTransform * (inScale * mV1);
80 Vec3 v2 = inCenterOfMassTransform * (inScale * mV2);
81 Vec3 v3 = inCenterOfMassTransform * (inScale * mV3);
82
83 AABox bounds(v1, v1);
84 bounds.Encapsulate(v2);
85 bounds.Encapsulate(v3);
86 bounds.ExpandBy(inScale * mConvexRadius);
87 return bounds;
88 }
89
90 class TriangleShape::TriangleNoConvex final : public Support
91 {
92 public:
93 TriangleNoConvex(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3) :
94 mTriangleSupport(inV1, inV2, inV3)
95 {
96 static_assert(sizeof(TriangleNoConvex) <= sizeof(SupportBuffer), "Buffer size too small");
97 JPH_ASSERT(IsAligned(this, alignof(TriangleNoConvex)));
98 }
99
100 virtual Vec3 GetSupport(Vec3Arg inDirection) const override
101 {
102 return mTriangleSupport.GetSupport(inDirection);
103 }
104
105 virtual float GetConvexRadius() const override
106 {
107 return 0.0f;
108 }
109
110 private:
111 TriangleConvexSupport mTriangleSupport;
112 };
113
114 class TriangleShape::TriangleWithConvex final : public Support
115 {
116 public:
117 TriangleWithConvex(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3, float inConvexRadius) :
118 mConvexRadius(inConvexRadius),
119 mTriangleSupport(inV1, inV2, inV3)
120 {
121 static_assert(sizeof(TriangleWithConvex) <= sizeof(SupportBuffer), "Buffer size too small");
122 JPH_ASSERT(IsAligned(this, alignof(TriangleWithConvex)));
123 }
124
125 virtual Vec3 GetSupport(Vec3Arg inDirection) const override
126 {
127 Vec3 support = mTriangleSupport.GetSupport(inDirection);
128 float len = inDirection.Length();
129 if (len > 0.0f)
130 support += (mConvexRadius / len) * inDirection;
131 return support;
132 }
133
134 virtual float GetConvexRadius() const override
135 {
136 return mConvexRadius;
137 }
138
139 private:
140 float mConvexRadius;
141 TriangleConvexSupport mTriangleSupport;
142 };
143
144 const ConvexShape::Support *TriangleShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
145 {
146 switch (inMode)
147 {
148 case ESupportMode::IncludeConvexRadius:
149 case ESupportMode::Default:
150 if (mConvexRadius > 0.0f)
151 return new (&inBuffer) TriangleWithConvex(inScale * mV1, inScale * mV2, inScale * mV3, mConvexRadius);
152 [[fallthrough]];
153
154 case ESupportMode::ExcludeConvexRadius:
155 return new (&inBuffer) TriangleNoConvex(inScale * mV1, inScale * mV2, inScale * mV3);
156 }
157
158 JPH_ASSERT(false);
159 return nullptr;
160 }
161
162 void TriangleShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
163 {
164 JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
165
166 // Calculate transform with scale
167 Mat44 transform = inCenterOfMassTransform.PreScaled(inScale);
168
169 // Flip triangle if scaled inside out
170 if (ScaleHelpers::IsInsideOut(inScale))
171 {
172 outVertices.push_back(transform * mV1);
173 outVertices.push_back(transform * mV3);
174 outVertices.push_back(transform * mV2);
175 }
176 else
177 {
178 outVertices.push_back(transform * mV1);
179 outVertices.push_back(transform * mV2);
180 outVertices.push_back(transform * mV3);
181 }
182 }
183
184 MassProperties TriangleShape::GetMassProperties() const
185 {
186 // We cannot calculate the volume for a triangle, so we return invalid mass properties.
187 // If you want your triangle to be dynamic, then you should provide the mass properties yourself when
188 // creating a Body:
189 //
190 // BodyCreationSettings::mOverrideMassProperties = EOverrideMassProperties::MassAndInertiaProvided;
191 // BodyCreationSettings::mMassPropertiesOverride.SetMassAndInertiaOfSolidBox(Vec3::sOne(), 1000.0f);
192 //
193 // Note that this makes the triangle shape behave the same as a mesh shape with a single triangle.
194 // In practice there is very little use for a dynamic triangle shape as back side collisions will be ignored
195 // so if the triangle falls the wrong way it will sink through the floor.
196 return MassProperties();
197 }
198
199 Vec3 TriangleShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
200 {
201 JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
202
203 Vec3 cross = (mV2 - mV1).Cross(mV3 - mV1);
204 float len = cross.Length();
205 return len != 0.0f? cross / len : Vec3::sAxisY();
206 }
207
208 void TriangleShape::GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const
209 {
210 // A triangle has no volume
211 outTotalVolume = outSubmergedVolume = 0.0f;
212 outCenterOfBuoyancy = Vec3::sZero();
213 }
214
215 #ifdef JPH_DEBUG_RENDERER
216 void TriangleShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
217 {
218 RVec3 v1 = inCenterOfMassTransform * (inScale * mV1);
219 RVec3 v2 = inCenterOfMassTransform * (inScale * mV2);
220 RVec3 v3 = inCenterOfMassTransform * (inScale * mV3);
221
222 if (ScaleHelpers::IsInsideOut(inScale))
223 std::swap(v1, v2);
224
225 if (inDrawWireframe)
226 inRenderer->DrawWireTriangle(v1, v2, v3, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor);
227 else
228 inRenderer->DrawTriangle(v1, v2, v3, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor);
229 }
230 #endif // JPH_DEBUG_RENDERER
231
232 bool TriangleShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
233 {
234 float fraction = RayTriangle(inRay.mOrigin, inRay.mDirection, mV1, mV2, mV3);
235 if (fraction < ioHit.mFraction)
236 {
237 ioHit.mFraction = fraction;
238 ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID();
239 return true;
240 }
241 return false;
242 }
243
244 void TriangleShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const
245 {
246 // Test shape filter
247 if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
248 return;
249
250 // Back facing check
251 if (inRayCastSettings.mBackFaceModeTriangles == EBackFaceMode::IgnoreBackFaces && (mV2 - mV1).Cross(mV3 - mV1).Dot(inRay.mDirection) > 0.0f)
252 return;
253
254 // Test ray against triangle
255 float fraction = RayTriangle(inRay.mOrigin, inRay.mDirection, mV1, mV2, mV3);
256 if (fraction < ioCollector.GetEarlyOutFraction())
257 {
258 // Better hit than the current hit
259 RayCastResult hit;
260 hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext());
261 hit.mFraction = fraction;
262 hit.mSubShapeID2 = inSubShapeIDCreator.GetID();
263 ioCollector.AddHit(hit);
264 }
265 }
266
267 void TriangleShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
268 {
269 // Can't be inside a triangle
270 }
271
272 void TriangleShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const CollideSoftBodyVertexIterator &inVertices, uint inNumVertices, int inCollidingShapeIndex) const
273 {
274 CollideSoftBodyVerticesVsTriangles collider(inCenterOfMassTransform, inScale);
275
276 for (CollideSoftBodyVertexIterator v = inVertices, sbv_end = inVertices + inNumVertices; v != sbv_end; ++v)
277 if (v.GetInvMass() > 0.0f)
278 {
279 collider.StartVertex(v);
280 collider.ProcessTriangle(mV1, mV2, mV3);
281 collider.FinishVertex(v, inCollidingShapeIndex);
282 }
283 }
284
285 void TriangleShape::sCollideConvexVsTriangle(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, [[maybe_unused]] const ShapeFilter &inShapeFilter)
286 {
287 JPH_ASSERT(inShape1->GetType() == EShapeType::Convex);
288 const ConvexShape *shape1 = static_cast<const ConvexShape *>(inShape1);
289 JPH_ASSERT(inShape2->GetSubType() == EShapeSubType::Triangle);
290 const TriangleShape *shape2 = static_cast<const TriangleShape *>(inShape2);
291
292 CollideConvexVsTriangles collider(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
293 collider.Collide(shape2->mV1, shape2->mV2, shape2->mV3, 0b111, inSubShapeIDCreator2.GetID());
294 }
295
296 void TriangleShape::sCollideSphereVsTriangle(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, [[maybe_unused]] const ShapeFilter &inShapeFilter)
297 {
298 JPH_ASSERT(inShape1->GetSubType() == EShapeSubType::Sphere);
299 const SphereShape *shape1 = static_cast<const SphereShape *>(inShape1);
300 JPH_ASSERT(inShape2->GetSubType() == EShapeSubType::Triangle);
301 const TriangleShape *shape2 = static_cast<const TriangleShape *>(inShape2);
302
303 CollideSphereVsTriangles collider(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
304 collider.Collide(shape2->mV1, shape2->mV2, shape2->mV3, 0b111, inSubShapeIDCreator2.GetID());
305 }
306
307 void TriangleShape::sCastConvexVsTriangle(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, [[maybe_unused]] const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector)
308 {
309 JPH_ASSERT(inShape->GetSubType() == EShapeSubType::Triangle);
310 const TriangleShape *shape = static_cast<const TriangleShape *>(inShape);
311
312 CastConvexVsTriangles caster(inShapeCast, inShapeCastSettings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
313 caster.Cast(shape->mV1, shape->mV2, shape->mV3, 0b111, inSubShapeIDCreator2.GetID());
314 }
315
316 void TriangleShape::sCastSphereVsTriangle(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, [[maybe_unused]] const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector)
317 {
318 JPH_ASSERT(inShape->GetSubType() == EShapeSubType::Triangle);
319 const TriangleShape *shape = static_cast<const TriangleShape *>(inShape);
320
321 CastSphereVsTriangles caster(inShapeCast, inShapeCastSettings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
322 caster.Cast(shape->mV1, shape->mV2, shape->mV3, 0b111, inSubShapeIDCreator2.GetID());
323 }
324
325 class TriangleShape::TSGetTrianglesContext
326 {
327 public:
328 TSGetTrianglesContext(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3) : mV1(inV1), mV2(inV2), mV3(inV3) { }
329
330 Vec3 mV1;
331 Vec3 mV2;
332 Vec3 mV3;
333
334 bool mIsDone = false;
335 };
336
337 void TriangleShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
338 {
339 static_assert(sizeof(TSGetTrianglesContext) <= sizeof(GetTrianglesContext), "GetTrianglesContext too small");
340 JPH_ASSERT(IsAligned(&ioContext, alignof(TSGetTrianglesContext)));
341
342 Mat44 m = Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(inScale);
343
344 new (&ioContext) TSGetTrianglesContext(m * mV1, m * mV2, m * mV3);
345 }
346
347 int TriangleShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
348 {
349 static_assert(cGetTrianglesMinTrianglesRequested >= 3, "cGetTrianglesMinTrianglesRequested is too small");
350 JPH_ASSERT(inMaxTrianglesRequested >= cGetTrianglesMinTrianglesRequested);
351
352 TSGetTrianglesContext &context = (TSGetTrianglesContext &)ioContext;
353
354 // Only return the triangle the 1st time
355 if (context.mIsDone)
356 return 0;
357 context.mIsDone = true;
358
359 // Store triangle
360 context.mV1.StoreFloat3(outTriangleVertices);
361 context.mV2.StoreFloat3(outTriangleVertices + 1);
362 context.mV3.StoreFloat3(outTriangleVertices + 2);
363
364 // Store material
365 if (outMaterials != nullptr)
366 *outMaterials = GetMaterial();
367
368 return 1;
369 }
370
371 void TriangleShape::SaveBinaryState(StreamOut &inStream) const
372 {
373 ConvexShape::SaveBinaryState(inStream);
374
375 inStream.Write(mV1);
376 inStream.Write(mV2);
377 inStream.Write(mV3);
378 inStream.Write(mConvexRadius);
379 }
380
381 void TriangleShape::RestoreBinaryState(StreamIn &inStream)
382 {
383 ConvexShape::RestoreBinaryState(inStream);
384
385 inStream.Read(mV1);
386 inStream.Read(mV2);
387 inStream.Read(mV3);
388 inStream.Read(mConvexRadius);
389 }
390
391 bool TriangleShape::IsValidScale(Vec3Arg inScale) const
392 {
393 return ConvexShape::IsValidScale(inScale) && (mConvexRadius == 0.0f || ScaleHelpers::IsUniformScale(inScale.Abs()));
394 }
395
396 Vec3 TriangleShape::MakeScaleValid(Vec3Arg inScale) const
397 {
398 Vec3 scale = ScaleHelpers::MakeNonZeroScale(inScale);
399
400 if (mConvexRadius == 0.0f)
401 return scale;
402
403 return scale.GetSign() * ScaleHelpers::MakeUniformScale(scale.Abs());
404 }
405
406 void TriangleShape::sRegister()
407 {
408 ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Triangle);
409 f.mConstruct = []() -> Shape * { return new TriangleShape; };
410 f.mColor = Color::sGreen;
411
412 for (EShapeSubType s : sConvexSubShapeTypes)
413 {
414 CollisionDispatch::sRegisterCollideShape(s, EShapeSubType::Triangle, sCollideConvexVsTriangle);
415 CollisionDispatch::sRegisterCastShape(s, EShapeSubType::Triangle, sCastConvexVsTriangle);
416
417 // Avoid registering triangle vs triangle as a reversed test to prevent infinite recursion
418 if (s != EShapeSubType::Triangle)
419 {
420 CollisionDispatch::sRegisterCollideShape(EShapeSubType::Triangle, s, CollisionDispatch::sReversedCollideShape);
421 CollisionDispatch::sRegisterCastShape(EShapeSubType::Triangle, s, CollisionDispatch::sReversedCastShape);
422 }
423 }
424
425 // Specialized collision functions
426 CollisionDispatch::sRegisterCollideShape(EShapeSubType::Sphere, EShapeSubType::Triangle, sCollideSphereVsTriangle);
427 CollisionDispatch::sRegisterCastShape(EShapeSubType::Sphere, EShapeSubType::Triangle, sCastSphereVsTriangle);
428 }
429
430 JPH_NAMESPACE_END