Jolt Physics
A multi core friendly Game Physics Engine
Loading...
Searching...
No Matches
InternalEdgeRemovingCollector.h
Go to the documentation of this file.
1// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
2// SPDX-FileCopyrightText: 2024 Jorrit Rouwe
3// SPDX-License-Identifier: MIT
4
5#pragma once
6
10
11//#define JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
12
13#ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
15#endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
16
18
25{
26 static constexpr uint cMaxLocalDelayedResults = 32;
27 static constexpr uint cMaxLocalVoidedFeatures = 128;
28
30 inline bool IsVoided(const SubShapeID &inSubShapeID, Vec3 inV) const
31 {
32 for (const Voided &vf : mVoidedFeatures)
33 if (vf.mSubShapeID == inSubShapeID
34 && inV.IsClose(Vec3::sLoadFloat3Unsafe(vf.mFeature), mVertexToleranceSq))
35 return true;
36 return false;
37 }
38
40 inline void VoidFeatures(const CollideShapeResult &inResult)
41 {
42 for (const Vec3 &v : inResult.mShape2Face)
43 if (!IsVoided(inResult.mSubShapeID1, v))
44 {
45 Voided vf;
46 v.StoreFloat3(&vf.mFeature);
47 vf.mSubShapeID = inResult.mSubShapeID1;
48 mVoidedFeatures.push_back(vf);
49 }
50 }
51
53 inline void Chain(const CollideShapeResult &inResult)
54 {
55 // Make sure the chained collector has the same context as we do
56 mChainedCollector.SetContext(GetContext());
57
58 // Forward the hit
59 mChainedCollector.AddHit(inResult);
60
61 // If our chained collector updated its early out fraction, we need to follow
63 }
64
66 inline void ChainAndVoid(const CollideShapeResult &inResult)
67 {
68 Chain(inResult);
69 VoidFeatures(inResult);
70
71 #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
73 DebugRenderer::sInstance->DrawArrow(mBaseOffset + inResult.mContactPointOn2, mBaseOffset + inResult.mContactPointOn2 + inResult.mPenetrationAxis.NormalizedOr(Vec3::sZero()), Color::sGreen, 0.1f);
74 #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
75 }
76
77public:
80 float inVertexToleranceSq
81 #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
82 , RVec3Arg inBaseOffset
83 #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
84 ) :
85 CollideShapeCollector(inChainedCollector),
86 mChainedCollector(inChainedCollector),
87 mVertexToleranceSq(inVertexToleranceSq)
88 #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
89 , mBaseOffset(inBaseOffset)
90 #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
91 {
92 // Initialize arrays to full capacity to avoid needless reallocation calls
93 mVoidedFeatures.reserve(cMaxLocalVoidedFeatures);
94 mDelayedResults.reserve(cMaxLocalDelayedResults);
95 }
96
97 // See: CollideShapeCollector::Reset
98 virtual void Reset() override
99 {
101
102 mChainedCollector.Reset();
103
104 mVoidedFeatures.clear();
105 mDelayedResults.clear();
106 }
107
108 // See: CollideShapeCollector::OnBody
109 virtual void OnBody(const Body &inBody) override
110 {
111 // Just forward the call to our chained collector
112 mChainedCollector.OnBody(inBody);
113 }
114
115 // See: CollideShapeCollector::AddHit
116 virtual void AddHit(const CollideShapeResult &inResult) override
117 {
118 // We only support welding when the shape is a triangle or has more vertices so that we can calculate a normal
119 if (inResult.mShape2Face.size() < 3)
120 return ChainAndVoid(inResult);
121
122 // Get the triangle normal of shape 2 face
123 Vec3 triangle_normal = (inResult.mShape2Face[1] - inResult.mShape2Face[0]).Cross(inResult.mShape2Face[2] - inResult.mShape2Face[0]);
124 float triangle_normal_len = triangle_normal.Length();
125 if (triangle_normal_len < 1e-6f)
126 return ChainAndVoid(inResult);
127
128 // If the triangle normal matches the contact normal within 1 degree, we can process the contact immediately
129 // We make the assumption here that if the contact normal and the triangle normal align that the we're dealing with a 'face contact'
130 Vec3 contact_normal = -inResult.mPenetrationAxis;
131 float contact_normal_len = inResult.mPenetrationAxis.Length();
132 if (triangle_normal.Dot(contact_normal) > 0.999848f * contact_normal_len * triangle_normal_len) // cos(1 degree)
133 return ChainAndVoid(inResult);
134
135 // Delayed processing
136 mDelayedResults.push_back(inResult);
137 }
138
140 void Flush()
141 {
142 // Sort on biggest penetration depth first
144 sorted_indices.resize(mDelayedResults.size());
145 for (uint i = 0; i < uint(mDelayedResults.size()); ++i)
146 sorted_indices[i] = i;
147 QuickSort(sorted_indices.begin(), sorted_indices.end(), [this](uint inLHS, uint inRHS) { return mDelayedResults[inLHS].mPenetrationDepth > mDelayedResults[inRHS].mPenetrationDepth; });
148
149 // Loop over all results
150 for (uint i = 0; i < uint(mDelayedResults.size()); ++i)
151 {
152 const CollideShapeResult &r = mDelayedResults[sorted_indices[i]];
153
154 // Determine which vertex or which edge is the closest to the contact point
155 float best_dist_sq = FLT_MAX;
156 uint best_v1_idx = 0;
157 uint best_v2_idx = 0;
158 uint num_v = uint(r.mShape2Face.size());
159 uint v1_idx = num_v - 1;
160 Vec3 v1 = r.mShape2Face[v1_idx] - r.mContactPointOn2;
161 for (uint v2_idx = 0; v2_idx < num_v; ++v2_idx)
162 {
163 Vec3 v2 = r.mShape2Face[v2_idx] - r.mContactPointOn2;
164 Vec3 v1_v2 = v2 - v1;
165 float denominator = v1_v2.LengthSq();
166 if (denominator < Square(FLT_EPSILON))
167 {
168 // Degenerate, assume v1 is closest, v2 will be tested in a later iteration
169 float v1_len_sq = v1.LengthSq();
170 if (v1_len_sq < best_dist_sq)
171 {
172 best_dist_sq = v1_len_sq;
173 best_v1_idx = v1_idx;
174 best_v2_idx = v1_idx;
175 }
176 }
177 else
178 {
179 // Taken from ClosestPoint::GetBaryCentricCoordinates
180 float fraction = -v1.Dot(v1_v2) / denominator;
181 if (fraction < 1.0e-6f)
182 {
183 // Closest lies on v1
184 float v1_len_sq = v1.LengthSq();
185 if (v1_len_sq < best_dist_sq)
186 {
187 best_dist_sq = v1_len_sq;
188 best_v1_idx = v1_idx;
189 best_v2_idx = v1_idx;
190 }
191 }
192 else if (fraction < 1.0f - 1.0e-6f)
193 {
194 // Closest lies on the line segment v1, v2
195 Vec3 closest = v1 + fraction * v1_v2;
196 float closest_len_sq = closest.LengthSq();
197 if (closest_len_sq < best_dist_sq)
198 {
199 best_dist_sq = closest_len_sq;
200 best_v1_idx = v1_idx;
201 best_v2_idx = v2_idx;
202 }
203 }
204 // else closest is v2, but v2 will be tested in a later iteration
205 }
206
207 v1_idx = v2_idx;
208 v1 = v2;
209 }
210
211 // Check if this vertex/edge is voided
212 bool voided = IsVoided(r.mSubShapeID1, r.mShape2Face[best_v1_idx])
213 && (best_v1_idx == best_v2_idx || IsVoided(r.mSubShapeID1, r.mShape2Face[best_v2_idx]));
214
215 #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
216 Color color = voided? Color::sRed : Color::sYellow;
217 DebugRenderer::sInstance->DrawText3D(mBaseOffset + r.mContactPointOn2, StringFormat("%d: %g", i, r.mPenetrationDepth), color, 0.1f);
220 DebugRenderer::sInstance->DrawMarker(mBaseOffset + r.mShape2Face[best_v1_idx], IsVoided(r.mSubShapeID1, r.mShape2Face[best_v1_idx])? Color::sRed : Color::sYellow, 0.1f);
221 DebugRenderer::sInstance->DrawMarker(mBaseOffset + r.mShape2Face[best_v2_idx], IsVoided(r.mSubShapeID1, r.mShape2Face[best_v2_idx])? Color::sRed : Color::sYellow, 0.1f);
222 #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
223
224 // No voided features, accept the contact
225 if (!voided)
226 Chain(r);
227
228 // Void the features of this face
229 VoidFeatures(r);
230 }
231
232 // All delayed results have been processed
233 mVoidedFeatures.clear();
234 mDelayedResults.clear();
235 }
236
237 // See: CollideShapeCollector::OnBodyEnd
238 virtual void OnBodyEnd() override
239 {
240 Flush();
241 mChainedCollector.OnBodyEnd();
242 }
243
245 static 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 = { }
246#ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
247 , RVec3Arg inBaseOffset = RVec3::sZero()
248#endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
249 )
250 {
251 JPH_ASSERT(inCollideShapeSettings.mActiveEdgeMode == EActiveEdgeMode::CollideWithAll); // Won't work without colliding with all edges
252 JPH_ASSERT(inCollideShapeSettings.mCollectFacesMode == ECollectFacesMode::CollectFaces); // Won't work without collecting faces
253
254 InternalEdgeRemovingCollector wrapper(ioCollector, inCollideShapeSettings.mInternalEdgeRemovalVertexToleranceSq
255 #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
256 , inBaseOffset
257 #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
258 );
259 CollisionDispatch::sCollideShapeVsShape(inShape1, inShape2, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1, inSubShapeIDCreator2, inCollideShapeSettings, wrapper, inShapeFilter);
260 wrapper.Flush();
261 }
262
263private:
264 // This algorithm tests a convex shape (shape 1) against a set of polygons (shape 2).
265 // This assumption doesn't hold if the shape we're testing is a compound shape, so we must also
266 // store the sub shape ID and ignore voided features that belong to another sub shape ID.
267 struct Voided
268 {
269 Float3 mFeature; // Feature that is voided (of shape 2). Read with Vec3::sLoadFloat3Unsafe so must not be the last member.
270 SubShapeID mSubShapeID; // Sub shape ID of the shape that is colliding against the feature (of shape 1).
271 };
272
273 CollideShapeCollector & mChainedCollector;
276 float mVertexToleranceSq; // Max squared distance to consider a vertex to be the same as another vertex, used to determine if a feature is voided
277#ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
278 RVec3 mBaseOffset; // Base offset for the query, used to draw the results in the right place
279#endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG
280};
281
@ CollideWithAll
Collide with all edges. Use this when you're interested in all collisions.
@ CollectFaces
mShape1/2Face is desired
unsigned int uint
Definition Core.h:505
#define JPH_NAMESPACE_END
Definition Core.h:428
#define JPH_NAMESPACE_BEGIN
Definition Core.h:422
#define JPH_ASSERT(...)
Definition IssueReporting.h:33
JPH_INLINE constexpr T Square(T inV)
Square a value.
Definition Math.h:55
void QuickSort(Iterator inBegin, Iterator inEnd, Compare inCompare)
Implementation of the quick sort algorithm. The STL version implementation is not consistent across p...
Definition QuickSort.h:53
JPH_SUPPRESS_WARNINGS_STD_BEGIN JPH_SUPPRESS_WARNINGS_STD_END JPH_NAMESPACE_BEGIN String StringFormat(const char *inFMT,...)
Definition StringTools.cpp:15
Definition Array.h:36
void resize(size_type inNewSize)
Resize array to new length.
Definition Array.h:197
const_iterator begin() const
Iterators.
Definition Array.h:493
size_type size() const
Returns amount of elements in the array.
Definition Array.h:397
void clear()
Destruct all elements and set length to zero.
Definition Array.h:222
void push_back(const T &inValue)
Add element to the back of the array.
Definition Array.h:354
void reserve(size_type inNewSize)
Reserve array space.
Definition Array.h:190
const_iterator end() const
Definition Array.h:498
Definition Body.h:39
ECollectFacesMode mCollectFacesMode
If colliding faces should be collected or only the collision point.
Definition CollideShape.h:80
JPH_OVERRIDE_NEW_DELETE EActiveEdgeMode mActiveEdgeMode
How active edges (edges that a moving object should bump into) are handled.
Definition CollideShape.h:77
Class that contains all information of two colliding shapes.
Definition CollideShape.h:19
SubShapeID mSubShapeID1
Sub shape ID that identifies the face on shape 1.
Definition CollideShape.h:63
Vec3 mContactPointOn2
Contact point on the surface of shape 2 (in world space or relative to base offset)....
Definition CollideShape.h:60
Vec3 mPenetrationAxis
Direction to move shape 2 out of collision along the shortest path (magnitude is meaningless,...
Definition CollideShape.h:61
float mPenetrationDepth
Penetration depth (move shape 2 by this distance to resolve the collision). If CollideShapeSettings::...
Definition CollideShape.h:62
Face mShape2Face
Colliding face on shape 2 (optional result, in world space or relative to base offset)
Definition CollideShape.h:67
Settings to be passed with a collision query.
Definition CollideShape.h:94
float mInternalEdgeRemovalVertexToleranceSq
Max squared distance to consider a vertex to be the same as another vertex, used by the internal edge...
Definition CollideShape.h:106
Virtual interface that allows collecting multiple collision results.
Definition CollisionCollector.h:45
virtual void AddHit(const ResultType &inResult)=0
This function will be called for every hit found, it's up to the application to decide how to store t...
virtual void Reset()
If you want to reuse this collector, call Reset()
Definition CollisionCollector.h:62
float GetEarlyOutFraction() const
Get the current early out value.
Definition CollisionCollector.h:96
const TransformedShape * GetContext() const
Definition CollisionCollector.h:75
virtual void OnBody(const Body &inBody)
Definition CollisionCollector.h:67
void UpdateEarlyOutFraction(float inFraction)
Update the early out fraction (should be lower than before)
Definition CollisionCollector.h:84
void SetContext(const TransformedShape *inContext)
Definition CollisionCollector.h:74
virtual void OnBodyEnd()
When running a query through the NarrowPhaseQuery class, this will be called after all AddHit calls h...
Definition CollisionCollector.h:70
static 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={ })
Definition CollisionDispatch.h:33
Class that holds an RGBA color with 8-bits per component.
Definition Color.h:16
static const Color sGreen
Definition Color.h:71
static const Color sRed
Definition Color.h:69
static const Color sYellow
Definition Color.h:74
virtual void DrawText3D(RVec3Arg inPosition, const string_view &inString, ColorArg inColor=Color::sWhite, float inHeight=0.5f)=0
Draw text.
void DrawMarker(RVec3Arg inPosition, ColorArg inColor, float inSize)
Draw a marker on a position.
Definition DebugRenderer.cpp:172
static DebugRenderer * sInstance
Singleton instance.
Definition DebugRenderer.h:179
void DrawWirePolygon(RMat44Arg inTransform, const VERTEX_ARRAY &inVertices, ColorArg inColor, float inArrowSize=0.0f)
Draw a wireframe polygon.
Definition DebugRenderer.h:83
void DrawArrow(RVec3Arg inFrom, RVec3Arg inTo, ColorArg inColor, float inSize)
Draw an arrow.
Definition DebugRenderer.cpp:184
Class that holds 3 floats. Used as a storage class. Convert to Vec3 for calculations.
Definition Float3.h:13
Definition InternalEdgeRemovingCollector.h:25
virtual void OnBody(const Body &inBody) override
Definition InternalEdgeRemovingCollector.h:109
InternalEdgeRemovingCollector(CollideShapeCollector &inChainedCollector, float inVertexToleranceSq)
Constructor, configures a collector to be called with all the results that do not hit internal edges.
Definition InternalEdgeRemovingCollector.h:79
void Flush()
After all hits have been added, call this function to process the delayed results.
Definition InternalEdgeRemovingCollector.h:140
static 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={ })
Version of CollisionDispatch::sCollideShapeVsShape that removes internal edges.
Definition InternalEdgeRemovingCollector.h:245
virtual void Reset() override
If you want to reuse this collector, call Reset()
Definition InternalEdgeRemovingCollector.h:98
virtual void AddHit(const CollideShapeResult &inResult) override
Definition InternalEdgeRemovingCollector.h:116
virtual void OnBodyEnd() override
When running a query through the NarrowPhaseQuery class, this will be called after all AddHit calls h...
Definition InternalEdgeRemovingCollector.h:238
Holds a 4x4 matrix of floats, but supports also operations on the 3x3 upper left part of the matrix.
Definition Mat44.h:13
static JPH_INLINE Mat44 sTranslation(Vec3Arg inV)
Get matrix that translates.
Definition Mat44.inl:144
Filter class.
Definition ShapeFilter.h:17
Base class for all shapes (collision volume of a body). Defines a virtual interface for collision det...
Definition Shape.h:185
size_type size() const
Returns amount of elements in the array.
Definition StaticArray.h:89
Definition SubShapeID.h:108
A sub shape id contains a path to an element (usually a triangle or other primitive type) of a compou...
Definition SubShapeID.h:23
Definition Vec3.h:17
JPH_INLINE bool IsClose(Vec3Arg inV2, float inMaxDistSq=1.0e-12f) const
Test if two vectors are close.
Definition Vec3.inl:488
JPH_INLINE float Dot(Vec3Arg inV2) const
Dot product.
Definition Vec3.inl:943
JPH_INLINE float Length() const
Length of vector.
Definition Vec3.inl:1000
JPH_INLINE Vec3 NormalizedOr(Vec3Arg inZeroValue) const
Normalize vector or return inZeroValue if the length of the vector is zero.
Definition Vec3.inl:1076
JPH_INLINE void StoreFloat3(Float3 *outV) const
Store 3 floats to memory.
Definition Vec3.inl:1153
JPH_INLINE float LengthSq() const
Squared length of vector.
Definition Vec3.inl:972
static JPH_INLINE Vec3 sZero()
Vector with all zeros.
Definition Vec3.inl:125
static JPH_INLINE Vec3 sLoadFloat3Unsafe(const Float3 &inV)
Load 3 floats from memory (reads 32 bits extra which it doesn't use)
Definition Vec3.inl:167