aboutsummaryrefslogtreecommitdiff
path: root/PhysX_3.4/Source/PhysX/src/NpFactory.cpp
blob: 26af044add765223e274aa56304e9ac6e6e40170 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
//
// 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-2018 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 "NpCast.h"
#include "NpFactory.h"
#include "NpPhysics.h"
#include "ScPhysics.h"
#include "ScbScene.h"
#include "ScbActor.h"
#include "GuHeightField.h"
#include "GuTriangleMesh.h"
#include "GuConvexMesh.h"

#if PX_USE_PARTICLE_SYSTEM_API
	#include "NpParticleSystem.h"
#endif

#if PX_USE_CLOTH_API
	#include "NpClothFabric.h"
	#include "PxClothCollisionData.h"
#endif

#include "NpConnector.h"
#include "NpPtrTableStorageManager.h"
#include "CmCollection.h"

using namespace physx;

NpFactory::NpFactory()
: GuMeshFactory()
, mConnectorArrayPool(PX_DEBUG_EXP("connectorArrayPool"))
, mPtrTableStorageManager(PX_NEW(NpPtrTableStorageManager))
, mMaterialPool(PX_DEBUG_EXP("MaterialPool"))
#if PX_USE_CLOTH_API
	, mClothFabricArray(PX_DEBUG_EXP("clothFabricArray"))
#endif
#if PX_SUPPORT_PVD
	, mNpFactoryListener(NULL)
#endif	
{
}

namespace
{
	template <typename T> void releaseAll(Ps::HashSet<T*>& container)
	{
		// a bit tricky: release will call the factory back to remove the object from
		// the tracking array, immediately invalidating the iterator. Reconstructing the
		// iterator per delete can be expensive. So, we use a temporary object.
		//
		// a coalesced hash would be efficient too, but we only ever iterate over it
		// here so it's not worth the 2x remove penalty over the normal hash.

		Ps::Array<T*, Ps::ReflectionAllocator<T*> > tmp;
		tmp.reserve(container.size());
		for(typename Ps::HashSet<T*>::Iterator iter = container.getIterator(); !iter.done(); ++iter)
			tmp.pushBack(*iter);

		PX_ASSERT(tmp.size() == container.size());
		for(PxU32 i=0;i<tmp.size();i++)
			tmp[i]->release();
	}
}



NpFactory::~NpFactory()
{
	PX_DELETE(mPtrTableStorageManager);
}


void NpFactory::release()
{
	releaseAll(mAggregateTracking);
	releaseAll(mConstraintTracking);
	releaseAll(mArticulationTracking);
	releaseAll(mActorTracking);
	while(mShapeTracking.size())
		static_cast<NpShape*>(mShapeTracking.getEntries()[0])->releaseInternal();

#if PX_USE_CLOTH_API
	while(mClothFabricArray.size())
	{
		mClothFabricArray[0]->release();
	}
#endif

	GuMeshFactory::release();  // deletes the class
}

void NpFactory::createInstance()
{
	PX_ASSERT(!mInstance);
	mInstance = PX_NEW(NpFactory)();
}


void NpFactory::destroyInstance()
{
	PX_ASSERT(mInstance);
	mInstance->release();
	mInstance = NULL;
}


NpFactory* NpFactory::mInstance = NULL;

///////////////////////////////////////////////////////////////////////////////

namespace
{
	template <typename T> void addToTracking(Ps::HashSet<T*>& set, T* element, Ps::Mutex& mutex, bool lock=true)
	{
		if(!element)
			return;

		if(lock)
			mutex.lock();

		set.insert(element);

		if(lock)
			mutex.unlock();
	}
}

/////////////////////////////////////////////////////////////////////////////// Actors

void NpFactory::addRigidStatic(PxRigidStatic* npActor, bool lock)
{
	addToTracking<PxActor>(mActorTracking, npActor, mTrackingMutex, lock);
}

void NpFactory::addRigidDynamic(PxRigidDynamic* npBody, bool lock)
{
	addToTracking<PxActor>(mActorTracking, npBody, mTrackingMutex, lock);
}

void NpFactory::addShape(PxShape* shape, bool lock)
{
	// this uses a coalesced hash set rather than a normal hash set so that we can iterate over it efficiently
	if(!shape)
		return;

	if(lock)
		mTrackingMutex.lock();

	mShapeTracking.insert(shape);

	if(lock)
		mTrackingMutex.unlock();
}


#if PX_USE_PARTICLE_SYSTEM_API

namespace
{
	NpParticleSystem* createParticleSystem(PxU32 maxParticles, bool perParticleRestOffset)
	{		
		return NpFactory::getInstance().createNpParticleSystem(maxParticles, perParticleRestOffset);
	}

	NpParticleFluid* createParticleFluid(PxU32 maxParticles, bool perParticleRestOffset)
	{		
		return NpFactory::getInstance().createNpParticleFluid(maxParticles, perParticleRestOffset);
	}

	// pointers to function above, initialized during subsystem registration
	NpParticleSystem* (*sCreateParticleSystemFn)(PxU32 maxParticles, bool perParticleRestOffset) = 0;
	NpParticleFluid* (*sCreateParticleFluidFn)(PxU32 maxParticles, bool perParticleRestOffset) = 0;
}

void NpFactory::registerParticles()
{
	sCreateParticleSystemFn = &::createParticleSystem;
	sCreateParticleFluidFn = &::createParticleFluid;
}

void NpFactory::addParticleSystem(PxParticleSystem* ps, bool lock)
{	
	addToTracking<PxActor>(mActorTracking, ps, mTrackingMutex, lock);
}

void NpFactory::addParticleFluid(PxParticleFluid* fluid, bool lock)
{
	addToTracking<PxActor>(mActorTracking, fluid, mTrackingMutex, lock);
}

NpParticleSystem* NpFactory::createNpParticleSystem(PxU32 maxParticles, bool perParticleRestOffset)
{
    NpParticleSystem* npParticleSystem;
	{
		Ps::Mutex::ScopedLock lock(mParticleSystemPoolLock);		
		npParticleSystem = mParticleSystemPool.construct(maxParticles, perParticleRestOffset);
	}
	return npParticleSystem;	
}

void NpFactory::releaseParticleSystemToPool(NpParticleSystem& particleSystem)
{
	PX_ASSERT(particleSystem.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY);
	Ps::Mutex::ScopedLock lock(mParticleSystemPoolLock);
	mParticleSystemPool.destroy(&particleSystem);
}

NpParticleFluid* NpFactory::createNpParticleFluid(PxU32 maxParticles, bool perParticleRestOffset)
{
    NpParticleFluid* npParticleFluid;
	{
		Ps::Mutex::ScopedLock lock(mParticleFluidPoolLock);		
		npParticleFluid = mParticleFluidPool.construct(maxParticles, perParticleRestOffset);
	}
	return npParticleFluid;	
}

void NpFactory::releaseParticleFluidToPool(NpParticleFluid& particleFluid)
{
	PX_ASSERT(particleFluid.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY);
	Ps::Mutex::ScopedLock lock(mParticleFluidPoolLock);
	mParticleFluidPool.destroy(&particleFluid);
}

PxParticleFluid* NpFactory::createParticleFluid(PxU32 maxParticles, bool perParticleRestOffset)
{
	if (!sCreateParticleFluidFn)
	{
		Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, 
			"Particle fluid creation failed. Use PxRegisterParticles to register particle module: returned NULL.");
		return NULL;
	}

	PxParticleFluid* fluid = sCreateParticleFluidFn(maxParticles, perParticleRestOffset);
	if (!fluid)
	{
		Ps::getFoundation().error(PxErrorCode::eINTERNAL_ERROR, __FILE__, __LINE__, 
			"Particle fluid initialization failed: returned NULL.");
		return NULL;
	}

	addParticleFluid(fluid);
	return fluid;
}

PxParticleSystem* NpFactory::createParticleSystem(PxU32 maxParticles, bool perParticleRestOffset)
{
	if (!sCreateParticleSystemFn)
	{
		Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, 
			"Particle system creation failed. Use PxRegisterParticles to register particle module: returned NULL.");
		return NULL;
	}

	PxParticleSystem* ps = sCreateParticleSystemFn(maxParticles, perParticleRestOffset);
	if (!ps)
	{
		Ps::getFoundation().error(PxErrorCode::eINTERNAL_ERROR, __FILE__, __LINE__, 
			"Particle system initialization failed: returned NULL.");
		return NULL;
	}

	addParticleSystem(ps);
	return ps;
}

#endif


#if PX_USE_CLOTH_API

namespace 
{
	NpCloth* createCloth(const PxTransform& globalPose, PxClothFabric& fabric, const PxClothParticle* particles, PxClothFlags flags)
	{		
		return NpFactory::getInstance().createNpCloth(globalPose, static_cast<NpClothFabric&>(fabric), particles, flags);
	}

	NpClothFabric* createClothFabric(PxInputStream& stream)
	{
		NpClothFabric* fabric = NpFactory::getInstance().createNpClothFabric();
		if(fabric)
		{
			if(fabric->load(stream))
				return fabric;
			fabric->decRefCount();
		}
		return NULL;
	}

	NpClothFabric* createClothFabric(const PxClothFabricDesc& desc)
	{
		NpClothFabric* fabric = NpFactory::getInstance().createNpClothFabric();
		if(fabric)
		{
			if(fabric->load(desc))
				return fabric;
			fabric->decRefCount();
		}
		return NULL;
	}

	// pointers to functions above, initialized during subsystem registration
	NpCloth* (*sCreateClothFn)(const PxTransform&, PxClothFabric&, const PxClothParticle*, PxClothFlags) = 0;
	NpClothFabric* (*sCreateClothFabricFromStreamFn)(PxInputStream&) = 0;
	NpClothFabric* (*sCreateClothFabricFromDescFn)(const PxClothFabricDesc&) = 0;
}

void NpFactory::registerCloth()
{
	sCreateClothFn = &::createCloth;
	sCreateClothFabricFromStreamFn = &::createClothFabric;
	sCreateClothFabricFromDescFn = &::createClothFabric;

	Sc::Physics::getInstance().registerCloth();	
}

void NpFactory::addCloth(PxCloth* cloth, bool lock)
{
	addToTracking<PxActor>(mActorTracking, cloth, mTrackingMutex, lock);
}

NpCloth* NpFactory::createNpCloth(const PxTransform& globalPose, PxClothFabric& fabric, const PxClothParticle* particles, PxClothFlags flags)
{
    NpCloth* npCloth;
	{
		Ps::Mutex::ScopedLock lock(mClothPoolLock);		
		npCloth = mClothPool.construct(globalPose, static_cast<NpClothFabric&>(fabric), particles, flags);
	}
	return npCloth;	
}

void NpFactory::releaseClothToPool(NpCloth& cloth)
{
	PX_ASSERT(cloth.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY);
	Ps::Mutex::ScopedLock lock(mClothPoolLock);
	mClothPool.destroy(&cloth);
}

NpClothFabric* NpFactory::createNpClothFabric()
{
    NpClothFabric* npClothFabric;
	{
		Ps::Mutex::ScopedLock lock(mClothFabricPoolLock);		
		npClothFabric = mClothFabricPool.construct();
	}
	return npClothFabric;	
}

void NpFactory::releaseClothFabricToPool(NpClothFabric& clothFabric)
{
	PX_ASSERT(clothFabric.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY);
	Ps::Mutex::ScopedLock lock(mClothFabricPoolLock);
	mClothFabricPool.destroy(&clothFabric);
}

void NpFactory::addClothFabric(NpClothFabric* cf, bool lock)
{
	if(lock)
	{
		Ps::Mutex::ScopedLock lock_(mTrackingMutex);
		if(!mClothFabricArray.size())
			mClothFabricArray.reserve(64);

		mClothFabricArray.pushBack(cf);
	}
	else
	{
		if(!mClothFabricArray.size())
			mClothFabricArray.reserve(64);

		mClothFabricArray.pushBack(cf);
	}
}

PxClothFabric* NpFactory::createClothFabric(PxInputStream& stream)
{
	if(!sCreateClothFabricFromStreamFn)
	{
		Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, 
			"Cloth not registered: returned NULL.");
		return NULL;
	}

	NpClothFabric* result = (*sCreateClothFabricFromStreamFn)(stream);

	if(result)
		addClothFabric(result);

	return result;
}

PxClothFabric* NpFactory::createClothFabric(const PxClothFabricDesc& desc)
{
	if(!sCreateClothFabricFromDescFn)
	{
		Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, 
			"Cloth not registered: returned NULL.");
		return NULL;
	}

	NpClothFabric* result = (*sCreateClothFabricFromDescFn)(desc);

	if(result)
		addClothFabric(result);

	return result;
}

bool NpFactory::removeClothFabric(PxClothFabric& cf)
{
	NpClothFabric* npClothFabric = &static_cast<NpClothFabric&>(cf);

	Ps::Mutex::ScopedLock lock(mTrackingMutex);

	// remove the cloth fabric from the array
	for(PxU32 i=0; i<mClothFabricArray.size(); i++)
	{
		if(mClothFabricArray[i]==npClothFabric)
		{
			mClothFabricArray.replaceWithLast(i);
#if PX_SUPPORT_PVD
			if(mNpFactoryListener)
				mNpFactoryListener->onNpFactoryBufferRelease(cf);
#endif
			return true;
		}
	}
	return false;
}

PxU32 NpFactory::getNbClothFabrics() const
{
	return mClothFabricArray.size();
}

PxU32 NpFactory::getClothFabrics(PxClothFabric** userBuffer, PxU32 bufferSize) const
{
	const PxU32 size = mClothFabricArray.size();

	const PxU32 writeCount = PxMin(size, bufferSize);
	for(PxU32 i=0; i<writeCount; i++)
		userBuffer[i] = mClothFabricArray[i];

	return writeCount;
}

PxCloth* NpFactory::createCloth(const PxTransform& globalPose, PxClothFabric& fabric, const PxClothParticle* particles, PxClothFlags flags)
{
	PX_CHECK_AND_RETURN_NULL(globalPose.isValid(),"globalPose is not valid.  createCloth returns NULL.");
	PX_CHECK_AND_RETURN_NULL((particles != NULL) && fabric.getNbParticles(), "No particles supplied. createCloth returns NULL.");

#if PX_CHECKED
	PX_CHECK_AND_RETURN_NULL(NpCloth::checkParticles(fabric.getNbParticles(), particles), "PxPhysics::createCloth: particle values must be finite and inverse weight must not be negative");
#endif

	if(!sCreateClothFn)
	{
		Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, 
			"Cloth not registered: returned NULL.");
		return NULL;
	}

	// create the internal cloth object
	NpCloth* npCloth = (*sCreateClothFn)(globalPose, fabric, particles, flags);
	if (npCloth)
	{
		addToTracking<PxActor>(mActorTracking, npCloth, mTrackingMutex);
		return npCloth;
	}
	else
	{
		Ps::getFoundation().error(PxErrorCode::eINTERNAL_ERROR, __FILE__, __LINE__, 
			"Cloth initialization failed: returned NULL.");
		return NULL;
	}
}
#endif

void NpFactory::onActorRelease(PxActor* a)
{
	Ps::Mutex::ScopedLock lock(mTrackingMutex);
	mActorTracking.erase(a);
}

void NpFactory::onShapeRelease(PxShape* a)
{
	Ps::Mutex::ScopedLock lock(mTrackingMutex);
	mShapeTracking.erase(a);
}


void NpFactory::addArticulation(PxArticulation* npArticulation, bool lock)
{
	addToTracking<PxArticulation>(mArticulationTracking, npArticulation, mTrackingMutex, lock);
}

namespace
{
	NpArticulation* createArticulation()
	{
		NpArticulation* npArticulation = NpFactory::getInstance().createNpArticulation();
		if (!npArticulation)
			Ps::getFoundation().error(PxErrorCode::eINTERNAL_ERROR, __FILE__, __LINE__, "Articulation initialization failed: returned NULL.");

		return npArticulation;
	}

	NpArticulationLink* createArticulationLink(NpArticulation&root, NpArticulationLink* parent, const PxTransform& pose)
	{
		PX_CHECK_AND_RETURN_NULL(pose.isValid(),"Supplied PxArticulation pose is not valid. Articulation link creation method returns NULL.");
		PX_CHECK_AND_RETURN_NULL((!parent || (&parent->getRoot() == &root)), "specified parent link is not part of the destination articulation. Articulation link creation method returns NULL.");
	
		NpArticulationLink* npArticulationLink = NpFactory::getInstance().createNpArticulationLink(root, parent, pose);
		if (!npArticulationLink)
		{
			Ps::getFoundation().error(PxErrorCode::eINTERNAL_ERROR, __FILE__, __LINE__, 
				"Articulation link initialization failed: returned NULL.");
			return NULL;
		}

		if (parent)
		{
			PxTransform parentPose = parent->getCMassLocalPose().transformInv(pose);
			PxTransform childPose = PxTransform(PxIdentity);
						
			NpArticulationJoint* npArticulationJoint = NpFactory::getInstance().createNpArticulationJoint(*parent, parentPose, *npArticulationLink, childPose);
			if (!npArticulationJoint)
			{
				PX_DELETE(npArticulationLink);
	
				Ps::getFoundation().error(PxErrorCode::eINTERNAL_ERROR, __FILE__, __LINE__, 
				"Articulation link initialization failed due to joint creation failure: returned NULL.");
				return NULL;
			}

			npArticulationLink->setInboundJoint(*npArticulationJoint);
		}

		return npArticulationLink;
	}

	// pointers to functions above, initialized during subsystem registration
	static NpArticulation* (*sCreateArticulationFn)() = 0;
	static NpArticulationLink* (*sCreateArticulationLinkFn)(NpArticulation&, NpArticulationLink* parent, const PxTransform& pose) = 0;
}

void NpFactory::registerArticulations()
{
	sCreateArticulationFn = &::createArticulation;
	sCreateArticulationLinkFn = &::createArticulationLink;
}

NpArticulation* NpFactory::createNpArticulation()
{
    NpArticulation* npArticulation;
	{
		Ps::Mutex::ScopedLock lock(mArticulationPoolLock);		
		npArticulation = mArticulationPool.construct();
	}
	return npArticulation;	
}

void NpFactory::releaseArticulationToPool(NpArticulation& articulation)
{
	PX_ASSERT(articulation.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY);
	Ps::Mutex::ScopedLock lock(mArticulationPoolLock);
	mArticulationPool.destroy(&articulation);
}

PxArticulation* NpFactory::createArticulation()
{
	if(!sCreateArticulationFn)
	{
		Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, 
			"Articulations not registered: returned NULL.");
		return NULL;
	}

	NpArticulation* npArticulation = (*sCreateArticulationFn)();
	if(npArticulation)
		addArticulation(npArticulation);

	return npArticulation;
}

void NpFactory::onArticulationRelease(PxArticulation* a)
{
	Ps::Mutex::ScopedLock lock(mTrackingMutex);
	mArticulationTracking.erase(a);
}

NpArticulationLink* NpFactory::createNpArticulationLink(NpArticulation&root, NpArticulationLink* parent, const PxTransform& pose)
{
	 NpArticulationLink* npArticulationLink;
	{
		Ps::Mutex::ScopedLock lock(mArticulationLinkPoolLock);		
		npArticulationLink = mArticulationLinkPool.construct(pose, root, parent);
	}
	return npArticulationLink;	
}

void NpFactory::releaseArticulationLinkToPool(NpArticulationLink& articulationLink)
{
	PX_ASSERT(articulationLink.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY);
	Ps::Mutex::ScopedLock lock(mArticulationLinkPoolLock);
	mArticulationLinkPool.destroy(&articulationLink);
}

PxArticulationLink* NpFactory::createArticulationLink(NpArticulation& root, NpArticulationLink* parent, const PxTransform& pose)
{
	if(!sCreateArticulationLinkFn)
	{
		Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, 
			"Articulations not registered: returned NULL.");
		return NULL;
	}

	return (*sCreateArticulationLinkFn)(root, parent, pose);
}

NpArticulationJoint* NpFactory::createNpArticulationJoint(NpArticulationLink& parent, const PxTransform& parentFrame, NpArticulationLink& child, const PxTransform& childFrame)
{
	 NpArticulationJoint* npArticulationJoint;
	{
		Ps::Mutex::ScopedLock lock(mArticulationJointPoolLock);		
		npArticulationJoint = mArticulationJointPool.construct(parent, parentFrame, child, childFrame);
	}
	return npArticulationJoint;	
}

void NpFactory::releaseArticulationJointToPool(NpArticulationJoint& articulationJoint)
{
	PX_ASSERT(articulationJoint.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY);
	Ps::Mutex::ScopedLock lock(mArticulationJointPoolLock);
	mArticulationJointPool.destroy(&articulationJoint);
}

/////////////////////////////////////////////////////////////////////////////// constraint

void NpFactory::addConstraint(PxConstraint* npConstraint, bool lock)
{
	addToTracking<PxConstraint>(mConstraintTracking, npConstraint, mTrackingMutex, lock);
}

PxConstraint* NpFactory::createConstraint(PxRigidActor* actor0, PxRigidActor* actor1, PxConstraintConnector& connector, const PxConstraintShaderTable& shaders, PxU32 dataSize)
{
	PX_CHECK_AND_RETURN_NULL((actor0 && !actor0->is<PxRigidStatic>()) || (actor1 && !actor1->is<PxRigidStatic>()), "createConstraint: At least one actor must be dynamic or an articulation link");

	NpConstraint* npConstraint;
	{
		Ps::Mutex::ScopedLock lock(mConstraintPoolLock);
		npConstraint = mConstraintPool.construct(actor0, actor1, connector, shaders, dataSize);
	}
	addConstraint(npConstraint);
	return npConstraint;
}

void NpFactory::releaseConstraintToPool(NpConstraint& constraint)
{
	PX_ASSERT(constraint.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY);
	Ps::Mutex::ScopedLock lock(mConstraintPoolLock);
	mConstraintPool.destroy(&constraint);
}

void NpFactory::onConstraintRelease(PxConstraint* c)
{
	Ps::Mutex::ScopedLock lock(mTrackingMutex);
	mConstraintTracking.erase(c);
}

/////////////////////////////////////////////////////////////////////////////// aggregate

// PX_AGGREGATE
void NpFactory::addAggregate(PxAggregate* npAggregate, bool lock)
{
	addToTracking<PxAggregate>(mAggregateTracking, npAggregate, mTrackingMutex, lock);
}

PxAggregate* NpFactory::createAggregate(PxU32 maxActors, bool selfCollisions)
{
	PX_CHECK_AND_RETURN_NULL(maxActors<=128, "maxActors limited to 128. createAggregate method returns NULL.");

	NpAggregate* npAggregate;

	{
		Ps::Mutex::ScopedLock lock(mAggregatePoolLock);
		npAggregate = mAggregatePool.construct(maxActors, selfCollisions);
	}

	addAggregate(npAggregate);
	return npAggregate;
}

void NpFactory::releaseAggregateToPool(NpAggregate& aggregate)
{
	PX_ASSERT(aggregate.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY);
	Ps::Mutex::ScopedLock lock(mAggregatePoolLock);
	mAggregatePool.destroy(&aggregate);
}

void NpFactory::onAggregateRelease(PxAggregate* a)
{
	Ps::Mutex::ScopedLock lock(mTrackingMutex);
	mAggregateTracking.erase(a);
}
//~PX_AGGREGATE


///////////////////////////////////////////////////////////////////////////////

PxMaterial* NpFactory::createMaterial(PxReal staticFriction, PxReal dynamicFriction, PxReal restitution)
{
	PX_CHECK_AND_RETURN_NULL(dynamicFriction >= 0.0f, "createMaterial: dynamicFriction must be >= 0.");
	PX_CHECK_AND_RETURN_NULL(staticFriction >= 0.0f, "createMaterial: staticFriction must be >= 0.");
	PX_CHECK_AND_RETURN_NULL(restitution >= 0.0f || restitution <= 1.0f, "createMaterial: restitution must be between 0 and 1.");
	
	Sc::MaterialData data;
	data.staticFriction = staticFriction;
	data.dynamicFriction = dynamicFriction;
	data.restitution = restitution;

	NpMaterial* npMaterial;
	{
		Ps::Mutex::ScopedLock lock(mMaterialPoolLock);		
		npMaterial = mMaterialPool.construct(data);
	}
	return npMaterial;	
}

void NpFactory::releaseMaterialToPool(NpMaterial& material)
{
	PX_ASSERT(material.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY);
	Ps::Mutex::ScopedLock lock(mMaterialPoolLock);
	mMaterialPool.destroy(&material);
}

///////////////////////////////////////////////////////////////////////////////

NpConnectorArray* NpFactory::acquireConnectorArray()
{
	Ps::MutexT<>::ScopedLock l(mConnectorArrayPoolLock);
	return mConnectorArrayPool.construct();
}

void NpFactory::releaseConnectorArray(NpConnectorArray* array)
{
	Ps::MutexT<>::ScopedLock l(mConnectorArrayPoolLock);
	mConnectorArrayPool.destroy(array);
}

///////////////////////////////////////////////////////////////////////////////



///////////////////////////////////////////////////////////////////////////////

NpShape* NpFactory::createShape(const PxGeometry& geometry,
								PxShapeFlags shapeFlags,
								PxMaterial*const* materials,
								PxU16 materialCount,
								bool isExclusive)
{	
	switch(geometry.getType())
	{
		case PxGeometryType::eBOX:
			PX_CHECK_AND_RETURN_NULL(static_cast<const PxBoxGeometry&>(geometry).isValid(), "Supplied PxGeometry is not valid. Shape creation method returns NULL.");
			break;
		case PxGeometryType::eSPHERE:
			PX_CHECK_AND_RETURN_NULL(static_cast<const PxSphereGeometry&>(geometry).isValid(), "Supplied PxGeometry is not valid. Shape creation method returns NULL.");
			break;
		case PxGeometryType::eCAPSULE:
			PX_CHECK_AND_RETURN_NULL(static_cast<const PxCapsuleGeometry&>(geometry).isValid(), "Supplied PxGeometry is not valid. Shape creation method returns NULL.");
			break;
		case PxGeometryType::eCONVEXMESH:
			PX_CHECK_AND_RETURN_NULL(static_cast<const PxConvexMeshGeometry&>(geometry).isValid(), "Supplied PxGeometry is not valid. Shape creation method returns NULL.");
			break;
		case PxGeometryType::ePLANE:
			PX_CHECK_AND_RETURN_NULL(static_cast<const PxPlaneGeometry&>(geometry).isValid(), "Supplied PxGeometry is not valid. Shape creation method returns NULL.");
			break;
		case PxGeometryType::eHEIGHTFIELD:
			PX_CHECK_AND_RETURN_NULL(static_cast<const PxHeightFieldGeometry&>(geometry).isValid(), "Supplied PxGeometry is not valid. Shape creation method returns NULL.");
			break;
		case PxGeometryType::eTRIANGLEMESH:
			PX_CHECK_AND_RETURN_NULL(static_cast<const PxTriangleMeshGeometry&>(geometry).isValid(), "Supplied PxGeometry is not valid. Shape creation method returns NULL.");
			break;
		case PxGeometryType::eGEOMETRY_COUNT:
		case PxGeometryType::eINVALID:
			PX_ASSERT(0);
	}

	//
	// Check for invalid material table setups
	//

#if PX_CHECKED
	if (!NpShape::checkMaterialSetup(geometry, "Shape creation", materials, materialCount))
		return NULL;
#endif

	Ps::InlineArray<PxU16, 4> materialIndices("NpFactory::TmpMaterialIndexBuffer");
	materialIndices.resize(materialCount);
	if (materialCount == 1)
	{
		materialIndices[0] = Ps::to16((static_cast<NpMaterial*>(materials[0]))->getHandle());
	}
	else
	{
		NpMaterial::getMaterialIndices(materials, materialIndices.begin(), materialCount);
	}

	NpShape* npShape;
	{
		Ps::Mutex::ScopedLock lock(mShapePoolLock);
		PxU16* mi = materialIndices.begin(); // required to placate pool constructor arg passing
		npShape = mShapePool.construct(geometry, shapeFlags, mi, materialCount, isExclusive);
	}

	if(!npShape)
		return NULL;

	for (PxU32 i=0; i < materialCount; i++)
		static_cast<NpMaterial*>(npShape->getMaterial(i))->incRefCount();

	addShape(npShape);

	return npShape;
}

void NpFactory::releaseShapeToPool(NpShape& shape)
{
	PX_ASSERT(shape.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY);
	Ps::Mutex::ScopedLock lock(mShapePoolLock);
	mShapePool.destroy(&shape);
}



PxU32 NpFactory::getNbShapes() const
{
	return mShapeTracking.size();
}

PxU32 NpFactory::getShapes(PxShape** userBuffer, PxU32 bufferSize, PxU32 startIndex)	const
{
	if(mShapeTracking.size()<startIndex)
		return 0;
	PxU32 count = PxMax(bufferSize, mShapeTracking.size()-startIndex);
	PxShape*const *shapes = mShapeTracking.getEntries();
	for(PxU32 i=0;i<count;i++)
		userBuffer[i] = shapes[startIndex+i];
	return count;
}


PxRigidStatic* NpFactory::createRigidStatic(const PxTransform& pose)
{
	PX_CHECK_AND_RETURN_NULL(pose.isValid(), "pose is not valid. createRigidStatic returns NULL.");

	NpRigidStatic* npActor;

	{
		Ps::Mutex::ScopedLock lock(mRigidStaticPoolLock);
		npActor = mRigidStaticPool.construct(pose);
	}

	addRigidStatic(npActor);
	return npActor;
}

void NpFactory::releaseRigidStaticToPool(NpRigidStatic& rigidStatic)
{
	PX_ASSERT(rigidStatic.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY);
	Ps::Mutex::ScopedLock lock(mRigidStaticPoolLock);
	mRigidStaticPool.destroy(&rigidStatic);
}

PxRigidDynamic* NpFactory::createRigidDynamic(const PxTransform& pose)
{
	PX_CHECK_AND_RETURN_NULL(pose.isValid(), "pose is not valid. createRigidDynamic returns NULL.");

	NpRigidDynamic* npBody;
	{
		Ps::Mutex::ScopedLock lock(mRigidDynamicPoolLock);
		npBody = mRigidDynamicPool.construct(pose);
	}
	addRigidDynamic(npBody);
	return npBody;
}


void NpFactory::releaseRigidDynamicToPool(NpRigidDynamic& rigidDynamic)
{
	PX_ASSERT(rigidDynamic.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY);
	Ps::Mutex::ScopedLock lock(mRigidDynamicPoolLock);
	mRigidDynamicPool.destroy(&rigidDynamic);
}

///////////////////////////////////////////////////////////////////////////////

// PT: this function is here to minimize the amount of locks when deserializing a collection
void NpFactory::addCollection(const Cm::Collection& collection)
{
	
	PxU32 nb = collection.getNbObjects();
	const Ps::Pair<PxBase* const, PxSerialObjectId>* entries = collection.internalGetObjects();
	// PT: we take the lock only once, here
	Ps::Mutex::ScopedLock lock(mTrackingMutex);

	for(PxU32 i=0;i<nb;i++)
	{
		PxBase* s = entries[i].first;
		const PxType serialType = s->getConcreteType();
//////////////////////////
		if(serialType==PxConcreteType::eHEIGHTFIELD)
		{
			Gu::HeightField* gu = static_cast<Gu::HeightField*>(s);
			gu->setMeshFactory(this);
			addHeightField(gu, false);
		}
		else if(serialType==PxConcreteType::eCONVEX_MESH)
		{
			Gu::ConvexMesh* gu = static_cast<Gu::ConvexMesh*>(s);
			gu->setMeshFactory(this);
			addConvexMesh(gu, false);
		}
		else if(serialType==PxConcreteType::eTRIANGLE_MESH_BVH33 || serialType==PxConcreteType::eTRIANGLE_MESH_BVH34)
		{
			Gu::TriangleMesh* gu = static_cast<Gu::TriangleMesh*>(s);
			gu->setMeshFactory(this);
			addTriangleMesh(gu, false);
		}
//////////////////////////
#if PX_USE_CLOTH_API
		else if (serialType==PxConcreteType::eCLOTH_FABRIC)
		{
			NpClothFabric* np = static_cast<NpClothFabric*>(s);
			// PT: TODO: investigate why cloth don't need a "setMeshFactory" call here
			addClothFabric(np, false);
		}
#endif
		else if(serialType==PxConcreteType::eRIGID_DYNAMIC)
		{
			NpRigidDynamic* np = static_cast<NpRigidDynamic*>(s);
			addRigidDynamic(np, false);
		}
		else if(serialType==PxConcreteType::eRIGID_STATIC)
		{
			NpRigidStatic* np = static_cast<NpRigidStatic*>(s);
			addRigidStatic(np, false);
		}
		else if(serialType==PxConcreteType::eSHAPE)
		{
			NpShape* np = static_cast<NpShape*>(s);
			addShape(np, false);
		}
		else if(serialType==PxConcreteType::eMATERIAL)
		{
		}
		else if(serialType==PxConcreteType::eCONSTRAINT)
		{
			NpConstraint* np = static_cast<NpConstraint*>(s);
			addConstraint(np, false);
		}
#if PX_USE_CLOTH_API
		else if (serialType==PxConcreteType::eCLOTH)
		{
			NpCloth* np = static_cast<NpCloth*>(s);
			addCloth(np, false);
		}
#endif
#if PX_USE_PARTICLE_SYSTEM_API
		else if(serialType==PxConcreteType::ePARTICLE_SYSTEM)
		{
			NpParticleSystem* np = static_cast<NpParticleSystem*>(s);
			addParticleSystem(np, false);
		}
		else if(serialType==PxConcreteType::ePARTICLE_FLUID)
		{
			NpParticleFluid* np = static_cast<NpParticleFluid*>(s);
			addParticleFluid(np, false);
		}
#endif
		else if(serialType==PxConcreteType::eAGGREGATE)
		{
			NpAggregate* np = static_cast<NpAggregate*>(s);
			addAggregate(np, false);

			// PT: TODO: double-check this.... is it correct?			
			for(PxU32 j=0;j<np->getCurrentSizeFast();j++)
			{
				PxBase* actor = np->getActorFast(j);
				const PxType serialType1 = actor->getConcreteType();

				if(serialType1==PxConcreteType::eRIGID_STATIC)
					addRigidStatic(static_cast<NpRigidStatic*>(actor), false);
				else if(serialType1==PxConcreteType::eRIGID_DYNAMIC)
					addRigidDynamic(static_cast<NpRigidDynamic*>(actor), false);
				else if(serialType1==PxConcreteType::ePARTICLE_SYSTEM)
				{}
				else if(serialType1==PxConcreteType::ePARTICLE_FLUID)
				{}
				else if(serialType1==PxConcreteType::eARTICULATION_LINK)
				{}
				else PX_ASSERT(0);
			}
		}
		else if(serialType==PxConcreteType::eARTICULATION)
		{
			NpArticulation* np = static_cast<NpArticulation*>(s);
			addArticulation(np, false);
		}
		else if(serialType==PxConcreteType::eARTICULATION_LINK)
		{
//			NpArticulationLink* np = static_cast<NpArticulationLink*>(s);
		}
		else if(serialType==PxConcreteType::eARTICULATION_JOINT)
		{
//			NpArticulationJoint* np = static_cast<NpArticulationJoint*>(s);
		}
		else
		{
//			assert(0);
		}
	}
}

///////////////////////////////////////////////////////////////////////////////

#if PX_SUPPORT_GPU_PHYSX
void NpFactory::notifyReleaseTriangleMesh(const PxTriangleMesh& tm)
{
	NpPhysics::getInstance().getNpPhysicsGpu().releaseTriangleMeshMirror(tm);
}

void NpFactory::notifyReleaseHeightField(const PxHeightField& hf)
{
	NpPhysics::getInstance().getNpPhysicsGpu().releaseHeightFieldMirror(hf);
}

void NpFactory::notifyReleaseConvexMesh(const PxConvexMesh& cm)
{
	NpPhysics::getInstance().getNpPhysicsGpu().releaseConvexMeshMirror(cm);
}
#endif

#if PX_SUPPORT_PVD
void NpFactory::setNpFactoryListener( NpFactoryListener& inListener)
{
	mNpFactoryListener = &inListener;
	addFactoryListener(inListener);
}
#endif
///////////////////////////////////////////////////////////////////////////////

// these calls are issued from the Scb layer when buffered deletes are issued. 
// TODO: we should really push these down as a virtual interface that is part of Scb's reqs
// to eliminate this link-time dep.


static void NpDestroyRigidActor(Scb::RigidStatic& scb)
{
	NpRigidStatic* np = const_cast<NpRigidStatic*>(getNpRigidStatic(&scb));

	void* ud = np->userData;

	if(np->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY)
		NpFactory::getInstance().releaseRigidStaticToPool(*np);
	else
		np->~NpRigidStatic();

	NpPhysics::getInstance().notifyDeletionListenersMemRelease(np, ud);
}

static void NpDestroyRigidDynamic(Scb::Body& scb)
{
	NpRigidDynamic* np = const_cast<NpRigidDynamic*>(getNpRigidDynamic(&scb));

	void* ud = np->userData;
	if(np->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY)
		NpFactory::getInstance().releaseRigidDynamicToPool(*np);
	else
		np->~NpRigidDynamic();
	NpPhysics::getInstance().notifyDeletionListenersMemRelease(np, ud);
}

#if PX_USE_PARTICLE_SYSTEM_API
static void NpDestroyParticleSystem(Scb::ParticleSystem& scb)
{	
	if(scb.getActorType() == PxActorType::ePARTICLE_SYSTEM)
	{
		NpParticleSystem* np = const_cast<NpParticleSystem*>(getNpParticleSystem(&scb));

		void* ud = np->userData;
		if(np->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY)
			NpFactory::getInstance().releaseParticleSystemToPool(*np);
		else
			np->~NpParticleSystem();	
		NpPhysics::getInstance().notifyDeletionListenersMemRelease(np, ud);
	}
	else
	{
		NpParticleFluid* np = const_cast<NpParticleFluid*>(getNpParticleFluid(&scb));

		void* ud = np->userData;
		if(np->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY)
			NpFactory::getInstance().releaseParticleFluidToPool(*np);
		else
			np->~NpParticleFluid();	
		NpPhysics::getInstance().notifyDeletionListenersMemRelease(np, ud);
	}
}
#endif

static void NpDestroyArticulationLink(Scb::Body& scb)
{
	NpArticulationLink* np = const_cast<NpArticulationLink*>(getNpArticulationLink(&scb));

	void* ud = np->userData;
	if(np->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY)
		NpFactory::getInstance().releaseArticulationLinkToPool(*np);
	else
		np->~NpArticulationLink();	
	NpPhysics::getInstance().notifyDeletionListenersMemRelease(np, ud);
}

static void NpDestroyArticulationJoint(Scb::ArticulationJoint& scb)
{
	NpArticulationJoint* np = const_cast<NpArticulationJoint*>(getNpArticulationJoint(&scb));

	if(np->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY)
		NpFactory::getInstance().releaseArticulationJointToPool(*np);
	else
		np->~NpArticulationJoint();	
	NpPhysics::getInstance().notifyDeletionListenersMemRelease(np, NULL);
}

static void NpDestroyArticulation(Scb::Articulation& scb)
{
	NpArticulation* np = const_cast<NpArticulation*>(getNpArticulation(&scb));

	void* ud = np->userData;
	if(np->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY)
		NpFactory::getInstance().releaseArticulationToPool(*np);
	else
		np->~NpArticulation();	
	NpPhysics::getInstance().notifyDeletionListenersMemRelease(np, ud);
}

static void NpDestroyAggregate(Scb::Aggregate& scb)
{
	NpAggregate* np = const_cast<NpAggregate*>(getNpAggregate(&scb));

	if(np->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY)
		NpFactory::getInstance().releaseAggregateToPool(*np);
	else
		np->~NpAggregate();

	NpPhysics::getInstance().notifyDeletionListenersMemRelease(np, NULL);
}

static void NpDestroyShape(Scb::Shape& scb)
{
	NpShape* np = const_cast<NpShape*>(getNpShape(&scb));

	void* ud = np->userData;

	if(np->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY)
		NpFactory::getInstance().releaseShapeToPool(*np);
	else
		np->~NpShape();

	NpPhysics::getInstance().notifyDeletionListenersMemRelease(np, ud);
}

static void NpDestroyConstraint(Scb::Constraint& scb)
{
	const size_t offset = size_t(&(reinterpret_cast<NpConstraint*>(0)->getScbConstraint()));
	NpConstraint* np = reinterpret_cast<NpConstraint*>(reinterpret_cast<char*>(&scb)-offset);
	if(np->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY)
		NpFactory::getInstance().releaseConstraintToPool(*np);
	else
		np->~NpConstraint();
	NpPhysics::getInstance().notifyDeletionListenersMemRelease(np, NULL);
}

#if PX_USE_CLOTH_API
static void NpDestroyCloth(Scb::Cloth& scb)
{
	NpCloth* np = const_cast<NpCloth*>(getNpCloth(&scb));

	void* ud = np->userData;
	if(np->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY)
		NpFactory::getInstance().releaseClothToPool(*np);
	else
		np->~NpCloth();
	NpPhysics::getInstance().notifyDeletionListenersMemRelease(np, ud);
}
#endif

namespace physx
{
	void NpDestroy(Scb::Base& base)
	{
		switch(base.getScbType())
		{
			case ScbType::eSHAPE_EXCLUSIVE:
			case ScbType::eSHAPE_SHARED:				{ NpDestroyShape(static_cast<Scb::Shape&>(base));							}break;
			case ScbType::eBODY:						{ NpDestroyRigidDynamic(static_cast<Scb::Body&>(base));						}break;
			case ScbType::eBODY_FROM_ARTICULATION_LINK:	{ NpDestroyArticulationLink(static_cast<Scb::Body&>(base));					}break;
			case ScbType::eRIGID_STATIC:				{ NpDestroyRigidActor(static_cast<Scb::RigidStatic&>(base));				}break;
			case ScbType::eCONSTRAINT:					{ NpDestroyConstraint(static_cast<Scb::Constraint&>(base));					}break;
#if PX_USE_PARTICLE_SYSTEM_API
			case ScbType::ePARTICLE_SYSTEM:				{ NpDestroyParticleSystem(static_cast<Scb::ParticleSystem&>(base));			}break;
#endif
			case ScbType::eARTICULATION:				{ NpDestroyArticulation(static_cast<Scb::Articulation&>(base));				}break;
			case ScbType::eARTICULATION_JOINT:			{ NpDestroyArticulationJoint(static_cast<Scb::ArticulationJoint&>(base));	}break;
			case ScbType::eAGGREGATE:					{ NpDestroyAggregate(static_cast<Scb::Aggregate&>(base));					}break;
#if PX_USE_CLOTH_API
			case ScbType::eCLOTH:						{ NpDestroyCloth(static_cast<Scb::Cloth&>(base));							}break;
#endif
			case ScbType::eUNDEFINED:
			case ScbType::eTYPE_COUNT:
				PX_ALWAYS_ASSERT_MESSAGE("NpDestroy: missing type!");
				break;
		}
	}
}