Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Collision/CollideConvexVsTriangles.cpp
21444 views
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)1// SPDX-FileCopyrightText: 2021 Jorrit Rouwe2// SPDX-License-Identifier: MIT34#include <Jolt/Jolt.h>56#include <Jolt/Physics/Collision/CollideConvexVsTriangles.h>7#include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>8#include <Jolt/Physics/Collision/CollideShape.h>9#include <Jolt/Physics/Collision/TransformedShape.h>10#include <Jolt/Physics/Collision/ActiveEdges.h>11#include <Jolt/Physics/Collision/NarrowPhaseStats.h>12#include <Jolt/Geometry/EPAPenetrationDepth.h>13#include <Jolt/Geometry/Plane.h>1415JPH_NAMESPACE_BEGIN1617CollideConvexVsTriangles::CollideConvexVsTriangles(const ConvexShape *inShape1, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeID &inSubShapeID1, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector) :18mCollideShapeSettings(inCollideShapeSettings),19mCollector(ioCollector),20mShape1(inShape1),21mScale1(inScale1),22mScale2(inScale2),23mTransform1(inCenterOfMassTransform1),24mSubShapeID1(inSubShapeID1)25{26// Get transforms27Mat44 inverse_transform2 = inCenterOfMassTransform2.InversedRotationTranslation();28Mat44 transform1_to_2 = inverse_transform2 * inCenterOfMassTransform1;29mTransform2To1 = transform1_to_2.InversedRotationTranslation();3031// Calculate bounds32mBoundsOf1 = inShape1->GetLocalBounds().Scaled(inScale1);33mBoundsOf1.ExpandBy(Vec3::sReplicate(inCollideShapeSettings.mMaxSeparationDistance));34mBoundsOf1InSpaceOf2 = mBoundsOf1.Transformed(transform1_to_2); // Convert bounding box of 1 into space of 23536// Determine if shape 2 is inside out or not37mScaleSign2 = ScaleHelpers::IsInsideOut(inScale2)? -1.0f : 1.0f;38}3940void CollideConvexVsTriangles::Collide(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, uint8 inActiveEdges, const SubShapeID &inSubShapeID2)41{42// Scale triangle and transform it to the space of 143Vec3 v0 = mTransform2To1 * (mScale2 * inV0);44Vec3 v1 = mTransform2To1 * (mScale2 * inV1);45Vec3 v2 = mTransform2To1 * (mScale2 * inV2);4647// Calculate triangle normal48Vec3 triangle_normal = mScaleSign2 * (v1 - v0).Cross(v2 - v0);4950// Backface check51bool back_facing = triangle_normal.Dot(v0) > 0.0f;52if (mCollideShapeSettings.mBackFaceMode == EBackFaceMode::IgnoreBackFaces && back_facing)53return;5455// Get bounding box for triangle56AABox triangle_bbox = AABox::sFromTwoPoints(v0, v1);57triangle_bbox.Encapsulate(v2);5859// Get intersection between triangle and shape box, if there is none, we're done60if (!triangle_bbox.Overlaps(mBoundsOf1))61return;6263// Create triangle support function64TriangleConvexSupport triangle(v0, v1, v2);6566// Perform collision detection67// Note: As we don't remember the penetration axis from the last iteration, and it is likely that the shape (A) we're colliding the triangle (B) against is in front of the triangle,68// and the penetration axis is the shortest distance along to push B out of collision, we use the inverse of the triangle normal as an initial penetration axis. This has been seen69// to improve performance by approx. 5% over using a fixed axis like (1, 0, 0).70Vec3 penetration_axis = -triangle_normal, point1, point2;71EPAPenetrationDepth pen_depth;72EPAPenetrationDepth::EStatus status;7374// Get the support function75if (mShape1ExCvxRadius == nullptr)76mShape1ExCvxRadius = mShape1->GetSupportFunction(ConvexShape::ESupportMode::ExcludeConvexRadius, mBufferExCvxRadius, mScale1);7778// Perform GJK step79float max_separation_distance = mCollideShapeSettings.mMaxSeparationDistance;80status = pen_depth.GetPenetrationDepthStepGJK(*mShape1ExCvxRadius, mShape1ExCvxRadius->GetConvexRadius() + max_separation_distance, triangle, 0.0f, mCollideShapeSettings.mCollisionTolerance, penetration_axis, point1, point2);8182// Check result of collision detection83if (status == EPAPenetrationDepth::EStatus::NotColliding)84return;85else if (status == EPAPenetrationDepth::EStatus::Indeterminate)86{87// Need to run expensive EPA algorithm8889// We know we're overlapping at this point, so we can set the max separation distance to 0.90// Numerically it is possible that GJK finds that the shapes are overlapping but EPA finds that they're separated.91// In order to avoid this, we clamp the max separation distance to 1 so that we don't excessively inflate the shape,92// but we still inflate it enough to avoid the case where EPA misses the collision.93max_separation_distance = min(max_separation_distance, 1.0f);9495// Get the support function96if (mShape1IncCvxRadius == nullptr)97mShape1IncCvxRadius = mShape1->GetSupportFunction(ConvexShape::ESupportMode::IncludeConvexRadius, mBufferIncCvxRadius, mScale1);9899// Add convex radius100AddConvexRadius shape1_add_max_separation_distance(*mShape1IncCvxRadius, max_separation_distance);101102// Perform EPA step103if (!pen_depth.GetPenetrationDepthStepEPA(shape1_add_max_separation_distance, triangle, mCollideShapeSettings.mPenetrationTolerance, penetration_axis, point1, point2))104return;105}106107// Check if the penetration is bigger than the early out fraction108float penetration_depth = (point2 - point1).Length() - max_separation_distance;109if (-penetration_depth >= mCollector.GetEarlyOutFraction())110return;111112// Correct point1 for the added separation distance113float penetration_axis_len = penetration_axis.Length();114if (penetration_axis_len > 0.0f)115point1 -= penetration_axis * (max_separation_distance / penetration_axis_len);116117// Check if we have enabled active edge detection118if (mCollideShapeSettings.mActiveEdgeMode == EActiveEdgeMode::CollideOnlyWithActive && inActiveEdges != 0b111)119{120// Convert the active edge velocity hint to local space121Vec3 active_edge_movement_direction = mTransform1.Multiply3x3Transposed(mCollideShapeSettings.mActiveEdgeMovementDirection);122123// Update the penetration axis to account for active edges124// Note that we flip the triangle normal as the penetration axis is pointing towards the triangle instead of away125penetration_axis = ActiveEdges::FixNormal(v0, v1, v2, back_facing? triangle_normal : -triangle_normal, inActiveEdges, point2, penetration_axis, active_edge_movement_direction);126}127128// Convert to world space129point1 = mTransform1 * point1;130point2 = mTransform1 * point2;131Vec3 penetration_axis_world = mTransform1.Multiply3x3(penetration_axis);132133// Create collision result134CollideShapeResult result(point1, point2, penetration_axis_world, penetration_depth, mSubShapeID1, inSubShapeID2, TransformedShape::sGetBodyID(mCollector.GetContext()));135136// Gather faces137if (mCollideShapeSettings.mCollectFacesMode == ECollectFacesMode::CollectFaces)138{139// Get supporting face of shape 1140mShape1->GetSupportingFace(SubShapeID(), -penetration_axis, mScale1, mTransform1, result.mShape1Face);141142// Get face of the triangle143result.mShape2Face.resize(3);144result.mShape2Face[0] = mTransform1 * v0;145result.mShape2Face[1] = mTransform1 * v1;146result.mShape2Face[2] = mTransform1 * v2;147148// When inside out, we need to swap the triangle winding149if (mScaleSign2 < 0.0f)150std::swap(result.mShape2Face[1], result.mShape2Face[2]);151}152153// Notify the collector154JPH_IF_TRACK_NARROWPHASE_STATS(TrackNarrowPhaseCollector track;)155mCollector.AddHit(result);156}157158JPH_NAMESPACE_END159160161