| 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/CylinderShape.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/CastResult.h> |
| 12 | #include <Jolt/Physics/Collision/CollidePointResult.h> |
| 13 | #include <Jolt/Physics/Collision/TransformedShape.h> |
| 14 | #include <Jolt/Physics/Collision/CollideSoftBodyVertexIterator.h> |
| 15 | #include <Jolt/Geometry/RayCylinder.h> |
| 16 | #include <Jolt/ObjectStream/TypeDeclarations.h> |
| 17 | #include <Jolt/Core/StreamIn.h> |
| 18 | #include <Jolt/Core/StreamOut.h> |
| 19 | #ifdef JPH_DEBUG_RENDERER |
| 20 | #include <Jolt/Renderer/DebugRenderer.h> |
| 21 | #endif // JPH_DEBUG_RENDERER |
| 22 | |
| 23 | JPH_NAMESPACE_BEGIN |
| 24 | |
| 25 | JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(CylinderShapeSettings) |
| 26 | { |
| 27 | JPH_ADD_BASE_CLASS(CylinderShapeSettings, ConvexShapeSettings) |
| 28 | |
| 29 | JPH_ADD_ATTRIBUTE(CylinderShapeSettings, mHalfHeight) |
| 30 | JPH_ADD_ATTRIBUTE(CylinderShapeSettings, mRadius) |
| 31 | JPH_ADD_ATTRIBUTE(CylinderShapeSettings, mConvexRadius) |
| 32 | } |
| 33 | |
| 34 | // Approximation of top face with 8 vertices |
| 35 | static const Vec3 cCylinderTopFace[] = |
| 36 | { |
| 37 | Vec3(0.0f, 1.0f, 1.0f), |
| 38 | Vec3(0.707106769f, 1.0f, 0.707106769f), |
| 39 | Vec3(1.0f, 1.0f, 0.0f), |
| 40 | Vec3(0.707106769f, 1.0f, -0.707106769f), |
| 41 | Vec3(-0.0f, 1.0f, -1.0f), |
| 42 | Vec3(-0.707106769f, 1.0f, -0.707106769f), |
| 43 | Vec3(-1.0f, 1.0f, 0.0f), |
| 44 | Vec3(-0.707106769f, 1.0f, 0.707106769f) |
| 45 | }; |
| 46 | |
| 47 | static const StaticArray<Vec3, 96> sUnitCylinderTriangles = []() { |
| 48 | StaticArray<Vec3, 96> verts; |
| 49 | |
| 50 | const Vec3 bottom_offset(0.0f, -2.0f, 0.0f); |
| 51 | |
| 52 | int num_verts = sizeof(cCylinderTopFace) / sizeof(Vec3); |
| 53 | for (int i = 0; i < num_verts; ++i) |
| 54 | { |
| 55 | Vec3 t1 = cCylinderTopFace[i]; |
| 56 | Vec3 t2 = cCylinderTopFace[(i + 1) % num_verts]; |
| 57 | Vec3 b1 = cCylinderTopFace[i] + bottom_offset; |
| 58 | Vec3 b2 = cCylinderTopFace[(i + 1) % num_verts] + bottom_offset; |
| 59 | |
| 60 | // Top |
| 61 | verts.emplace_back(0.0f, 1.0f, 0.0f); |
| 62 | verts.push_back(t1); |
| 63 | verts.push_back(t2); |
| 64 | |
| 65 | // Bottom |
| 66 | verts.emplace_back(0.0f, -1.0f, 0.0f); |
| 67 | verts.push_back(b2); |
| 68 | verts.push_back(b1); |
| 69 | |
| 70 | // Side |
| 71 | verts.push_back(t1); |
| 72 | verts.push_back(b1); |
| 73 | verts.push_back(t2); |
| 74 | |
| 75 | verts.push_back(t2); |
| 76 | verts.push_back(b1); |
| 77 | verts.push_back(b2); |
| 78 | } |
| 79 | |
| 80 | return verts; |
| 81 | }(); |
| 82 | |
| 83 | ShapeSettings::ShapeResult CylinderShapeSettings::Create() const |
| 84 | { |
| 85 | if (mCachedResult.IsEmpty()) |
| 86 | Ref<Shape> shape = new CylinderShape(*this, mCachedResult); |
| 87 | return mCachedResult; |
| 88 | } |
| 89 | |
| 90 | CylinderShape::CylinderShape(const CylinderShapeSettings &inSettings, ShapeResult &outResult) : |
| 91 | ConvexShape(EShapeSubType::Cylinder, inSettings, outResult), |
| 92 | mHalfHeight(inSettings.mHalfHeight), |
| 93 | mRadius(inSettings.mRadius), |
| 94 | mConvexRadius(inSettings.mConvexRadius) |
| 95 | { |
| 96 | if (inSettings.mHalfHeight < inSettings.mConvexRadius) |
| 97 | { |
| 98 | outResult.SetError("Invalid height"); |
| 99 | return; |
| 100 | } |
| 101 | |
| 102 | if (inSettings.mRadius < inSettings.mConvexRadius) |
| 103 | { |
| 104 | outResult.SetError("Invalid radius"); |
| 105 | return; |
| 106 | } |
| 107 | |
| 108 | if (inSettings.mConvexRadius < 0.0f) |
| 109 | { |
| 110 | outResult.SetError("Invalid convex radius"); |
| 111 | return; |
| 112 | } |
| 113 | |
| 114 | outResult.Set(this); |
| 115 | } |
| 116 | |
| 117 | CylinderShape::CylinderShape(float inHalfHeight, float inRadius, float inConvexRadius, const PhysicsMaterial *inMaterial) : |
| 118 | ConvexShape(EShapeSubType::Cylinder, inMaterial), |
| 119 | mHalfHeight(inHalfHeight), |
| 120 | mRadius(inRadius), |
| 121 | mConvexRadius(inConvexRadius) |
| 122 | { |
| 123 | JPH_ASSERT(inHalfHeight >= inConvexRadius); |
| 124 | JPH_ASSERT(inRadius >= inConvexRadius); |
| 125 | JPH_ASSERT(inConvexRadius >= 0.0f); |
| 126 | } |
| 127 | |
| 128 | class CylinderShape::Cylinder final : public Support |
| 129 | { |
| 130 | public: |
| 131 | Cylinder(float inHalfHeight, float inRadius, float inConvexRadius) : |
| 132 | mHalfHeight(inHalfHeight), |
| 133 | mRadius(inRadius), |
| 134 | mConvexRadius(inConvexRadius) |
| 135 | { |
| 136 | static_assert(sizeof(Cylinder) <= sizeof(SupportBuffer), "Buffer size too small"); |
| 137 | JPH_ASSERT(IsAligned(this, alignof(Cylinder))); |
| 138 | } |
| 139 | |
| 140 | virtual Vec3 GetSupport(Vec3Arg inDirection) const override |
| 141 | { |
| 142 | // Support mapping, taken from: |
| 143 | // A Fast and Robust GJK Implementation for Collision Detection of Convex Objects - Gino van den Bergen |
| 144 | // page 8 |
| 145 | float x = inDirection.GetX(), y = inDirection.GetY(), z = inDirection.GetZ(); |
| 146 | float o = sqrt(Square(x) + Square(z)); |
| 147 | if (o > 0.0f) |
| 148 | return Vec3((mRadius * x) / o, Sign(y) * mHalfHeight, (mRadius * z) / o); |
| 149 | else |
| 150 | return Vec3(0, Sign(y) * mHalfHeight, 0); |
| 151 | } |
| 152 | |
| 153 | virtual float GetConvexRadius() const override |
| 154 | { |
| 155 | return mConvexRadius; |
| 156 | } |
| 157 | |
| 158 | private: |
| 159 | float mHalfHeight; |
| 160 | float mRadius; |
| 161 | float mConvexRadius; |
| 162 | }; |
| 163 | |
| 164 | const ConvexShape::Support *CylinderShape::GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const |
| 165 | { |
| 166 | JPH_ASSERT(IsValidScale(inScale)); |
| 167 | |
| 168 | // Get scaled cylinder |
| 169 | Vec3 abs_scale = inScale.Abs(); |
| 170 | float scale_xz = abs_scale.GetX(); |
| 171 | float scale_y = abs_scale.GetY(); |
| 172 | float scaled_half_height = scale_y * mHalfHeight; |
| 173 | float scaled_radius = scale_xz * mRadius; |
| 174 | float scaled_convex_radius = ScaleHelpers::ScaleConvexRadius(mConvexRadius, inScale); |
| 175 | |
| 176 | switch (inMode) |
| 177 | { |
| 178 | case ESupportMode::IncludeConvexRadius: |
| 179 | case ESupportMode::Default: |
| 180 | return new (&inBuffer) Cylinder(scaled_half_height, scaled_radius, 0.0f); |
| 181 | |
| 182 | case ESupportMode::ExcludeConvexRadius: |
| 183 | return new (&inBuffer) Cylinder(scaled_half_height - scaled_convex_radius, scaled_radius - scaled_convex_radius, scaled_convex_radius); |
| 184 | } |
| 185 | |
| 186 | JPH_ASSERT(false); |
| 187 | return nullptr; |
| 188 | } |
| 189 | |
| 190 | void CylinderShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const |
| 191 | { |
| 192 | JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID"); |
| 193 | JPH_ASSERT(IsValidScale(inScale)); |
| 194 | |
| 195 | // Get scaled cylinder |
| 196 | Vec3 abs_scale = inScale.Abs(); |
| 197 | float scale_xz = abs_scale.GetX(); |
| 198 | float scale_y = abs_scale.GetY(); |
| 199 | float scaled_half_height = scale_y * mHalfHeight; |
| 200 | float scaled_radius = scale_xz * mRadius; |
| 201 | |
| 202 | float x = inDirection.GetX(), y = inDirection.GetY(), z = inDirection.GetZ(); |
| 203 | float xz_sq = Square(x) + Square(z); |
| 204 | float y_sq = Square(y); |
| 205 | |
| 206 | // Check which component is bigger |
| 207 | if (xz_sq > y_sq) |
| 208 | { |
| 209 | // Hitting side |
| 210 | float f = -scaled_radius / sqrt(xz_sq); |
| 211 | float vx = x * f; |
| 212 | float vz = z * f; |
| 213 | outVertices.push_back(inCenterOfMassTransform * Vec3(vx, scaled_half_height, vz)); |
| 214 | outVertices.push_back(inCenterOfMassTransform * Vec3(vx, -scaled_half_height, vz)); |
| 215 | } |
| 216 | else |
| 217 | { |
| 218 | // Hitting top or bottom |
| 219 | |
| 220 | // When the inDirection is more than 5 degrees from vertical, align the vertices so that 1 of the vertices |
| 221 | // points towards inDirection in the XZ plane. This ensures that we always have a vertex towards max penetration depth. |
| 222 | Mat44 transform = inCenterOfMassTransform; |
| 223 | if (xz_sq > 0.00765427f * y_sq) |
| 224 | { |
| 225 | Vec4 base_x = Vec4(x, 0, z, 0) / sqrt(xz_sq); |
| 226 | Vec4 base_z = base_x.Swizzle<SWIZZLE_Z, SWIZZLE_Y, SWIZZLE_X, SWIZZLE_W>() * Vec4(-1, 0, 1, 0); |
| 227 | transform = transform * Mat44(base_x, Vec4(0, 1, 0, 0), base_z, Vec4(0, 0, 0, 1)); |
| 228 | } |
| 229 | |
| 230 | // Adjust for scale and height |
| 231 | Vec3 multiplier = y < 0.0f? Vec3(scaled_radius, scaled_half_height, scaled_radius) : Vec3(-scaled_radius, -scaled_half_height, scaled_radius); |
| 232 | transform = transform.PreScaled(multiplier); |
| 233 | |
| 234 | for (const Vec3 &v : cCylinderTopFace) |
| 235 | outVertices.push_back(transform * v); |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | MassProperties CylinderShape::GetMassProperties() const |
| 240 | { |
| 241 | MassProperties p; |
| 242 | |
| 243 | // Mass is surface of circle * height |
| 244 | float radius_sq = Square(mRadius); |
| 245 | float height = 2.0f * mHalfHeight; |
| 246 | p.mMass = JPH_PI * radius_sq * height * GetDensity(); |
| 247 | |
| 248 | // Inertia according to https://en.wikipedia.org/wiki/List_of_moments_of_inertia: |
| 249 | float inertia_y = radius_sq * p.mMass * 0.5f; |
| 250 | float inertia_x = inertia_y * 0.5f + p.mMass * height * height / 12.0f; |
| 251 | float inertia_z = inertia_x; |
| 252 | |
| 253 | // Set inertia |
| 254 | p.mInertia = Mat44::sScale(Vec3(inertia_x, inertia_y, inertia_z)); |
| 255 | |
| 256 | return p; |
| 257 | } |
| 258 | |
| 259 | Vec3 CylinderShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const |
| 260 | { |
| 261 | JPH_ASSERT(inSubShapeID.IsEmpty(), "Invalid subshape ID"); |
| 262 | |
| 263 | // Calculate distance to infinite cylinder surface |
| 264 | Vec3 local_surface_position_xz(inLocalSurfacePosition.GetX(), 0, inLocalSurfacePosition.GetZ()); |
| 265 | float local_surface_position_xz_len = local_surface_position_xz.Length(); |
| 266 | float distance_to_curved_surface = abs(local_surface_position_xz_len - mRadius); |
| 267 | |
| 268 | // Calculate distance to top or bottom plane |
| 269 | float distance_to_top_or_bottom = abs(abs(inLocalSurfacePosition.GetY()) - mHalfHeight); |
| 270 | |
| 271 | // Return normal according to closest surface |
| 272 | if (distance_to_curved_surface < distance_to_top_or_bottom) |
| 273 | return local_surface_position_xz / local_surface_position_xz_len; |
| 274 | else |
| 275 | return inLocalSurfacePosition.GetY() > 0.0f? Vec3::sAxisY() : -Vec3::sAxisY(); |
| 276 | } |
| 277 | |
| 278 | AABox CylinderShape::GetLocalBounds() const |
| 279 | { |
| 280 | Vec3 extent = Vec3(mRadius, mHalfHeight, mRadius); |
| 281 | return AABox(-extent, extent); |
| 282 | } |
| 283 | |
| 284 | #ifdef JPH_DEBUG_RENDERER |
| 285 | void CylinderShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const |
| 286 | { |
| 287 | DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid; |
| 288 | inRenderer->DrawCylinder(inCenterOfMassTransform * Mat44::sScale(inScale.Abs()), mHalfHeight, mRadius, inUseMaterialColors? GetMaterial()->GetDebugColor() : inColor, DebugRenderer::ECastShadow::On, draw_mode); |
| 289 | } |
| 290 | #endif // JPH_DEBUG_RENDERER |
| 291 | |
| 292 | bool CylinderShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const |
| 293 | { |
| 294 | // Test ray against capsule |
| 295 | float fraction = RayCylinder(inRay.mOrigin, inRay.mDirection, mHalfHeight, mRadius); |
| 296 | if (fraction < ioHit.mFraction) |
| 297 | { |
| 298 | ioHit.mFraction = fraction; |
| 299 | ioHit.mSubShapeID2 = inSubShapeIDCreator.GetID(); |
| 300 | return true; |
| 301 | } |
| 302 | return false; |
| 303 | } |
| 304 | |
| 305 | void CylinderShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const |
| 306 | { |
| 307 | // Test shape filter |
| 308 | if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID())) |
| 309 | return; |
| 310 | |
| 311 | // Check if the point is in the cylinder |
| 312 | if (abs(inPoint.GetY()) <= mHalfHeight // Within the height |
| 313 | && Square(inPoint.GetX()) + Square(inPoint.GetZ()) <= Square(mRadius)) // Within the radius |
| 314 | ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() }); |
| 315 | } |
| 316 | |
| 317 | void CylinderShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const CollideSoftBodyVertexIterator &inVertices, uint inNumVertices, int inCollidingShapeIndex) const |
| 318 | { |
| 319 | JPH_ASSERT(IsValidScale(inScale)); |
| 320 | |
| 321 | Mat44 inverse_transform = inCenterOfMassTransform.InversedRotationTranslation(); |
| 322 | |
| 323 | // Get scaled cylinder |
| 324 | Vec3 abs_scale = inScale.Abs(); |
| 325 | float half_height = abs_scale.GetY() * mHalfHeight; |
| 326 | float radius = abs_scale.GetX() * mRadius; |
| 327 | |
| 328 | for (CollideSoftBodyVertexIterator v = inVertices, sbv_end = inVertices + inNumVertices; v != sbv_end; ++v) |
| 329 | if (v.GetInvMass() > 0.0f) |
| 330 | { |
| 331 | Vec3 local_pos = inverse_transform * v.GetPosition(); |
| 332 | |
| 333 | // Calculate penetration into side surface |
| 334 | Vec3 side_normal = local_pos; |
| 335 | side_normal.SetY(0.0f); |
| 336 | float side_normal_length = side_normal.Length(); |
| 337 | float side_penetration = radius - side_normal_length; |
| 338 | |
| 339 | // Calculate penetration into top or bottom plane |
| 340 | float top_penetration = half_height - abs(local_pos.GetY()); |
| 341 | |
| 342 | Vec3 point, normal; |
| 343 | if (side_penetration < 0.0f && top_penetration < 0.0f) |
| 344 | { |
| 345 | // We're outside the cylinder height and radius |
| 346 | point = side_normal * (radius / side_normal_length) + Vec3(0, half_height * Sign(local_pos.GetY()), 0); |
| 347 | normal = (local_pos - point).NormalizedOr(Vec3::sAxisY()); |
| 348 | } |
| 349 | else if (side_penetration < top_penetration) |
| 350 | { |
| 351 | // Side surface is closest |
| 352 | normal = side_normal_length > 0.0f? side_normal / side_normal_length : Vec3::sAxisX(); |
| 353 | point = radius * normal; |
| 354 | } |
| 355 | else |
| 356 | { |
| 357 | // Top or bottom plane is closest |
| 358 | normal = Vec3(0, Sign(local_pos.GetY()), 0); |
| 359 | point = half_height * normal; |
| 360 | } |
| 361 | |
| 362 | // Calculate penetration |
| 363 | Plane plane = Plane::sFromPointAndNormal(point, normal); |
| 364 | float penetration = -plane.SignedDistance(local_pos); |
| 365 | if (v.UpdatePenetration(penetration)) |
| 366 | v.SetCollision(plane.GetTransformed(inCenterOfMassTransform), inCollidingShapeIndex); |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | void CylinderShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const |
| 371 | { |
| 372 | Mat44 unit_cylinder_transform(Vec4(mRadius, 0, 0, 0), Vec4(0, mHalfHeight, 0, 0), Vec4(0, 0, mRadius, 0), Vec4(0, 0, 0, 1)); |
| 373 | new (&ioContext) GetTrianglesContextVertexList(inPositionCOM, inRotation, inScale, unit_cylinder_transform, sUnitCylinderTriangles.data(), sUnitCylinderTriangles.size(), GetMaterial()); |
| 374 | } |
| 375 | |
| 376 | int CylinderShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const |
| 377 | { |
| 378 | return ((GetTrianglesContextVertexList &)ioContext).GetTrianglesNext(inMaxTrianglesRequested, outTriangleVertices, outMaterials); |
| 379 | } |
| 380 | |
| 381 | void CylinderShape::SaveBinaryState(StreamOut &inStream) const |
| 382 | { |
| 383 | ConvexShape::SaveBinaryState(inStream); |
| 384 | |
| 385 | inStream.Write(mHalfHeight); |
| 386 | inStream.Write(mRadius); |
| 387 | inStream.Write(mConvexRadius); |
| 388 | } |
| 389 | |
| 390 | void CylinderShape::RestoreBinaryState(StreamIn &inStream) |
| 391 | { |
| 392 | ConvexShape::RestoreBinaryState(inStream); |
| 393 | |
| 394 | inStream.Read(mHalfHeight); |
| 395 | inStream.Read(mRadius); |
| 396 | inStream.Read(mConvexRadius); |
| 397 | } |
| 398 | |
| 399 | bool CylinderShape::IsValidScale(Vec3Arg inScale) const |
| 400 | { |
| 401 | return ConvexShape::IsValidScale(inScale) && ScaleHelpers::IsUniformScaleXZ(inScale.Abs()); |
| 402 | } |
| 403 | |
| 404 | Vec3 CylinderShape::MakeScaleValid(Vec3Arg inScale) const |
| 405 | { |
| 406 | Vec3 scale = ScaleHelpers::MakeNonZeroScale(inScale); |
| 407 | |
| 408 | return scale.GetSign() * ScaleHelpers::MakeUniformScaleXZ(scale.Abs()); |
| 409 | } |
| 410 | |
| 411 | void CylinderShape::sRegister() |
| 412 | { |
| 413 | ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::Cylinder); |
| 414 | f.mConstruct = []() -> Shape * { return new CylinderShape; }; |
| 415 | f.mColor = Color::sGreen; |
| 416 | } |
| 417 | |
| 418 | JPH_NAMESPACE_END |