-
Notifications
You must be signed in to change notification settings - Fork 845
Expand file tree
/
Copy pathPxsCCD.cpp
More file actions
2057 lines (1693 loc) · 68.4 KB
/
PxsCCD.cpp
File metadata and controls
2057 lines (1693 loc) · 68.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2019 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxProfiler.h"
#include "PxsContactManager.h"
#include "PxsContext.h"
#include "PxsRigidBody.h"
#include "PxcContactMethodImpl.h"
#include "GuContactPoint.h"
#include "PxsCCD.h"
#include "PsSort.h"
#include "PsAtomic.h"
#include "CmFlushPool.h"
#include "PxsMaterialManager.h"
#include "PxcMaterialMethodImpl.h"
#include "PxsMaterialManager.h"
#include "PxsMaterialCombiner.h"
#include "PxcNpContactPrepShared.h"
#include "PxvGeometry.h"
#include "DyThresholdTable.h"
#include "GuCCDSweepConvexMesh.h"
#include "PsUtilities.h"
#include "foundation/PxProfiler.h"
#include "GuBounds.h"
#if DEBUG_RENDER_CCD
#include "CmRenderOutput.h"
#include "CmRenderBuffer.h"
#include "PxPhysics.h"
#include "PxScene.h"
#endif
#define DEBUG_RENDER_CCD_FIRST_PASS_ONLY 1
#define DEBUG_RENDER_CCD_ATOM_PTR 0
#define DEBUG_RENDER_CCD_NORMAL 1
using namespace physx;
using namespace physx::shdfnd;
using namespace physx::Dy;
using namespace Gu;
static PX_FORCE_INLINE void verifyCCDPair(const PxsCCDPair& /*pair*/)
{
#if 0
if (pair.mBa0)
pair.mBa0->getPose();
if (pair.mBa1)
pair.mBa1->getPose();
#endif
}
#if CCD_DEBUG_PRINTS
namespace physx {
static const char* gGeomTypes[PxGeometryType::eGEOMETRY_COUNT+1] = {
"sphere", "plane", "capsule", "box", "convex", "trimesh", "heightfield", "*"
};
FILE* gCCDLog = NULL;
static inline void openCCDLog()
{
if (gCCDLog)
{
fclose(gCCDLog);
gCCDLog = NULL;
}
gCCDLog = fopen("c:\\ccd.txt", "wt");
fprintf(gCCDLog, ">>>>>>>>>>>>>>>>>>>>>>>>>>> CCD START FRAME <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
}
static inline void printSeparator(
const char* prefix, PxU32 pass, PxsRigidBody* atom0, PxGeometryType::Enum g0, PxsRigidBody* atom1, PxGeometryType::Enum g1)
{
fprintf(gCCDLog, "------- %s pass %d (%s %x) vs (%s %x)\n", prefix, pass, gGeomTypes[g0], atom0, gGeomTypes[g1], atom1);
fflush(gCCDLog);
}
static inline void printCCDToi(
const char* header, PxF32 t, const PxVec3& v,
PxsRigidBody* atom0, PxGeometryType::Enum g0, PxsRigidBody* atom1, PxGeometryType::Enum g1
)
{
fprintf(gCCDLog, "%s (%s %x vs %s %x): %.5f, (%.2f, %.2f, %.2f)\n", header, gGeomTypes[g0], atom0, gGeomTypes[g1], atom1, t, v.x, v.y, v.z);
fflush(gCCDLog);
}
static inline void printCCDPair(const char* header, PxsCCDPair& pair)
{
printCCDToi(header, pair.mMinToi, pair.mMinToiNormal, pair.mBa0, pair.mG0, pair.mBa1, pair.mG1);
}
// also used in PxcSweepConvexMesh.cpp
void printCCDDebug(const char* msg, const PxsRigidBody* atom0, PxGeometryType::Enum g0, bool printPtr)
{
fprintf(gCCDLog, " %s (%s %x)\n", msg, gGeomTypes[g0], printPtr ? atom0 : 0);
fflush(gCCDLog);
}
// also used in PxcSweepConvexMesh.cpp
void printShape(
PxsRigidBody* atom0, PxGeometryType::Enum g0, const char* annotation, PxReal dt, PxU32 pass, bool printPtr)
{
fprintf(gCCDLog, "%s (%s %x) atom=(%.2f, %.2f, %.2f)>(%.2f, %.2f, %.2f) v=(%.1f, %.1f, %.1f), mv=(%.1f, %.1f, %.1f)\n",
annotation, gGeomTypes[g0], printPtr ? atom0 : 0,
atom0->getLastCCDTransform().p.x, atom0->getLastCCDTransform().p.y, atom0->getLastCCDTransform().p.z,
atom0->getPose().p.x, atom0->getPose().p.y, atom0->getPose().p.z,
atom0->getLinearVelocity().x, atom0->getLinearVelocity().y, atom0->getLinearVelocity().z,
atom0->getLinearMotionVelocity(dt).x, atom0->getLinearMotionVelocity(dt).y, atom0->getLinearMotionVelocity(dt).z );
fflush(gCCDLog);
#if DEBUG_RENDER_CCD && DEBUG_RENDER_CCD_ATOM_PTR
if (!DEBUG_RENDER_CCD_FIRST_PASS_ONLY || pass == 0)
{
PxScene *s; PxGetPhysics()->getScenes(&s, 1, 0);
Cm::RenderOutput((Cm::RenderBuffer&)s->getRenderBuffer())
<< Cm::DebugText(atom0->getPose().p, 0.05f, "%x", atom0);
}
#endif
}
static inline void flushCCDLog()
{
fflush(gCCDLog);
}
} // namespace physx
#else
namespace physx
{
void printShape(PxsRigidBody* /*atom0*/, PxGeometryType::Enum /*g0*/, const char* /*annotation*/, PxReal /*dt*/, PxU32 /*pass*/, bool printPtr = true)
{PX_UNUSED(printPtr);}
static inline void openCCDLog() {}
static inline void flushCCDLog() {}
void printCCDDebug(const char* /*msg*/, const PxsRigidBody* /*atom0*/, PxGeometryType::Enum /*g0*/, bool printPtr = true) {PX_UNUSED(printPtr);}
static inline void printSeparator(
const char* /*prefix*/, PxU32 /*pass*/, PxsRigidBody* /*atom0*/, PxGeometryType::Enum /*g0*/,
PxsRigidBody* /*atom1*/, PxGeometryType::Enum /*g1*/) {}
} // namespace physx
#endif
namespace
{
// PT: TODO: refactor with ShapeSim version (SIMD)
PX_INLINE PxTransform getShapeAbsPose(const PxsShapeCore* shapeCore, const PxsRigidCore* rigidCore, PxU32 isDynamic)
{
if(isDynamic)
{
const PxsBodyCore* PX_RESTRICT bodyCore = static_cast<const PxsBodyCore*>(rigidCore);
return bodyCore->body2World * bodyCore->getBody2Actor().getInverse() *shapeCore->transform;
}
else
{
return rigidCore->body2World * shapeCore->transform;
}
}
}
namespace physx
{
PxsCCDContext::PxsCCDContext(PxsContext* context, Dy::ThresholdStream& thresholdStream, PxvNphaseImplementationContext& nPhaseContext) :
mPostCCDSweepTask (context->getContextId(), this, "PxsContext.postCCDSweep"),
mPostCCDAdvanceTask (context->getContextId(), this, "PxsContext.postCCDAdvance"),
mPostCCDDepenetrateTask (context->getContextId(), this, "PxsContext.postCCDDepenetrate"),
mDisableCCDResweep (false),
miCCDPass (0),
mSweepTotalHits (0),
mCCDThreadContext (NULL),
mCCDPairsPerBatch (0),
mCCDMaxPasses (1),
mContext (context),
mThresholdStream (thresholdStream),
mNphaseContext(nPhaseContext)
{
}
PxsCCDContext::~PxsCCDContext()
{
}
PxsCCDContext* PxsCCDContext::create(PxsContext* context, Dy::ThresholdStream& thresholdStream, PxvNphaseImplementationContext& nPhaseContext)
{
PxsCCDContext* dc = reinterpret_cast<PxsCCDContext*>(
PX_ALLOC(sizeof(PxsCCDContext), "PxsCCDContext"));
if(dc)
{
new(dc) PxsCCDContext(context, thresholdStream, nPhaseContext);
}
return dc;
}
void PxsCCDContext::destroy()
{
this->~PxsCCDContext();
PX_FREE(this);
}
PxTransform PxsCCDShape::getAbsPose(const PxsRigidBody* atom) const
{
// PT: TODO: refactor with ShapeSim version (SIMD) - or with redundant getShapeAbsPose() above in this same file!
if(atom)
return atom->getPose() * atom->getCore().getBody2Actor().getInverse() * mShapeCore->transform;
else
return mRigidCore->body2World * mShapeCore->transform;
}
PxTransform PxsCCDShape::getLastCCDAbsPose(const PxsRigidBody* atom) const
{
// PT: TODO: refactor with ShapeSim version (SIMD)
return atom->getLastCCDTransform() * atom->getCore().getBody2Actor().getInverse() * mShapeCore->transform;
}
PxReal PxsCCDPair::sweepFindToi(PxcNpThreadContext& context, PxReal dt, PxU32 pass)
{
printSeparator("findToi", pass, mBa0, mG0, NULL, PxGeometryType::eGEOMETRY_COUNT);
//Update shape transforms if necessary
updateShapes();
//Extract the bodies
PxsRigidBody* atom0 = mBa0;
PxsRigidBody* atom1 = mBa1;
PxsCCDShape* ccdShape0 = mCCDShape0;
PxsCCDShape* ccdShape1 = mCCDShape1;
PxGeometryType::Enum g0 = mG0, g1 = mG1;
//If necessary, flip the bodies to make sure that g0 <= g1
if(mG1 < mG0)
{
g0 = mG1;
g1 = mG0;
ccdShape0 = mCCDShape1;
ccdShape1 = mCCDShape0;
atom0 = mBa1;
atom1 = mBa0;
}
PX_ALIGN(16, PxTransform tm0);
PX_ALIGN(16, PxTransform tm1);
PX_ALIGN(16, PxTransform lastTm0);
PX_ALIGN(16, PxTransform lastTm1);
tm0 = ccdShape0->mCurrentTransform;
lastTm0 = ccdShape0->mPrevTransform;
tm1 = ccdShape1->mCurrentTransform;
lastTm1 = ccdShape1->mPrevTransform;
const PxVec3 trA = tm0.p - lastTm0.p;
const PxVec3 trB = tm1.p - lastTm1.p;
const PxVec3 relTr = trA - trB;
// Do the sweep
PxVec3 sweepNormal(0.0f);
PxVec3 sweepPoint(0.0f);
PxReal restDistance = PxMax(mCm->getWorkUnit().restDistance, 0.f);
context.mDt = dt;
context.mCCDFaceIndex = PXC_CONTACT_NO_FACE_INDEX;
//Cull the sweep hit based on the relative velocity along the normal
const PxReal fastMovingThresh0 = ccdShape0->mFastMovingThreshold;
const PxReal fastMovingThresh1 = ccdShape1->mFastMovingThreshold;
const PxReal sumFastMovingThresh = (fastMovingThresh0 + fastMovingThresh1);
PxReal toi = Gu::SweepShapeShape(*ccdShape0, *ccdShape1, tm0, tm1, lastTm0, lastTm1, restDistance,
sweepNormal, sweepPoint, mMinToi, context.mCCDFaceIndex, sumFastMovingThresh);
//If toi is after the end of TOI, return no hit
if (toi >= 1.0f)
{
mToiType = PxsCCDPair::ePrecise;
mPenetration = 0.f;
mPenetrationPostStep = 0.f;
mMinToi = PX_MAX_REAL; // needs to be reset in case of resweep
return toi;
}
PX_ASSERT(PxIsFinite(toi));
PX_ASSERT(sweepNormal.isFinite());
mFaceIndex = context.mCCDFaceIndex;
//Work out linear motion (used to cull the sweep hit)
const PxReal linearMotion = relTr.dot(-sweepNormal);
//If we swapped the shapes, swap them back
if(mG1 >= mG0)
sweepNormal = -sweepNormal;
mToiType = PxsCCDPair::ePrecise;
PxReal penetration = 0.f;
PxReal penetrationPostStep = 0.f;
//If linear motion along normal < the CCD threshold, set toi to no-hit.
if((linearMotion) < sumFastMovingThresh)
{
mMinToi = PX_MAX_REAL; // needs to be reset in case of resweep
return PX_MAX_REAL;
}
else if(toi <= 0.f)
{
//If the toi <= 0.f, this implies an initial overlap. If the value < 0.f, it implies penetration
PxReal stepRatio0 = atom0 ? atom0->mCCD->mTimeLeft : 1.f;
PxReal stepRatio1 = atom1 ? atom1->mCCD->mTimeLeft : 1.f;
PxReal stepRatio = PxMin(stepRatio0, stepRatio1);
penetration = -toi;
toi = 0.f;
if(stepRatio == 1.f)
{
//If stepRatio == 1.f (i.e. neither body has stepped forwards any time at all)
//we extract the advance coefficients from the bodies and permit the bodies to step forwards a small amount
//to ensure that they won't remain jammed because TOI = 0.0
const PxReal advance0 = atom0 ? atom0->mCore->ccdAdvanceCoefficient : 1.f;
const PxReal advance1 = atom1 ? atom1->mCore->ccdAdvanceCoefficient : 1.f;
const PxReal advance = PxMin(advance0, advance1);
PxReal fastMoving = PxMin(fastMovingThresh0, atom1 ? fastMovingThresh1 : PX_MAX_REAL);
PxReal advanceCoeff = advance * fastMoving;
penetrationPostStep = advanceCoeff/linearMotion;
}
PX_ASSERT(PxIsFinite(toi));
}
//Store TOI, penetration and post-step (how much to step forward in initial overlap conditions)
mMinToi = toi;
mPenetration = penetration;
mPenetrationPostStep = penetrationPostStep;
mMinToiPoint = sweepPoint;
mMinToiNormal = sweepNormal;
//Work out the materials for the contact (restitution, friction etc.)
context.mContactBuffer.count = 0;
context.mContactBuffer.contact(mMinToiPoint, mMinToiNormal, 0.f, g1 == PxGeometryType::eTRIANGLEMESH || g1 == PxGeometryType::eHEIGHTFIELD? mFaceIndex : PXC_CONTACT_NO_FACE_INDEX);
PxsMaterialInfo materialInfo;
g_GetSingleMaterialMethodTable[g0](ccdShape0->mShapeCore, 0, context, &materialInfo);
g_GetSingleMaterialMethodTable[g1](ccdShape1->mShapeCore, 1, context, &materialInfo);
const PxsMaterialData& data0 = *context.mMaterialManager->getMaterial(materialInfo.mMaterialIndex0);
const PxsMaterialData& data1 = *context.mMaterialManager->getMaterial(materialInfo.mMaterialIndex1);
const PxReal restitution = PxsMaterialCombiner::combineRestitution(data0, data1);
PxsMaterialCombiner combiner(1.0f, 1.0f);
PxsMaterialCombiner::PxsCombinedMaterial combinedMat = combiner.combineIsotropicFriction(data0, data1);
const PxReal sFriction = combinedMat.staFriction;
const PxReal dFriction = combinedMat.dynFriction;
mMaterialIndex0 = materialInfo.mMaterialIndex0;
mMaterialIndex1 = materialInfo.mMaterialIndex1;
mDynamicFriction = dFriction;
mStaticFriction = sFriction;
mRestitution = restitution;
return toi;
}
void PxsCCDPair::updateShapes()
{
if(mBa0)
{
//If the CCD shape's update count doesn't match the body's update count, this shape needs its transforms and bounds re-calculated
if(mBa0->mCCD->mUpdateCount != mCCDShape0->mUpdateCount)
{
const PxTransform tm0 = mCCDShape0->getAbsPose(mBa0);
const PxTransform lastTm0 = mCCDShape0->getLastCCDAbsPose(mBa0);
const PxVec3 trA = tm0.p - lastTm0.p;
Gu::Vec3p origin, extents;
Gu::computeBoundsWithCCDThreshold(origin, extents, mCCDShape0->mShapeCore->geometry.getGeometry(), tm0, NULL);
mCCDShape0->mCenter = origin - trA;
mCCDShape0->mExtents = extents;
mCCDShape0->mPrevTransform = lastTm0;
mCCDShape0->mCurrentTransform = tm0;
mCCDShape0->mUpdateCount = mBa0->mCCD->mUpdateCount;
}
}
if(mBa1)
{
//If the CCD shape's update count doesn't match the body's update count, this shape needs its transforms and bounds re-calculated
if(mBa1->mCCD->mUpdateCount != mCCDShape1->mUpdateCount)
{
const PxTransform tm1 = mCCDShape1->getAbsPose(mBa1);
const PxTransform lastTm1 = mCCDShape1->getLastCCDAbsPose(mBa1);
const PxVec3 trB = tm1.p - lastTm1.p;
Vec3p origin, extents;
computeBoundsWithCCDThreshold(origin, extents, mCCDShape1->mShapeCore->geometry.getGeometry(), tm1, NULL);
mCCDShape1->mCenter = origin - trB;
mCCDShape1->mExtents = extents;
mCCDShape1->mPrevTransform = lastTm1;
mCCDShape1->mCurrentTransform = tm1;
mCCDShape1->mUpdateCount = mBa1->mCCD->mUpdateCount;
}
}
}
PxReal PxsCCDPair::sweepEstimateToi()
{
//Update shape transforms if necessary
updateShapes();
//PxsRigidBody* atom1 = mBa1;
//PxsRigidBody* atom0 = mBa0;
PxsCCDShape* ccdShape0 = mCCDShape0;
PxsCCDShape* ccdShape1 = mCCDShape1;
PxGeometryType::Enum g0 = mG0, g1 = mG1;
PX_UNUSED(g0);
//Flip shapes if necessary
if(mG1 < mG0)
{
g0 = mG1;
g1 = mG0;
/*atom0 = mBa1;
atom1 = mBa0;*/
ccdShape0 = mCCDShape1;
ccdShape1 = mCCDShape0;
}
//Extract previous/current transforms, translations etc.
PxTransform tm0, lastTm0, tm1, lastTm1;
PxVec3 trA(0.f);
PxVec3 trB(0.f);
tm0 = ccdShape0->mCurrentTransform;
lastTm0 = ccdShape0->mPrevTransform;
trA = tm0.p - lastTm0.p;
tm1 = ccdShape1->mCurrentTransform;
lastTm1 = ccdShape1->mPrevTransform;
trB = tm1.p - lastTm1.p;
PxReal restDistance = PxMax(mCm->getWorkUnit().restDistance, 0.f);
const PxVec3 relTr = trA - trB;
//Work out the sum of the fast moving thresholds scaled by the step ratio
const PxReal fastMovingThresh0 = ccdShape0->mFastMovingThreshold;
const PxReal fastMovingThresh1 = ccdShape1->mFastMovingThreshold;
const PxReal sumFastMovingThresh = (fastMovingThresh0 + fastMovingThresh1);
mToiType = eEstimate;
//If the objects are not moving fast-enough relative to each-other to warrant CCD, set estimated time as PX_MAX_REAL
if((relTr.magnitudeSquared()) <= (sumFastMovingThresh * sumFastMovingThresh))
{
mToiType = eEstimate;
mMinToi = PX_MAX_REAL;
return PX_MAX_REAL;
}
//Otherwise, the objects *are* moving fast-enough so perform estimation pass
if(g1 == PxGeometryType::eTRIANGLEMESH)
{
//Special-case estimation code for meshes
PxF32 toi = Gu::SweepEstimateAnyShapeMesh(*ccdShape0, *ccdShape1, tm0, tm1, lastTm0, lastTm1, restDistance, sumFastMovingThresh);
mMinToi = toi;
return toi;
}
else if (g1 == PxGeometryType::eHEIGHTFIELD)
{
//Special-case estimation code for heightfields
PxF32 toi = Gu::SweepEstimateAnyShapeHeightfield(*ccdShape0, *ccdShape1, tm0, tm1, lastTm0, lastTm1, restDistance, sumFastMovingThresh);
mMinToi = toi;
return toi;
}
//Generic estimation code for prim-prim sweeps
PxVec3 centreA, extentsA;
PxVec3 centreB, extentsB;
centreA = ccdShape0->mCenter;
extentsA = ccdShape0->mExtents + PxVec3(restDistance);
centreB = ccdShape1->mCenter;
extentsB = ccdShape1->mExtents;
PxF32 toi = Gu::sweepAABBAABB(centreA, extentsA * 1.1f, centreB, extentsB * 1.1f, trA, trB);
mMinToi = toi;
return toi;
}
bool PxsCCDPair::sweepAdvanceToToi(PxReal dt, bool clipTrajectoryToToi)
{
PxsCCDShape* ccds0 = mCCDShape0;
PxsRigidBody* atom0 = mBa0;
PxsCCDShape* ccds1 = mCCDShape1;
PxsRigidBody* atom1 = mBa1;
const PxsCCDPair* thisPair = this;
//Both already had a pass so don't do anything
if ((atom0 == NULL || atom0->mCCD->mPassDone) && (atom1 == NULL || atom1->mCCD->mPassDone))
return false;
//Test to validate that they're both infinite mass objects. If so, there can be no response so terminate on a notification-only
if((atom0 == NULL || atom0->mCore->inverseMass == 0.f) && (atom1 == NULL || atom1->mCore->inverseMass == 0.f))
return false;
//If the TOI < 1.f. If not, this hit happens after this frame or at the very end of the frame. Either way, next frame can handle it
if (thisPair->mMinToi < 1.0f)
{
if(thisPair->mCm->getWorkUnit().flags & PxcNpWorkUnitFlag::eDISABLE_RESPONSE || thisPair->mMaxImpulse == 0.f)
{
//Don't mark pass as done on either body
return true;
}
PxReal minToi = thisPair->mMinToi;
PxF32 penetration = -mPenetration * 10.f;
PxVec3 minToiNormal = thisPair->mMinToiNormal;
if (!minToiNormal.isNormalized())
{
// somehow we got zero normal. This can happen for instance if two identical objects spawn exactly on top of one another
// abort ccd and clip to current toi
if (atom0 && !atom0->mCCD->mPassDone)
{
atom0->advancePrevPoseToToi(minToi);
atom0->advanceToToi(minToi, dt, true);
atom0->mCCD->mUpdateCount++;
}
return true;
}
//Get the material indices...
const PxReal restitution = mRestitution;
const PxReal sFriction = mStaticFriction;
const PxReal dFriction = mDynamicFriction;
PxVec3 v0(0.f), v1(0.f);
PxReal invMass0(0.f), invMass1(0.f);
#if CCD_ANGULAR_IMPULSE
PxMat33 invInertia0(PxVec3(0.f), PxVec3(0.f), PxVec3(0.f)), invInertia1(PxVec3(0.f), PxVec3(0.f), PxVec3(0.f));
PxVec3 localPoint0(0.f), localPoint1(0.f);
#endif
PxReal dom0 = mCm->getDominance0();
PxReal dom1 = mCm->getDominance1();
//Work out velocity and invMass for body 0
if(atom0)
{
//Put contact point in local space, then find how much point is moving using point velocity...
#if CCD_ANGULAR_IMPULSE
localPoint0 = mMinToiPoint - trA.p;
v0 = atom0->mCore->linearVelocity + atom0->mCore->angularVelocity.cross(localPoint0);
physx::Cm::transformInertiaTensor(atom0->mCore->inverseInertia, PxMat33(trA.q),invInertia0);
invInertia0 *= dom0;
#else
v0 = atom0->mCore->linearVelocity + atom0->mCore->angularVelocity.cross(ccds0->mCurrentTransform.p - atom0->mCore->body2World.p);
#endif
invMass0 = atom0->getInvMass() * dom0;
}
//Work out velocity and invMass for body 1
if(atom1)
{
//Put contact point in local space, then find how much point is moving using point velocity...
#if CCD_ANGULAR_IMPULSE
localPoint1 = mMinToiPoint - trB.p;
v1 = atom1->mCore->linearVelocity + atom1->mCore->angularVelocity.cross(localPoint1);
physx::Cm::transformInertiaTensor(atom1->mCore->inverseInertia, PxMat33(trB.q),invInertia1);
invInertia1 *= dom1;
#else
v1 = atom1->mCore->linearVelocity + atom1->mCore->angularVelocity.cross(ccds1->mCurrentTransform.p - atom1->mCore->body2World.p);
#endif
invMass1 = atom1->getInvMass() * dom1;
}
PX_ASSERT(v0.isFinite() && v1.isFinite());
//Work out relative velocity
PxVec3 vRel = v1 - v0;
//Project relative velocity onto contact normal and bias with penetration
PxReal relNorVel = vRel.dot(minToiNormal);
PxReal relNorVelPlusPen = relNorVel + penetration;
#if CCD_ANGULAR_IMPULSE
if(relNorVelPlusPen >= -1e-6f)
{
//we fall back on linear only parts...
localPoint0 = PxVec3(0.f);
localPoint1 = PxVec3(0.f);
v0 = atom0 ? atom0->getLinearVelocity() : PxVec3(0.f);
v1 = atom1 ? atom1->getLinearVelocity() : PxVec3(0.f);
vRel = v1 - v0;
relNorVel = vRel.dot(minToiNormal);
relNorVelPlusPen = relNorVel + penetration;
}
#endif
//If the relative motion is moving towards each-other, respond
if(relNorVelPlusPen < -1e-6f)
{
PxReal sumRecipMass = invMass0 + invMass1;
const PxReal jLin = relNorVelPlusPen;
const PxReal normalResponse = (1.f + restitution) * jLin;
#if CCD_ANGULAR_IMPULSE
const PxVec3 angularMom0 = invInertia0 * (localPoint0.cross(mMinToiNormal));
const PxVec3 angularMom1 = invInertia1 * (localPoint1.cross(mMinToiNormal));
const PxReal jAng = minToiNormal.dot(angularMom0.cross(localPoint0) + angularMom1.cross(localPoint1));
const PxReal impulseDivisor = sumRecipMass + jAng;
#else
const PxReal impulseDivisor = sumRecipMass;
#endif
const PxReal jImp = PxMax(-mMaxImpulse, normalResponse/impulseDivisor);
PxVec3 j(0.f);
//If the user requested CCD friction, calculate friction forces.
//Note, CCD is *linear* so friction is also linear. The net result is that CCD friction can stop bodies' lateral motion so its better to have it disabled
//unless there's a real need for it.
if(mHasFriction)
{
PxVec3 vPerp = vRel - relNorVel * minToiNormal;
PxVec3 tDir = vPerp;
PxReal length = tDir.normalize();
PxReal vPerpImp = length/impulseDivisor;
PxF32 fricResponse = 0.f;
PxF32 staticResponse = (jImp*sFriction);
PxF32 dynamicResponse = (jImp*dFriction);
if (PxAbs(staticResponse) >= vPerpImp)
fricResponse = vPerpImp;
else
{
fricResponse = -dynamicResponse /* times m0 */;
}
//const PxVec3 fricJ = -vPerp.getNormalized() * (fricResponse/impulseDivisor);
const PxVec3 fricJ = tDir * (fricResponse);
j = jImp * mMinToiNormal + fricJ;
}
else
{
j = jImp * mMinToiNormal;
}
verifyCCDPair(*this);
//If we have a negative impulse value, then we need to apply it. If not, the bodies are separating (no impulse to apply).
if(jImp < 0.f)
{
mAppliedForce = -jImp;
//Adjust velocities
if((atom0 != NULL && atom0->mCCD->mPassDone) ||
(atom1 != NULL && atom1->mCCD->mPassDone))
{
mPenetrationPostStep = 0.f;
}
else
{
if (atom0)
{
//atom0->mAcceleration.linear = atom0->getLinearVelocity(); // to provide pre-"solver" velocity in contact reports
atom0->setLinearVelocity(atom0->getLinearVelocity() + j * invMass0);
atom0->constrainLinearVelocity();
#if CCD_ANGULAR_IMPULSE
atom0->mAcceleration.angular = atom0->getAngularVelocity(); // to provide pre-"solver" velocity in contact reports
atom0->setAngularVelocity(atom0->getAngularVelocity() + invInertia0 * localPoint0.cross(j));
atom0->constrainAngularVelocity();
#endif
}
if (atom1)
{
//atom1->mAcceleration.linear = atom1->getLinearVelocity(); // to provide pre-"solver" velocity in contact reports
atom1->setLinearVelocity(atom1->getLinearVelocity() - j * invMass1);
atom1->constrainLinearVelocity();
#if CCD_ANGULAR_IMPULSE
atom1->mAcceleration.angular = atom1->getAngularVelocity(); // to provide pre-"solver" velocity in contact reports
atom1->setAngularVelocity(atom1->getAngularVelocity() - invInertia1 * localPoint1.cross(j));
atom1->constrainAngularVelocity();
#endif
}
}
}
}
//Update poses
if (atom0 && !atom0->mCCD->mPassDone)
{
atom0->advancePrevPoseToToi(minToi);
atom0->advanceToToi(minToi, dt, clipTrajectoryToToi && mPenetrationPostStep == 0.f);
atom0->mCCD->mUpdateCount++;
}
if (atom1 && !atom1->mCCD->mPassDone)
{
atom1->advancePrevPoseToToi(minToi);
atom1->advanceToToi(minToi, dt, clipTrajectoryToToi && mPenetrationPostStep == 0.f);
atom1->mCCD->mUpdateCount++;
}
//If we had a penetration post-step (i.e. an initial overlap), step forwards slightly after collision response
if(mPenetrationPostStep > 0.f)
{
if (atom0 && !atom0->mCCD->mPassDone)
{
atom0->advancePrevPoseToToi(mPenetrationPostStep);
if(clipTrajectoryToToi)
atom0->advanceToToi(mPenetrationPostStep, dt, clipTrajectoryToToi);
}
if (atom1 && !atom1->mCCD->mPassDone)
{
atom1->advancePrevPoseToToi(mPenetrationPostStep);
if(clipTrajectoryToToi)
atom1->advanceToToi(mPenetrationPostStep, dt, clipTrajectoryToToi);
}
}
//Mark passes as done
if (atom0)
{
atom0->mCCD->mPassDone = true;
atom0->mCCD->mHasAnyPassDone = true;
}
if (atom1)
{
atom1->mCCD->mPassDone = true;
atom1->mCCD->mHasAnyPassDone = true;
}
return true;
//return false;
}
else
{
printCCDDebug("advToi: clean sweep", atom0, mG0);
}
return false;
}
struct IslandCompare
{
bool operator()(PxsCCDPair& a, PxsCCDPair& b) const { return a.mIslandId < b.mIslandId; }
};
struct IslandPtrCompare
{
bool operator()(PxsCCDPair*& a, PxsCCDPair*& b) const { return a->mIslandId < b->mIslandId; }
};
struct ToiCompare
{
bool operator()(PxsCCDPair& a, PxsCCDPair& b) const
{
return (a.mMinToi < b.mMinToi) ||
((a.mMinToi == b.mMinToi) && (a.mBa1 != NULL && b.mBa1 == NULL));
}
};
struct ToiPtrCompare
{
bool operator()(PxsCCDPair*& a, PxsCCDPair*& b) const
{
return (a->mMinToi < b->mMinToi) ||
((a->mMinToi == b->mMinToi) && (a->mBa1 != NULL && b->mBa1 == NULL));
}
};
// --------------------------------------------------------------
/**
\brief Class to perform a set of sweep estimate tasks
*/
class PxsCCDSweepTask : public Cm::Task
{
PxsCCDPair** mPairs;
PxU32 mNumPairs;
public:
PxsCCDSweepTask(PxU64 contextID, PxsCCDPair** pairs, PxU32 nPairs)
: Cm::Task(contextID), mPairs(pairs), mNumPairs(nPairs)
{
}
virtual void runInternal()
{
for (PxU32 j = 0; j < mNumPairs; j++)
{
PxsCCDPair& pair = *mPairs[j];
pair.sweepEstimateToi();
pair.mEstimatePass = 0;
}
}
virtual const char *getName() const
{
return "PxsContext.CCDSweep";
}
private:
PxsCCDSweepTask& operator=(const PxsCCDSweepTask&);
};
#define ENABLE_RESWEEP 1
// --------------------------------------------------------------
/**
\brief Class to advance a set of islands
*/
class PxsCCDAdvanceTask : public Cm::Task
{
PxsCCDPair** mCCDPairs;
PxU32 mNumPairs;
PxsContext* mContext;
PxsCCDContext* mCCDContext;
PxReal mDt;
PxU32 mCCDPass;
const PxsCCDBodyArray& mCCDBodies;
PxU32 mFirstThreadIsland;
PxU32 mIslandsPerThread;
PxU32 mTotalIslandCount;
PxU32 mFirstIslandPair; // pairs are sorted by island
PxsCCDBody** mIslandBodies;
PxU16* mNumIslandBodies;
PxI32* mSweepTotalHits;
bool mClipTrajectory;
bool mDisableResweep;
PxsCCDAdvanceTask& operator=(const PxsCCDAdvanceTask&);
public:
PxsCCDAdvanceTask(PxsCCDPair** pairs, PxU32 nPairs, const PxsCCDBodyArray& ccdBodies,
PxsContext* context, PxsCCDContext* ccdContext, PxReal dt, PxU32 ccdPass,
PxU32 firstIslandPair, PxU32 firstThreadIsland, PxU32 islandsPerThread, PxU32 totalIslands,
PxsCCDBody** islandBodies, PxU16* numIslandBodies, bool clipTrajectory, bool disableResweep,
PxI32* sweepTotalHits)
: Cm::Task(context->getContextId()), mCCDPairs(pairs), mNumPairs(nPairs), mContext(context), mCCDContext(ccdContext), mDt(dt),
mCCDPass(ccdPass), mCCDBodies(ccdBodies), mFirstThreadIsland(firstThreadIsland),
mIslandsPerThread(islandsPerThread), mTotalIslandCount(totalIslands), mFirstIslandPair(firstIslandPair),
mIslandBodies(islandBodies), mNumIslandBodies(numIslandBodies), mSweepTotalHits(sweepTotalHits),
mClipTrajectory(clipTrajectory), mDisableResweep(disableResweep)
{
PX_ASSERT(mFirstIslandPair < mNumPairs);
}
virtual void runInternal()
{
PxI32 sweepTotalHits = 0;
PxcNpThreadContext* threadContext = mContext->getNpThreadContext();
// --------------------------------------------------------------------------------------
// loop over island labels assigned to this thread
PxU32 islandStart = mFirstIslandPair;
PxU32 lastIsland = PxMin(mFirstThreadIsland + mIslandsPerThread, mTotalIslandCount);
for (PxU32 iIsland = mFirstThreadIsland; iIsland < lastIsland; iIsland++)
{
if (islandStart >= mNumPairs)
// this is possible when for instance there are two islands with 0 pairs in the second
// since islands are initially segmented using bodies, not pairs, it can happen
break;
// --------------------------------------------------------------------------------------
// sort all pairs within current island by toi
PxU32 islandEnd = islandStart+1;
PX_ASSERT(mCCDPairs[islandStart]->mIslandId == iIsland);
while (islandEnd < mNumPairs && mCCDPairs[islandEnd]->mIslandId == iIsland) // find first index past the current island id
islandEnd++;
if (islandEnd > islandStart+1)
shdfnd::sort(mCCDPairs+islandStart, islandEnd-islandStart, ToiPtrCompare());
PX_ASSERT(islandEnd <= mNumPairs);
// --------------------------------------------------------------------------------------
// advance all affected pairs within each island to min toi
// for each pair (A,B) in toi order, find any later-toi pairs that collide against A or B
// and resweep against changed trajectories of either A or B (excluding statics and kinematics)
PxReal islandMinToi = PX_MAX_REAL;
PxU32 estimatePass = 1;
PxReal dt = mDt;
for (PxU32 iFront = islandStart; iFront < islandEnd; iFront++)
{
PxsCCDPair& pair = *mCCDPairs[iFront];
verifyCCDPair(pair);
//If we have reached a pair with a TOI after 1.0, we can terminate this island
if(pair.mMinToi > 1.f)
break;
bool needSweep0 = (pair.mBa0 && pair.mBa0->mCCD->mPassDone == false);
bool needSweep1 = (pair.mBa1 && pair.mBa1->mCCD->mPassDone == false);
//If both bodies have been updated (or one has been updated and the other is static), we can skip to the next pair
if(!(needSweep0 || needSweep1))
continue;
{
//If the pair was an estimate, we must perform an accurate sweep now
if(pair.mToiType == PxsCCDPair::eEstimate)
{
pair.sweepFindToi(*threadContext, dt, mCCDPass);
//Test to see if the pair is still the earliest pair.
if((iFront + 1) < islandEnd && mCCDPairs[iFront+1]->mMinToi < pair.mMinToi)
{
//If there is an earlier pair, we push this pair into its correct place in the list and return to the start
//of this update loop
PxsCCDPair* tmp = &pair;
PxU32 index = iFront;
while((index + 1) < islandEnd && mCCDPairs[index+1]->mMinToi < pair.mMinToi)
{
mCCDPairs[index] = mCCDPairs[index+1];
++index;
}
mCCDPairs[index] = tmp;
--iFront;
continue;
}
}
if (pair.mMinToi > 1.f)
break;