Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Collision/InternalEdgeRemovingCollector.h
9912 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::sIdentity(), inResult.mShape2Face, Color::sGreen);72DebugRenderer::sInstance->DrawArrow(RVec3(inResult.mContactPointOn2), RVec3(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 &inChainedCollector) :79CollideShapeCollector(inChainedCollector),80mChainedCollector(inChainedCollector)81{82// Initialize arrays to full capacity to avoid needless reallocation calls83mVoidedFeatures.reserve(cMaxLocalVoidedFeatures);84mDelayedResults.reserve(cMaxLocalDelayedResults);85}8687// See: CollideShapeCollector::Reset88virtual void Reset() override89{90CollideShapeCollector::Reset();9192mChainedCollector.Reset();9394mVoidedFeatures.clear();95mDelayedResults.clear();96}9798// See: CollideShapeCollector::OnBody99virtual void OnBody(const Body &inBody) override100{101// Just forward the call to our chained collector102mChainedCollector.OnBody(inBody);103}104105// See: CollideShapeCollector::AddHit106virtual void AddHit(const CollideShapeResult &inResult) override107{108// We only support welding when the shape is a triangle or has more vertices so that we can calculate a normal109if (inResult.mShape2Face.size() < 3)110return ChainAndVoid(inResult);111112// Get the triangle normal of shape 2 face113Vec3 triangle_normal = (inResult.mShape2Face[1] - inResult.mShape2Face[0]).Cross(inResult.mShape2Face[2] - inResult.mShape2Face[0]);114float triangle_normal_len = triangle_normal.Length();115if (triangle_normal_len < 1e-6f)116return ChainAndVoid(inResult);117118// If the triangle normal matches the contact normal within 1 degree, we can process the contact immediately119// We make the assumption here that if the contact normal and the triangle normal align that the we're dealing with a 'face contact'120Vec3 contact_normal = -inResult.mPenetrationAxis;121float contact_normal_len = inResult.mPenetrationAxis.Length();122if (triangle_normal.Dot(contact_normal) > 0.999848f * contact_normal_len * triangle_normal_len) // cos(1 degree)123return ChainAndVoid(inResult);124125// Delayed processing126mDelayedResults.push_back(inResult);127}128129/// After all hits have been added, call this function to process the delayed results130void Flush()131{132// Sort on biggest penetration depth first133Array<uint, STLLocalAllocator<uint, cMaxLocalDelayedResults>> sorted_indices;134sorted_indices.resize(mDelayedResults.size());135for (uint i = 0; i < uint(mDelayedResults.size()); ++i)136sorted_indices[i] = i;137QuickSort(sorted_indices.begin(), sorted_indices.end(), [this](uint inLHS, uint inRHS) { return mDelayedResults[inLHS].mPenetrationDepth > mDelayedResults[inRHS].mPenetrationDepth; });138139// Loop over all results140for (uint i = 0; i < uint(mDelayedResults.size()); ++i)141{142const CollideShapeResult &r = mDelayedResults[sorted_indices[i]];143144// Determine which vertex or which edge is the closest to the contact point145float best_dist_sq = FLT_MAX;146uint best_v1_idx = 0;147uint best_v2_idx = 0;148uint num_v = uint(r.mShape2Face.size());149uint v1_idx = num_v - 1;150Vec3 v1 = r.mShape2Face[v1_idx] - r.mContactPointOn2;151for (uint v2_idx = 0; v2_idx < num_v; ++v2_idx)152{153Vec3 v2 = r.mShape2Face[v2_idx] - r.mContactPointOn2;154Vec3 v1_v2 = v2 - v1;155float denominator = v1_v2.LengthSq();156if (denominator < Square(FLT_EPSILON))157{158// Degenerate, assume v1 is closest, v2 will be tested in a later iteration159float v1_len_sq = v1.LengthSq();160if (v1_len_sq < best_dist_sq)161{162best_dist_sq = v1_len_sq;163best_v1_idx = v1_idx;164best_v2_idx = v1_idx;165}166}167else168{169// Taken from ClosestPoint::GetBaryCentricCoordinates170float fraction = -v1.Dot(v1_v2) / denominator;171if (fraction < 1.0e-6f)172{173// Closest lies on v1174float v1_len_sq = v1.LengthSq();175if (v1_len_sq < best_dist_sq)176{177best_dist_sq = v1_len_sq;178best_v1_idx = v1_idx;179best_v2_idx = v1_idx;180}181}182else if (fraction < 1.0f - 1.0e-6f)183{184// Closest lies on the line segment v1, v2185Vec3 closest = v1 + fraction * v1_v2;186float closest_len_sq = closest.LengthSq();187if (closest_len_sq < best_dist_sq)188{189best_dist_sq = closest_len_sq;190best_v1_idx = v1_idx;191best_v2_idx = v2_idx;192}193}194// else closest is v2, but v2 will be tested in a later iteration195}196197v1_idx = v2_idx;198v1 = v2;199}200201// Check if this vertex/edge is voided202bool voided = IsVoided(r.mSubShapeID1, r.mShape2Face[best_v1_idx])203&& (best_v1_idx == best_v2_idx || IsVoided(r.mSubShapeID1, r.mShape2Face[best_v2_idx]));204205#ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG206Color color = voided? Color::sRed : Color::sYellow;207DebugRenderer::sInstance->DrawText3D(RVec3(r.mContactPointOn2), StringFormat("%d: %g", i, r.mPenetrationDepth), color, 0.1f);208DebugRenderer::sInstance->DrawWirePolygon(RMat44::sIdentity(), r.mShape2Face, color);209DebugRenderer::sInstance->DrawArrow(RVec3(r.mContactPointOn2), RVec3(r.mContactPointOn2) + r.mPenetrationAxis.NormalizedOr(Vec3::sZero()), color, 0.1f);210DebugRenderer::sInstance->DrawMarker(RVec3(r.mShape2Face[best_v1_idx]), IsVoided(r.mSubShapeID1, r.mShape2Face[best_v1_idx])? Color::sRed : Color::sYellow, 0.1f);211DebugRenderer::sInstance->DrawMarker(RVec3(r.mShape2Face[best_v2_idx]), IsVoided(r.mSubShapeID1, r.mShape2Face[best_v2_idx])? Color::sRed : Color::sYellow, 0.1f);212#endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG213214// No voided features, accept the contact215if (!voided)216Chain(r);217218// Void the features of this face219VoidFeatures(r);220}221222// All delayed results have been processed223mVoidedFeatures.clear();224mDelayedResults.clear();225}226227// See: CollideShapeCollector::OnBodyEnd228virtual void OnBodyEnd() override229{230Flush();231mChainedCollector.OnBodyEnd();232}233234/// Version of CollisionDispatch::sCollideShapeVsShape that removes internal edges235static 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 = { })236{237JPH_ASSERT(inCollideShapeSettings.mActiveEdgeMode == EActiveEdgeMode::CollideWithAll); // Won't work without colliding with all edges238JPH_ASSERT(inCollideShapeSettings.mCollectFacesMode == ECollectFacesMode::CollectFaces); // Won't work without collecting faces239240InternalEdgeRemovingCollector wrapper(ioCollector);241CollisionDispatch::sCollideShapeVsShape(inShape1, inShape2, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1, inSubShapeIDCreator2, inCollideShapeSettings, wrapper, inShapeFilter);242wrapper.Flush();243}244245private:246// This algorithm tests a convex shape (shape 1) against a set of polygons (shape 2).247// This assumption doesn't hold if the shape we're testing is a compound shape, so we must also248// store the sub shape ID and ignore voided features that belong to another sub shape ID.249struct Voided250{251Float3 mFeature; // Feature that is voided (of shape 2). Read with Vec3::sLoadFloat3Unsafe so must not be the last member.252SubShapeID mSubShapeID; // Sub shape ID of the shape that is colliding against the feature (of shape 1).253};254255CollideShapeCollector & mChainedCollector;256Array<Voided, STLLocalAllocator<Voided, cMaxLocalVoidedFeatures>> mVoidedFeatures;257Array<CollideShapeResult, STLLocalAllocator<CollideShapeResult, cMaxLocalDelayedResults>> mDelayedResults;258};259260JPH_NAMESPACE_END261262263