Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Collision/InternalEdgeRemovingCollector.h
22051 views
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)1// SPDX-FileCopyrightText: 2024 Jorrit Rouwe2// SPDX-License-Identifier: MIT34#pragma once56#include <Jolt/Core/QuickSort.h>7#include <Jolt/Core/STLLocalAllocator.h>8#include <Jolt/Physics/Collision/CollisionDispatch.h>910//#define JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG1112#ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG13#include <Jolt/Renderer/DebugRenderer.h>14#endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG1516JPH_NAMESPACE_BEGIN1718/// Removes internal edges from collision results. Can be used to filter out 'ghost collisions'.19/// Based on: Contact generation for meshes - Pierre Terdiman (https://www.codercorner.com/MeshContacts.pdf)20///21/// Note that this class requires that CollideSettingsBase::mActiveEdgeMode == EActiveEdgeMode::CollideWithAll22/// and CollideSettingsBase::mCollectFacesMode == ECollectFacesMode::CollectFaces.23class InternalEdgeRemovingCollector : public CollideShapeCollector24{25static constexpr uint cMaxLocalDelayedResults = 32;26static constexpr uint cMaxLocalVoidedFeatures = 128;2728/// Check if a vertex is voided29inline bool IsVoided(const SubShapeID &inSubShapeID, Vec3 inV) const30{31for (const Voided &vf : mVoidedFeatures)32if (vf.mSubShapeID == inSubShapeID33&& inV.IsClose(Vec3::sLoadFloat3Unsafe(vf.mFeature), 1.0e-8f))34return true;35return false;36}3738/// Add all vertices of a face to the voided features39inline void VoidFeatures(const CollideShapeResult &inResult)40{41for (const Vec3 &v : inResult.mShape2Face)42if (!IsVoided(inResult.mSubShapeID1, v))43{44Voided vf;45v.StoreFloat3(&vf.mFeature);46vf.mSubShapeID = inResult.mSubShapeID1;47mVoidedFeatures.push_back(vf);48}49}5051/// Call the chained collector52inline void Chain(const CollideShapeResult &inResult)53{54// Make sure the chained collector has the same context as we do55mChainedCollector.SetContext(GetContext());5657// Forward the hit58mChainedCollector.AddHit(inResult);5960// If our chained collector updated its early out fraction, we need to follow61UpdateEarlyOutFraction(mChainedCollector.GetEarlyOutFraction());62}6364/// Call the chained collector and void all features of inResult65inline void ChainAndVoid(const CollideShapeResult &inResult)66{67Chain(inResult);68VoidFeatures(inResult);6970#ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG71DebugRenderer::sInstance->DrawWirePolygon(RMat44::sTranslation(mBaseOffset), inResult.mShape2Face, Color::sGreen);72DebugRenderer::sInstance->DrawArrow(mBaseOffset + inResult.mContactPointOn2, mBaseOffset + inResult.mContactPointOn2 + inResult.mPenetrationAxis.NormalizedOr(Vec3::sZero()), Color::sGreen, 0.1f);73#endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG74}7576public:77/// Constructor, configures a collector to be called with all the results that do not hit internal edges78explicit InternalEdgeRemovingCollector(CollideShapeCollector &inChainedCollector79#ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG80, RVec3Arg inBaseOffset81#endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG82) :83CollideShapeCollector(inChainedCollector),84mChainedCollector(inChainedCollector)85#ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG86, mBaseOffset(inBaseOffset)87#endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG88{89// Initialize arrays to full capacity to avoid needless reallocation calls90mVoidedFeatures.reserve(cMaxLocalVoidedFeatures);91mDelayedResults.reserve(cMaxLocalDelayedResults);92}9394// See: CollideShapeCollector::Reset95virtual void Reset() override96{97CollideShapeCollector::Reset();9899mChainedCollector.Reset();100101mVoidedFeatures.clear();102mDelayedResults.clear();103}104105// See: CollideShapeCollector::OnBody106virtual void OnBody(const Body &inBody) override107{108// Just forward the call to our chained collector109mChainedCollector.OnBody(inBody);110}111112// See: CollideShapeCollector::AddHit113virtual void AddHit(const CollideShapeResult &inResult) override114{115// We only support welding when the shape is a triangle or has more vertices so that we can calculate a normal116if (inResult.mShape2Face.size() < 3)117return ChainAndVoid(inResult);118119// Get the triangle normal of shape 2 face120Vec3 triangle_normal = (inResult.mShape2Face[1] - inResult.mShape2Face[0]).Cross(inResult.mShape2Face[2] - inResult.mShape2Face[0]);121float triangle_normal_len = triangle_normal.Length();122if (triangle_normal_len < 1e-6f)123return ChainAndVoid(inResult);124125// If the triangle normal matches the contact normal within 1 degree, we can process the contact immediately126// We make the assumption here that if the contact normal and the triangle normal align that the we're dealing with a 'face contact'127Vec3 contact_normal = -inResult.mPenetrationAxis;128float contact_normal_len = inResult.mPenetrationAxis.Length();129if (triangle_normal.Dot(contact_normal) > 0.999848f * contact_normal_len * triangle_normal_len) // cos(1 degree)130return ChainAndVoid(inResult);131132// Delayed processing133mDelayedResults.push_back(inResult);134}135136/// After all hits have been added, call this function to process the delayed results137void Flush()138{139// Sort on biggest penetration depth first140Array<uint, STLLocalAllocator<uint, cMaxLocalDelayedResults>> sorted_indices;141sorted_indices.resize(mDelayedResults.size());142for (uint i = 0; i < uint(mDelayedResults.size()); ++i)143sorted_indices[i] = i;144QuickSort(sorted_indices.begin(), sorted_indices.end(), [this](uint inLHS, uint inRHS) { return mDelayedResults[inLHS].mPenetrationDepth > mDelayedResults[inRHS].mPenetrationDepth; });145146// Loop over all results147for (uint i = 0; i < uint(mDelayedResults.size()); ++i)148{149const CollideShapeResult &r = mDelayedResults[sorted_indices[i]];150151// Determine which vertex or which edge is the closest to the contact point152float best_dist_sq = FLT_MAX;153uint best_v1_idx = 0;154uint best_v2_idx = 0;155uint num_v = uint(r.mShape2Face.size());156uint v1_idx = num_v - 1;157Vec3 v1 = r.mShape2Face[v1_idx] - r.mContactPointOn2;158for (uint v2_idx = 0; v2_idx < num_v; ++v2_idx)159{160Vec3 v2 = r.mShape2Face[v2_idx] - r.mContactPointOn2;161Vec3 v1_v2 = v2 - v1;162float denominator = v1_v2.LengthSq();163if (denominator < Square(FLT_EPSILON))164{165// Degenerate, assume v1 is closest, v2 will be tested in a later iteration166float v1_len_sq = v1.LengthSq();167if (v1_len_sq < best_dist_sq)168{169best_dist_sq = v1_len_sq;170best_v1_idx = v1_idx;171best_v2_idx = v1_idx;172}173}174else175{176// Taken from ClosestPoint::GetBaryCentricCoordinates177float fraction = -v1.Dot(v1_v2) / denominator;178if (fraction < 1.0e-6f)179{180// Closest lies on v1181float v1_len_sq = v1.LengthSq();182if (v1_len_sq < best_dist_sq)183{184best_dist_sq = v1_len_sq;185best_v1_idx = v1_idx;186best_v2_idx = v1_idx;187}188}189else if (fraction < 1.0f - 1.0e-6f)190{191// Closest lies on the line segment v1, v2192Vec3 closest = v1 + fraction * v1_v2;193float closest_len_sq = closest.LengthSq();194if (closest_len_sq < best_dist_sq)195{196best_dist_sq = closest_len_sq;197best_v1_idx = v1_idx;198best_v2_idx = v2_idx;199}200}201// else closest is v2, but v2 will be tested in a later iteration202}203204v1_idx = v2_idx;205v1 = v2;206}207208// Check if this vertex/edge is voided209bool voided = IsVoided(r.mSubShapeID1, r.mShape2Face[best_v1_idx])210&& (best_v1_idx == best_v2_idx || IsVoided(r.mSubShapeID1, r.mShape2Face[best_v2_idx]));211212#ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG213Color color = voided? Color::sRed : Color::sYellow;214DebugRenderer::sInstance->DrawText3D(mBaseOffset + r.mContactPointOn2, StringFormat("%d: %g", i, r.mPenetrationDepth), color, 0.1f);215DebugRenderer::sInstance->DrawWirePolygon(RMat44::sTranslation(mBaseOffset), r.mShape2Face, color);216DebugRenderer::sInstance->DrawArrow(mBaseOffset + r.mContactPointOn2, mBaseOffset + r.mContactPointOn2 + r.mPenetrationAxis.NormalizedOr(Vec3::sZero()), color, 0.1f);217DebugRenderer::sInstance->DrawMarker(mBaseOffset + r.mShape2Face[best_v1_idx], IsVoided(r.mSubShapeID1, r.mShape2Face[best_v1_idx])? Color::sRed : Color::sYellow, 0.1f);218DebugRenderer::sInstance->DrawMarker(mBaseOffset + r.mShape2Face[best_v2_idx], IsVoided(r.mSubShapeID1, r.mShape2Face[best_v2_idx])? Color::sRed : Color::sYellow, 0.1f);219#endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG220221// No voided features, accept the contact222if (!voided)223Chain(r);224225// Void the features of this face226VoidFeatures(r);227}228229// All delayed results have been processed230mVoidedFeatures.clear();231mDelayedResults.clear();232}233234// See: CollideShapeCollector::OnBodyEnd235virtual void OnBodyEnd() override236{237Flush();238mChainedCollector.OnBodyEnd();239}240241/// Version of CollisionDispatch::sCollideShapeVsShape that removes internal edges242static void sCollideShapeVsShape(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, const ShapeFilter &inShapeFilter = { }243#ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG244, RVec3Arg inBaseOffset = RVec3::sZero()245#endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG246)247{248JPH_ASSERT(inCollideShapeSettings.mActiveEdgeMode == EActiveEdgeMode::CollideWithAll); // Won't work without colliding with all edges249JPH_ASSERT(inCollideShapeSettings.mCollectFacesMode == ECollectFacesMode::CollectFaces); // Won't work without collecting faces250251InternalEdgeRemovingCollector wrapper(ioCollector252#ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG253, inBaseOffset254#endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG255);256CollisionDispatch::sCollideShapeVsShape(inShape1, inShape2, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1, inSubShapeIDCreator2, inCollideShapeSettings, wrapper, inShapeFilter);257wrapper.Flush();258}259260private:261// This algorithm tests a convex shape (shape 1) against a set of polygons (shape 2).262// This assumption doesn't hold if the shape we're testing is a compound shape, so we must also263// store the sub shape ID and ignore voided features that belong to another sub shape ID.264struct Voided265{266Float3 mFeature; // Feature that is voided (of shape 2). Read with Vec3::sLoadFloat3Unsafe so must not be the last member.267SubShapeID mSubShapeID; // Sub shape ID of the shape that is colliding against the feature (of shape 1).268};269270CollideShapeCollector & mChainedCollector;271Array<Voided, STLLocalAllocator<Voided, cMaxLocalVoidedFeatures>> mVoidedFeatures;272Array<CollideShapeResult, STLLocalAllocator<CollideShapeResult, cMaxLocalDelayedResults>> mDelayedResults;273#ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG274RVec3 mBaseOffset; // Base offset for the query, used to draw the results in the right place275#endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG276};277278JPH_NAMESPACE_END279280281