Debian Codegraph @

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

raw symbols SCIP
1 // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
2 // SPDX-FileCopyrightText: 2024 Jorrit Rouwe
3 // SPDX-License-Identifier: MIT
4
5 #include <Jolt/Jolt.h>
6
7 #include <Jolt/Physics/Collision/Shape/TaperedCylinderShape.h>
8 #include <Jolt/Physics/Collision/Shape/CylinderShape.h>
9 #include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
10 #include <Jolt/Physics/Collision/CollidePointResult.h>
11 #include <Jolt/Physics/Collision/TransformedShape.h>
12 #include <Jolt/Physics/Collision/CollideSoftBodyVertexIterator.h>
13 #include <Jolt/ObjectStream/TypeDeclarations.h>
14 #include <Jolt/Core/StreamIn.h>
15 #include <Jolt/Core/StreamOut.h>
16 #ifdef JPH_DEBUG_RENDERER
17 #include <Jolt/Renderer/DebugRenderer.h>
18 #endif // JPH_DEBUG_RENDERER
19
20 JPH_NAMESPACE_BEGIN
21
22 // Approximation of a face of the tapered cylinder
23 static const Vec3 cTaperedCylinderFace[] =
24 {
25 Vec3(0.0f, 0.0f, 1.0f),
26 Vec3(0.707106769f, 0.0f, 0.707106769f),
27 Vec3(1.0f, 0.0f, 0.0f),
28 Vec3(0.707106769f, 0.0f, -0.707106769f),
29 Vec3(-0.0f, 0.0f, -1.0f),
30 Vec3(-0.707106769f, 0.0f, -0.707106769f),
31 Vec3(-1.0f, 0.0f, 0.0f),
32 Vec3(-0.707106769f, 0.0f, 0.707106769f)
33 };
34
35 JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(TaperedCylinderShapeSettings)
36 {
37 JPH_ADD_BASE_CLASS(TaperedCylinderShapeSettings, ConvexShapeSettings)
38
39 JPH_ADD_ATTRIBUTE(TaperedCylinderShapeSettings, mHalfHeight)
40 JPH_ADD_ATTRIBUTE(TaperedCylinderShapeSettings, mTopRadius)
41 JPH_ADD_ATTRIBUTE(TaperedCylinderShapeSettings, mBottomRadius)
42 JPH_ADD_ATTRIBUTE(TaperedCylinderShapeSettings, mConvexRadius)
43 }
44
45 ShapeSettings::ShapeResult TaperedCylinderShapeSettings::Create() const
46 {
47 if (mCachedResult.IsEmpty())
48 {
49 Ref<Shape> shape;
50 if (mTopRadius == mBottomRadius)
51 {
52 // Convert to regular cylinder
53 CylinderShapeSettings settings;
54 settings.mHalfHeight = mHalfHeight;
55 settings.mRadius = mTopRadius;
56 settings.mMaterial = mMaterial;
57 settings.mConvexRadius = mConvexRadius;
58 new CylinderShape(settings, mCachedResult);
59 }
60 else
61 {
62 // Normal tapered cylinder shape
63 new TaperedCylinderShape(*this, mCachedResult);
64 }
65 }
66 return mCachedResult;
67 }
68
69 TaperedCylinderShapeSettings::TaperedCylinderShapeSettings(float inHalfHeightOfTaperedCylinder, float inTopRadius, float inBottomRadius, float inConvexRadius, const PhysicsMaterial *inMaterial) :
70 ConvexShapeSettings(inMaterial),
71 mHalfHeight(inHalfHeightOfTaperedCylinder),
72 mTopRadius(inTopRadius),
73 mBottomRadius(inBottomRadius),
74 mConvexRadius(inConvexRadius)
75 {
76 }
77
78 TaperedCylinderShape::TaperedCylinderShape(const TaperedCylinderShapeSettings &inSettings, ShapeResult &outResult) :
79 ConvexShape(EShapeSubType::TaperedCylinder, inSettings, outResult),
80 mTopRadius(inSettings.mTopRadius),
81 mBottomRadius(inSettings.mBottomRadius),
82 mConvexRadius(inSettings.mConvexRadius)
83 {
84 if (mTopRadius < 0.0f)
85 {
86 outResult.SetError("Invalid top radius");
87 return;
88 }
89
90 if (mBottomRadius < 0.0f)
91 {
92 outResult.SetError("Invalid bottom radius");
93 return;
94 }
95
96 if (inSettings.mHalfHeight <= 0.0f)
97 {
98 outResult.SetError("Invalid height");
99 return;
100 }
101
102 if (inSettings.mConvexRadius < 0.0f)
103 {
104 outResult.SetError("Invalid convex radius");
105 return;
106 }
107
108 if (inSettings.mTopRadius < inSettings.mConvexRadius)
109 {
110 outResult.SetError("Convex radius must be smaller than convex radius");
111 return;
112 }
113
114 if (inSettings.mBottomRadius < inSettings.mConvexRadius)
115 {
116 outResult.SetError("Convex radius must be smaller than bottom radius");
117 return;
118 }
119
120 // Calculate the center of mass (using wxMaxima).
121 // Radius of cross section for tapered cylinder from 0 to h:
122 // r(x):=br+x*(tr-br)/h;
123 // Area:
124 // area(x):=%pi*r(x)^2;
125 // Total volume of cylinder:
126 // volume(h):=integrate(area(x),x,0,h);
127 // Center of mass:
128 // com(br,tr,h):=integrate(x*area(x),x,0,h)/volume(h);
129 // Results:
130 // ratsimp(com(br,tr,h),br,bt);
131 // Non-tapered cylinder should have com = 0.5:
132 // ratsimp(com(r,r,h));
133 // Cone with tip at origin and height h should have com = 3/4 h
134 // ratsimp(com(0,r,h));
135 float h = 2.0f * inSettings.mHalfHeight;
136 float tr = mTopRadius;
137 float tr2 = Square(tr);
138 float br = mBottomRadius;
139 float br2 = Square(br);
140 float com = h * (3 * tr2 + 2 * br * tr + br2) / (4.0f * (tr2 + br * tr + br2));
141 mTop = h - com;
142 mBottom = -com;
143
144 outResult.Set(this);
145 }
146
147 class TaperedCylinderShape::TaperedCylinder final : public Support
148 {
149 public:
150 TaperedCylinder(float inTop, float inBottom, float inTopRadius, float inBottomRadius, float inConvexRadius) :
151 mTop(inTop),
152 mBottom(inBottom),
153 mTopRadius(inTopRadius),
154 mBottomRadius(inBottomRadius),
155 mConvexRadius(inConvexRadius)
156 {
157 static_assert(sizeof(TaperedCylinder) <= sizeof(SupportBuffer), "Buffer size too small");
158 JPH_ASSERT(IsAligned(this, alignof(TaperedCylinder)));
159 }
160
161 virtual Vec3 GetSupport(Vec3Arg inDirection) const override
162 {
163 float x = inDirection.GetX(), y = inDirection.GetY(), z = inDirection.GetZ();
164 float o = sqrt(Square(x) + Square(z));
165 if (o > 0.0f)
166 {
167 Vec3 top_support((mTopRadius * x) / o, mTop, (mTopRadius * z) / o);
168 Vec3 bottom_support((mBottomRadius * x) / o, mBottom, (mBottomRadius * z) / o);
169 return inDirection.Dot(top_support) > inDirection.Dot(bottom_support)? top_support : bottom_support;
170 }
171 else
172 {
173 if (y > 0.0f)
174 return Vec3(0, mTop, 0);
175 else
176 return Vec3(0, mBottom, 0);
177 }
178 }
179
180 virtual float GetConvexRadius() const override
181 {
182 return mConvexRadius;
183 }
184
185 private:
186 float mTop;
187 float mBottom;
188 float mTopRadius;
189 float mBottomRadius;
190 float mConvexRadius;
191 };
192
193 JPH_INLINE void TaperedCylinderShape::GetScaled(Vec3Arg inScale, float &outTop, float &outBottom, float &outTopRadius, float &outBottomRadius, float &outConvexRadius) const
194 {
195 Vec3 abs_scale = inScale.Abs();
196 float scale_xz = abs_scale.GetX();
197 float scale_y = inScale.GetY();
198
199 outTop = scale_y * mTop;
200 outBottom = scale_y * mBottom;
201 outTopRadius = scale_xz * mTopRadius;
202 outBottomRadius = scale_xz * mBottomRadius;
203 outConvexRadius = min(abs_scale.GetY(), scale_xz) * mConvexRadius;
204
205 // Negative Y-scale flips the top and bottom
206 if (outBottom > outTop)
207 {
208 std::swap(outTop, outBottom);
209 std::swap(outTopRadius, outBottomRadius);
210 }
211 }
212
213 const ConvexShape::Support *TaperedCylinderShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const
214 {
215 JPH_ASSERT(IsValidScale(inScale));
216
217 // Get scaled tapered cylinder
218 float top, bottom, top_radius, bottom_radius, convex_radius;
219 GetScaled(inScale, top, bottom, top_radius, bottom_radius, convex_radius);
220
221 switch (inMode)
222 {
223 case ESupportMode::IncludeConvexRadius:
224 case ESupportMode::Default:
225 return new (&inBuffer) TaperedCylinder(top, bottom, top_radius, bottom_radius, 0.0f);
226
227 case ESupportMode::ExcludeConvexRadius:
228 return new (&inBuffer) TaperedCylinder(top - convex_radius, bottom + convex_radius, top_radius - convex_radius, bottom_radius - convex_radius, convex_radius);
229 }
230
231 JPH_ASSERT(false);
232 return nullptr;
233 }
234
235 JPH_INLINE static Vec3 sCalculateSideNormalXZ(Vec3Arg inSurfacePosition)
236 {
237 return (Vec3(1, 0, 1) * inSurfacePosition).NormalizedOr(Vec3::sAxisX());
238 }
239
240 JPH_INLINE static Vec3 sCalculateSideNormal(Vec3Arg inNormalXZ, float inTop, float inBottom, float inTopRadius, float inBottomRadius)
241 {
242 float tan_alpha = (inBottomRadius - inTopRadius) / (inTop - inBottom);
243 return Vec3(inNormalXZ.GetX(), tan_alpha, inNormalXZ.GetZ()).Normalized();
244 }
245
246 void TaperedCylinderShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
247 {
248 JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
249 JPH_ASSERT(IsValidScale(inScale));
250
251 // Get scaled tapered cylinder
252 float top, bottom, top_radius, bottom_radius, convex_radius;
253 GetScaled(inScale, top, bottom, top_radius, bottom_radius, convex_radius);
254
255 // Get the normal of the side of the cylinder
256 Vec3 normal_xz = sCalculateSideNormalXZ(-inDirection);
257 Vec3 normal = sCalculateSideNormal(normal_xz, top, bottom, top_radius, bottom_radius);
258
259 constexpr float cMinRadius = 1.0e-3f;
260
261 // Check if the normal is closer to the side than to the top or bottom
262 if (abs(normal.Dot(inDirection)) > abs(inDirection.GetY()))
263 {
264 // Return the side of the cylinder
265 outVertices.push_back(inCenterOfMassTransform * (normal_xz * top_radius + Vec3(0, top, 0)));
266 outVertices.push_back(inCenterOfMassTransform * (normal_xz * bottom_radius + Vec3(0, bottom, 0)));
267 }
268 else
269 {
270 // When the inDirection is more than 5 degrees from vertical, align the vertices so that 1 of the vertices
271 // points towards inDirection in the XZ plane. This ensures that we always have a vertex towards max penetration depth.
272 Mat44 transform = inCenterOfMassTransform;
273 Vec4 base_x = Vec4(inDirection.GetX(), 0, inDirection.GetZ(), 0);
274 float xz_sq = base_x.LengthSq();
275 float y_sq = Square(inDirection.GetY());
276 if (xz_sq > 0.00765427f * y_sq)
277 {
278 base_x /= sqrt(xz_sq);
279 Vec4 base_z = base_x.Swizzle<SWIZZLE_Z, SWIZZLE_Y, SWIZZLE_X, SWIZZLE_W>() * Vec4(-1, 0, 1, 0);
280 transform = transform * Mat44(base_x, Vec4(0, 1, 0, 0), base_z, Vec4(0, 0, 0, 1));
281 }
282
283 if (inDirection.GetY() < 0.0f)
284 {
285 // Top of the cylinder
286 if (top_radius > cMinRadius)
287 {
288 Vec3 top_3d(0, top, 0);
289 for (Vec3 v : cTaperedCylinderFace)
290 outVertices.push_back(transform * (top_radius * v + top_3d));
291 }
292 }
293 else
294 {
295 // Bottom of the cylinder
296 if (bottom_radius > cMinRadius)
297 {
298 Vec3 bottom_3d(0, bottom, 0);
299 for (const Vec3 *v = cTaperedCylinderFace + std::size(cTaperedCylinderFace) - 1; v >= cTaperedCylinderFace; --v)
300 outVertices.push_back(transform * (bottom_radius * *v + bottom_3d));
301 }
302 }
303 }
304 }
305
306 MassProperties TaperedCylinderShape::GetMassProperties() const
307 {
308 MassProperties p;
309
310 // Calculate mass
311 float density = GetDensity();
312 p.mMass = GetVolume() * density;
313
314 // Calculate inertia of a tapered cylinder (using wxMaxima)
315 // Radius:
316 // r(x):=br+(x-b)*(tr-br)/(t-b);
317 // Where t=top, b=bottom, tr=top radius, br=bottom radius
318 // Area of the cross section of the cylinder at x:
319 // area(x):=%pi*r(x)^2;
320 // Inertia x slice at x (using inertia of a solid disc, see https://en.wikipedia.org/wiki/List_of_moments_of_inertia, note needs to be multiplied by density):
321 // dix(x):=area(x)*r(x)^2/4;
322 // Inertia y slice at y (note needs to be multiplied by density)
323 // diy(x):=area(x)*r(x)^2/2;
324 // Volume:
325 // volume(b,t):=integrate(area(x),x,b,t);
326 // The constant density (note that we have this through GetDensity() so we'll use that instead):
327 // density(b,t):=m/volume(b,t);
328 // Inertia tensor element xx, note that we use the parallel axis theorem to move the inertia: Ixx' = Ixx + m translation^2, also note we multiply by density here:
329 // Ixx(br,tr,b,t):=integrate(dix(x)+area(x)*x^2,x,b,t)*density(b,t);
330 // Inertia tensor element yy:
331 // Iyy(br,tr,b,t):=integrate(diy(x),x,b,t)*density(b,t);
332 // Note that we can simplify Ixx by using:
333 // Ixx_delta(br,tr,b,t):=Ixx(br,tr,b,t)-Iyy(br,tr,b,t)/2;
334 // For a cylinder this formula matches what is listed on the wiki:
335 // factor(Ixx(r,r,-h/2,h/2));
336 // factor(Iyy(r,r,-h/2,h/2));
337 // For a cone with tip at origin too:
338 // factor(Ixx(0,r,0,h));
339 // factor(Iyy(0,r,0,h));
340 // Now for the tapered cylinder:
341 // rat(Ixx(br,tr,b,t),br,bt);
342 // rat(Iyy(br,tr,b,t),br,bt);
343 // rat(Ixx_delta(br,tr,b,t),br,bt);
344 float t = mTop;
345 float t2 = Square(t);
346 float t3 = t * t2;
347
348 float b = mBottom;
349 float b2 = Square(b);
350 float b3 = b * b2;
351
352 float br = mBottomRadius;
353 float br2 = Square(br);
354 float br3 = br * br2;
355 float br4 = Square(br2);
356
357 float tr = mTopRadius;
358 float tr2 = Square(tr);
359 float tr3 = tr * tr2;
360 float tr4 = Square(tr2);
361
362 float inertia_y = (JPH_PI / 10.0f) * density * (t - b) * (br4 + tr * br3 + tr2 * br2 + tr3 * br + tr4);
363 float inertia_x_delta = (JPH_PI / 30.0f) * density * ((t3 + 2 * b * t2 + 3 * b2 * t - 6 * b3) * br2 + (3 * t3 + b * t2 - b2 * t - 3 * b3) * tr * br + (6 * t3 - 3 * b * t2 - 2 * b2 * t - b3) * tr2);
364 float inertia_x = inertia_x_delta + inertia_y / 2;
365 float inertia_z = inertia_x;
366 p.mInertia = Mat44::sScale(Vec3(inertia_x, inertia_y, inertia_z));
367 return p;
368 }
369
370 Vec3 TaperedCylinderShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
371 {
372 JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID");
373
374 constexpr float cEpsilon = 1.0e-5f;
375
376 if (inLocalSurfacePosition.GetY() > mTop - cEpsilon)
377 return Vec3(0, 1, 0);
378 else if (inLocalSurfacePosition.GetY() < mBottom + cEpsilon)
379 return Vec3(0, -1, 0);
380 else
381 return sCalculateSideNormal(sCalculateSideNormalXZ(inLocalSurfacePosition), mTop, mBottom, mTopRadius, mBottomRadius);
382 }
383
384 AABox TaperedCylinderShape::GetLocalBounds() const
385 {
386 float max_radius = max(mTopRadius, mBottomRadius);
387 return AABox(Vec3(-max_radius, mBottom, -max_radius), Vec3(max_radius, mTop, max_radius));
388 }
389
390 void TaperedCylinderShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
391 {
392 // Test shape filter
393 if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
394 return;
395
396 // Check if the point is in the tapered cylinder
397 if (inPoint.GetY() >= mBottom && inPoint.GetY() <= mTop // Within height
398 && Square(inPoint.GetX()) + Square(inPoint.GetZ()) <= Square(mBottomRadius + (inPoint.GetY() - mBottom) * (mTopRadius - mBottomRadius) / (mTop - mBottom))) // Within the radius
399 ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });
400 }
401
402 void TaperedCylinderShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const CollideSoftBodyVertexIterator &inVertices, uint inNumVertices, int inCollidingShapeIndex) const
403 {
404 JPH_ASSERT(IsValidScale(inScale));
405
406 Mat44 inverse_transform = inCenterOfMassTransform.InversedRotationTranslation();
407
408 // Get scaled tapered cylinder
409 float top, bottom, top_radius, bottom_radius, convex_radius;
410 GetScaled(inScale, top, bottom, top_radius, bottom_radius, convex_radius);
411 Vec3 top_3d(0, top, 0);
412 Vec3 bottom_3d(0, bottom, 0);
413
414 for (CollideSoftBodyVertexIterator v = inVertices, sbv_end = inVertices + inNumVertices; v != sbv_end; ++v)
415 if (v.GetInvMass() > 0.0f)
416 {
417 Vec3 local_pos = inverse_transform * v.GetPosition();
418
419 // Calculate penetration into side surface
420 Vec3 normal_xz = sCalculateSideNormalXZ(local_pos);
421 Vec3 side_normal = sCalculateSideNormal(normal_xz, top, bottom, top_radius, bottom_radius);
422 Vec3 side_support_top = normal_xz * top_radius + top_3d;
423 float side_penetration = (side_support_top - local_pos).Dot(side_normal);
424
425 // Calculate penetration into top and bottom plane
426 float top_penetration = top - local_pos.GetY();
427 float bottom_penetration = local_pos.GetY() - bottom;
428 float min_top_bottom_penetration = min(top_penetration, bottom_penetration);
429
430 Vec3 point, normal;
431 if (side_penetration < 0.0f || min_top_bottom_penetration < 0.0f)
432 {
433 // We're outside the cylinder
434 // Calculate the closest point on the line segment from bottom to top support point:
435 // closest_point = bottom + fraction * (top - bottom) / |top - bottom|^2
436 Vec3 side_support_bottom = normal_xz * bottom_radius + bottom_3d;
437 Vec3 bottom_to_top = side_support_top - side_support_bottom;
438 float fraction = (local_pos - side_support_bottom).Dot(bottom_to_top);
439
440 // Calculate the distance to the axis of the cylinder
441 float distance_to_axis = normal_xz.Dot(local_pos);
442 bool inside_top_radius = distance_to_axis <= top_radius;
443 bool inside_bottom_radius = distance_to_axis <= bottom_radius;
444
445 /*
446 Regions of tapered cylinder (side view):
447
448 _ B | |
449 --_ | A |
450 t-------+
451 C / \
452 / tapered \
453 _ / cylinder \
454 --_ / \
455 b-----------------+
456 D | E |
457 | |
458
459 t = side_support_top, b = side_support_bottom
460 Lines between B and C and C and D are at a 90 degree angle to the line between t and b
461 */
462 if (fraction >= bottom_to_top.LengthSq() // Region B: Above the line segment
463 && !inside_top_radius) // Outside the top radius
464 {
465 // Top support point is closest
466 point = side_support_top;
467 normal = (local_pos - point).NormalizedOr(Vec3::sAxisY());
468 }
469 else if (fraction < 0.0f // Region D: Below the line segment
470 && !inside_bottom_radius) // Outside the bottom radius
471 {
472 // Bottom support point is closest
473 point = side_support_bottom;
474 normal = (local_pos - point).NormalizedOr(Vec3::sAxisY());
475 }
476 else if (top_penetration < 0.0f // Region A: Above the top plane
477 && inside_top_radius) // Inside the top radius
478 {
479 // Top plane is closest
480 point = top_3d;
481 normal = Vec3(0, 1, 0);
482 }
483 else if (bottom_penetration < 0.0f // Region E: Below the bottom plane
484 && inside_bottom_radius) // Inside the bottom radius
485 {
486 // Bottom plane is closest
487 point = bottom_3d;
488 normal = Vec3(0, -1, 0);
489 }
490 else // Region C
491 {
492 // Side surface is closest
493 point = side_support_top;
494 normal = side_normal;
495 }
496 }
497 else if (side_penetration < min_top_bottom_penetration)
498 {
499 // Side surface is closest
500 point = side_support_top;
501 normal = side_normal;
502 }
503 else if (top_penetration < bottom_penetration)
504 {
505 // Top plane is closest
506 point = top_3d;
507 normal = Vec3(0, 1, 0);
508 }
509 else
510 {
511 // Bottom plane is closest
512 point = bottom_3d;
513 normal = Vec3(0, -1, 0);
514 }
515
516 // Calculate penetration
517 Plane plane = Plane::sFromPointAndNormal(point, normal);
518 float penetration = -plane.SignedDistance(local_pos);
519 if (v.UpdatePenetration(penetration))
520 v.SetCollision(plane.GetTransformed(inCenterOfMassTransform), inCollidingShapeIndex);
521 }
522 }
523
524 class TaperedCylinderShape::TCSGetTrianglesContext
525 {
526 public:
527 explicit TCSGetTrianglesContext(Mat44Arg inTransform) : mTransform(inTransform) { }
528
529 Mat44 mTransform;
530 uint mProcessed = 0; // Which elements we processed, bit 0 = top, bit 1 = bottom, bit 2 = side
531 };
532
533 void TaperedCylinderShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
534 {
535 static_assert(sizeof(TCSGetTrianglesContext) <= sizeof(GetTrianglesContext), "GetTrianglesContext too small");
536 JPH_ASSERT(IsAligned(&ioContext, alignof(TCSGetTrianglesContext)));
537
538 // Make sure the scale is not inside out
539 Vec3 scale = ScaleHelpers::IsInsideOut(inScale)? inScale.FlipSign<-1, 1, 1>() : inScale;
540
541 // Mark top and bottom processed if their radius is too small
542 TCSGetTrianglesContext *context = new (&ioContext) TCSGetTrianglesContext(Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(scale));
543 constexpr float cMinRadius = 1.0e-3f;
544 if (mTopRadius < cMinRadius)
545 context->mProcessed |= 0b001;
546 if (mBottomRadius < cMinRadius)
547 context->mProcessed |= 0b010;
548 }
549
550 int TaperedCylinderShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
551 {
552 constexpr int cNumVertices = int(std::size(cTaperedCylinderFace));
553
554 static_assert(cGetTrianglesMinTrianglesRequested >= 2 * cNumVertices);
555 JPH_ASSERT(inMaxTrianglesRequested >= cGetTrianglesMinTrianglesRequested);
556
557 TCSGetTrianglesContext &context = (TCSGetTrianglesContext &)ioContext;
558
559 int total_num_triangles = 0;
560
561 // Top cap
562 Vec3 top_3d(0, mTop, 0);
563 if ((context.mProcessed & 0b001) == 0)
564 {
565 Vec3 v0 = context.mTransform * (top_3d + mTopRadius * cTaperedCylinderFace[0]);
566 Vec3 v1 = context.mTransform * (top_3d + mTopRadius * cTaperedCylinderFace[1]);
567
568 for (const Vec3 *v = cTaperedCylinderFace + 2, *v_end = cTaperedCylinderFace + cNumVertices; v < v_end; ++v)
569 {
570 Vec3 v2 = context.mTransform * (top_3d + mTopRadius * *v);
571
572 v0.StoreFloat3(outTriangleVertices++);
573 v1.StoreFloat3(outTriangleVertices++);
574 v2.StoreFloat3(outTriangleVertices++);
575
576 v1 = v2;
577 }
578
579 total_num_triangles = cNumVertices - 2;
580 context.mProcessed |= 0b001;
581 }
582
583 // Bottom cap
584 Vec3 bottom_3d(0, mBottom, 0);
585 if ((context.mProcessed & 0b010) == 0
586 && total_num_triangles + cNumVertices - 2 < inMaxTrianglesRequested)
587 {
588 Vec3 v0 = context.mTransform * (bottom_3d + mBottomRadius * cTaperedCylinderFace[0]);
589 Vec3 v1 = context.mTransform * (bottom_3d + mBottomRadius * cTaperedCylinderFace[1]);
590
591 for (const Vec3 *v = cTaperedCylinderFace + 2, *v_end = cTaperedCylinderFace + cNumVertices; v < v_end; ++v)
592 {
593 Vec3 v2 = context.mTransform * (bottom_3d + mBottomRadius * *v);
594
595 v0.StoreFloat3(outTriangleVertices++);
596 v2.StoreFloat3(outTriangleVertices++);
597 v1.StoreFloat3(outTriangleVertices++);
598
599 v1 = v2;
600 }
601
602 total_num_triangles += cNumVertices - 2;
603 context.mProcessed |= 0b010;
604 }
605
606 // Side
607 if ((context.mProcessed & 0b100) == 0
608 && total_num_triangles + 2 * cNumVertices < inMaxTrianglesRequested)
609 {
610 Vec3 v0t = context.mTransform * (top_3d + mTopRadius * cTaperedCylinderFace[cNumVertices - 1]);
611 Vec3 v0b = context.mTransform * (bottom_3d + mBottomRadius * cTaperedCylinderFace[cNumVertices - 1]);
612
613 for (const Vec3 *v = cTaperedCylinderFace, *v_end = cTaperedCylinderFace + cNumVertices; v < v_end; ++v)
614 {
615 Vec3 v1t = context.mTransform * (top_3d + mTopRadius * *v);
616 v0t.StoreFloat3(outTriangleVertices++);
617 v0b.StoreFloat3(outTriangleVertices++);
618 v1t.StoreFloat3(outTriangleVertices++);
619
620 Vec3 v1b = context.mTransform * (bottom_3d + mBottomRadius * *v);
621 v1t.StoreFloat3(outTriangleVertices++);
622 v0b.StoreFloat3(outTriangleVertices++);
623 v1b.StoreFloat3(outTriangleVertices++);
624
625 v0t = v1t;
626 v0b = v1b;
627 }
628
629 total_num_triangles += 2 * cNumVertices;
630 context.mProcessed |= 0b100;
631 }
632
633 // Store materials
634 if (outMaterials != nullptr)
635 {
636 const PhysicsMaterial *material = GetMaterial();
637 for (const PhysicsMaterial **m = outMaterials, **m_end = outMaterials + total_num_triangles; m < m_end; ++m)
638 *m = material;
639 }
640
641 return total_num_triangles;
642 }
643
644 #ifdef JPH_DEBUG_RENDERER
645 void TaperedCylinderShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
646 {
647 // Preserve flip along y axis but make sure we're not inside out
648 Vec3 scale = ScaleHelpers::IsInsideOut(inScale)? inScale.FlipSign<-1, 1, 1>() : inScale;
649 RMat44 world_transform = inCenterOfMassTransform * Mat44::sScale(scale);
650
651 DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
652 inRenderer->DrawTaperedCylinder(world_transform, mTop, mBottom, mTopRadius, mBottomRadius, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor, DebugRenderer::ECastShadow::On, draw_mode);
653 }
654 #endif // JPH_DEBUG_RENDERER
655
656 void TaperedCylinderShape::SaveBinaryState(StreamOut &inStream) const
657 {
658 ConvexShape::SaveBinaryState(inStream);
659
660 inStream.Write(mTop);
661 inStream.Write(mBottom);
662 inStream.Write(mTopRadius);
663 inStream.Write(mBottomRadius);
664 inStream.Write(mConvexRadius);
665 }
666
667 void TaperedCylinderShape::RestoreBinaryState(StreamIn &inStream)
668 {
669 ConvexShape::RestoreBinaryState(inStream);
670
671 inStream.Read(mTop);
672 inStream.Read(mBottom);
673 inStream.Read(mTopRadius);
674 inStream.Read(mBottomRadius);
675 inStream.Read(mConvexRadius);
676 }
677
678 float TaperedCylinderShape::GetVolume() const
679 {
680 // Volume of a tapered cylinder is: integrate(%pi*(b+x*(t-b)/h)^2,x,0,h) where t is the top radius, b is the bottom radius and h is the height
681 return (JPH_PI / 3.0f) * (mTop - mBottom) * (Square(mTopRadius) + mTopRadius * mBottomRadius + Square(mBottomRadius));
682 }
683
684 bool TaperedCylinderShape::IsValidScale(Vec3Arg inScale) const
685 {
686 return ConvexShape::IsValidScale(inScale) && ScaleHelpers::IsUniformScaleXZ(inScale.Abs());
687 }
688
689 Vec3 TaperedCylinderShape::MakeScaleValid(Vec3Arg inScale) const
690 {
691 Vec3 scale = ScaleHelpers::MakeNonZeroScale(inScale);
692
693 return scale.GetSign() * ScaleHelpers::MakeUniformScaleXZ(scale.Abs());
694 }
695
696 void TaperedCylinderShape::sRegister()
697 {
698 ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::TaperedCylinder);
699 f.mConstruct = []() -> Shape * { return new TaperedCylinderShape; };
700 f.mColor = Color::sGreen;
701 }
702
703 JPH_NAMESPACE_END