Subversion Repository Public Repository

Divide-Dependencies

This repository has no backups
This repository's network speed is throttled to 100KB/sec

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
//
// 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) 2018 NVIDIA Corporation. All rights reserved.



#include "ApexDefs.h"

#include "Apex.h"
#include "ClothingScene.h"
#include "ClothingActorImpl.h"
#include "ClothingAssetImpl.h"
#include "ClothingCooking.h"
#include "SceneIntl.h"
#include "ClothingRenderProxyImpl.h"

#include "DebugRenderParams.h"
#include "ProfilerCallback.h"

#include "Simulation.h"

#include "PsThread.h"
#include "ApexUsingNamespace.h"
#include "PsAtomic.h"

#if APEX_CUDA_SUPPORT
#include "PxGpuDispatcher.h"
#endif

#include "ApexPvdClient.h"

namespace nvidia
{
namespace clothing
{

ClothingScene::ClothingScene(ModuleClothingImpl& _module, SceneIntl& scene, RenderDebugInterface* renderDebug, ResourceList& list)
	: mModule(&_module)
	, mApexScene(&scene)
#if PX_PHYSICS_VERSION_MAJOR == 3
	, mPhysXScene(NULL)
#endif
	, mSumBenefit(0)
	, mWaitForSolverTask(NULL)
	, mSimulationTask(NULL)
	, mSceneRunning(0)
	, mRenderDebug(renderDebug)
	, mDebugRenderParams(NULL)
	, mClothingDebugRenderParams(NULL)
	, mCurrentCookingTask(NULL)
	, mCurrentSimulationDelta(0)
	, mAverageSimulationFrequency(0.0f)
#ifndef _DEBUG
	, mFramesCount(0)
	, mSimulatedTime(0.f)
	, mTimestep(0.f)
#endif
	, mCpuFactory(NULL, NULL)
#if APEX_CUDA_SUPPORT
	, mGpuFactory(NULL, NULL)
	, mPhysXGpuIndicator(NULL)
#endif
{
	mClothingBeforeTickStartTask.setScene(this);
	list.add(*this);

	/* Initialize reference to ClothingDebugRenderParams */
	mDebugRenderParams = DYNAMIC_CAST(DebugRenderParams*)(mApexScene->getDebugRenderParams());
	PX_ASSERT(mDebugRenderParams);
	NvParameterized::Handle handle(*mDebugRenderParams), memberHandle(*mDebugRenderParams);
	int size;

	if (mDebugRenderParams->getParameterHandle("moduleName", handle) == NvParameterized::ERROR_NONE)
	{
		handle.getArraySize(size, 0);
		handle.resizeArray(size + 1);
		if (handle.getChildHandle(size, memberHandle) == NvParameterized::ERROR_NONE)
		{
			memberHandle.initParamRef(ClothingDebugRenderParams::staticClassName(), true);
		}
	}

	/* Load reference to ClothingDebugRenderParams */
	NvParameterized::Interface* refPtr = NULL;
	memberHandle.getParamRef(refPtr);
	mClothingDebugRenderParams = DYNAMIC_CAST(ClothingDebugRenderParams*)(refPtr);
	PX_ASSERT(mClothingDebugRenderParams);

	mLastSimulationDeltas.reserve(mModule->getAvgSimFrequencyWindowSize());

	mWaitForSolverTask = PX_NEW(WaitForSolverTask)(this);

	mSimulationTask = PX_NEW(ClothingSceneSimulateTask)(mApexScene, this, mModule, GetInternalApexSDK()->getProfileZoneManager());
	mSimulationTask->setWaitTask(mWaitForSolverTask);
}



ClothingScene::~ClothingScene()
{
}



void ClothingScene::simulate(float elapsedTime)
{
	for (uint32_t i = 0; i < mActorArray.size(); i++)
	{
		ClothingActorImpl* clothingActor = static_cast<ClothingActorImpl*>(mActorArray[i]);
		clothingActor->waitForFetchResults();
	}

	if (mLastSimulationDeltas.size() < mLastSimulationDeltas.capacity())
	{
		mCurrentSimulationDelta = mLastSimulationDeltas.size();
		mLastSimulationDeltas.pushBack(elapsedTime);
	}
	else if (mLastSimulationDeltas.size() > 0)
	{
		mCurrentSimulationDelta = (mCurrentSimulationDelta + 1) % mLastSimulationDeltas.size();
		mLastSimulationDeltas[mCurrentSimulationDelta] = elapsedTime;
	}

	float temp = 0.0f;
	for (uint32_t i = 0; i < mLastSimulationDeltas.size(); i++)
		temp += mLastSimulationDeltas[i];

	if (temp > 0.0f)
		mAverageSimulationFrequency = (float)(mLastSimulationDeltas.size()) / temp;
	else
		mAverageSimulationFrequency = 0.0f;

	tickRenderProxies();
}



bool ClothingScene::needsManualSubstepping() const
{
	// we could test if any of them is being simulated, but assuming some sane budget settings
	// there will always be >0 clothing actors simulated if there are any present

	if (!mModule->allowApexWorkBetweenSubsteps())
	{
		return false;
	}

	// PH: new rule. The actual simulation object needs to request this too!
	bool manualSubstepping = false;
	for (uint32_t i = 0; i < mActorArray.size(); i++)
	{
		ClothingActorImpl* clothingActor = static_cast<ClothingActorImpl*>(mActorArray[i]);
		manualSubstepping |= clothingActor->needsManualSubstepping();
	}
	return manualSubstepping;
}



void ClothingScene::interStep(uint32_t substepNumber, uint32_t maxSubSteps)
{
	for (uint32_t i = 0; i < mActorArray.size(); i++)
	{
		ClothingActorImpl* clothingActor = static_cast<ClothingActorImpl*>(mActorArray[i]);

		if (clothingActor->needsManualSubstepping())
		{
			clothingActor->tickSynchBeforeSimulate_LocksPhysX(0.0f, 0.0f, substepNumber, maxSubSteps);
			clothingActor->skinPhysicsMesh(maxSubSteps > 1, (float)(substepNumber + 1) / (float)maxSubSteps);
			clothingActor->updateConstrainPositions_LocksPhysX();
			clothingActor->applyCollision_LocksPhysX();
		}
	}
}



void ClothingScene::submitTasks(float elapsedTime, float substepSize, uint32_t numSubSteps)
{
	PxTaskManager* taskManager = mApexScene->getTaskManager();
	const bool isFinalStep = mApexScene->isFinalStep();

	for (uint32_t i = 0; i < mActorArray.size(); i++)
	{
		ClothingActorImpl* clothingActor = static_cast<ClothingActorImpl*>(mActorArray[i]);
#if APEX_UE4
		clothingActor->initBeforeTickTasks(elapsedTime, substepSize, numSubSteps, taskManager, 0, 0);
#else
		clothingActor->initBeforeTickTasks(elapsedTime, substepSize, numSubSteps);
#endif

		if (isFinalStep)
		{
			clothingActor->submitTasksDuring(taskManager);
		}
	}

	taskManager->submitUnnamedTask(mClothingBeforeTickStartTask);

	mSimulationTask->setDeltaTime(elapsedTime);
	if (elapsedTime > 0.0f)
	{
		taskManager->submitUnnamedTask(*mSimulationTask);
		taskManager->submitUnnamedTask(*mWaitForSolverTask);
	}
}



void ClothingScene::setTaskDependencies()
{
	PxTaskManager* taskManager = mApexScene->getTaskManager();
	const PxTaskID physxTick = taskManager->getNamedTask(AST_PHYSX_SIMULATE);
	PxTask* physxTickTask = taskManager->getTaskFromID(physxTick);

#if APEX_DURING_TICK_TIMING_FIX
	const PxTaskID duringFinishedId = taskManager->getNamedTask(AST_DURING_TICK_COMPLETE);
#else
	const PxTaskID duringFinishedId = taskManager->getNamedTask(AST_PHYSX_CHECK_RESULTS);
#endif

	bool startSimulateTask = mSimulationTask->getDeltaTime() > 0;

#if APEX_UE4
	PxTask* dependentTask = physxTickTask;
	PxTaskID duringStartId = physxTick;

	if (startSimulateTask)
	{
		dependentTask = mSimulationTask;
		duringStartId = mSimulationTask->getTaskID();
		mSimulationTask->startAfter(mClothingBeforeTickStartTask.getTaskID());
	}
#else
	PxTaskID duringStartId = startSimulateTask ? mSimulationTask->getTaskID() : physxTick;
#endif
	const bool isFinalStep = mApexScene->isFinalStep();

	for (uint32_t i = 0; i < mActorArray.size(); i++)
	{
		ApexActor* actor = mActorArray[i];
		ClothingActorImpl* clothingActor = static_cast<ClothingActorImpl*>(actor);
#if !APEX_UE4
		PxTask* dependentTask = physxTickTask;
		if (startSimulateTask)
		{
			dependentTask = mSimulationTask;
			mSimulationTask->startAfter(mClothingBeforeTickStartTask.getTaskID());
		}
#endif

		clothingActor->setTaskDependenciesBefore(dependentTask);

		if (isFinalStep)
		{
			// PH:	daisy chain the during tasks to not trash other (=PhysX) tasks' cache etc.
			// HL:	found a case where duringTick becomes the bottleneck because of the daisy chaining

			/*duringStartId = */clothingActor->setTaskDependenciesDuring(duringStartId, duringFinishedId);
		}
	}
#if APEX_UE4
	mSimulationTask->startAfter(mClothingBeforeTickStartTask.getTaskID());
#endif

	mClothingBeforeTickStartTask.finishBefore(physxTick);

	if (startSimulateTask)
	{
		mSimulationTask->finishBefore(physxTick);
		mWaitForSolverTask->startAfter(mSimulationTask->getTaskID());
		mWaitForSolverTask->startAfter(duringFinishedId);
		mWaitForSolverTask->finishBefore(taskManager->getNamedTask(AST_PHYSX_FETCH_RESULTS));
	}
}



void ClothingScene::fetchResults()
{
	if (!mApexScene->isFinalStep())
	{
		return;
	}

	PX_PROFILE_ZONE("ClothingScene::fetchResults", GetInternalApexSDK()->getContextId());

	// make sure to start cooking tasks if possible (and delete old ones)
	submitCookingTask(NULL);

	if (!mModule->allowAsyncFetchResults())
	{
		for (uint32_t i = 0; i < mActorArray.size(); i++)
		{
			ClothingActorImpl* clothingActor = static_cast<ClothingActorImpl*>(mActorArray[i]);
			clothingActor->waitForFetchResults();
		}
	}

	// TBD - if we need to send callbacks to the user, add them here
}


#if PX_PHYSICS_VERSION_MAJOR == 3

void ClothingScene::setModulePhysXScene(PxScene* newPhysXScene)
{
	if (mPhysXScene == newPhysXScene)
	{
		return;
	}

	PxScene* oldPhysXScene = mPhysXScene;

	mPhysXScene = newPhysXScene;
	for (uint32_t i = 0; i < mActorArray.size(); ++i)
	{
		// downcast
		ClothingActorImpl* actor = static_cast<ClothingActorImpl*>(mActorArray[i]);

		actor->setPhysXScene(newPhysXScene);
	}

	mClothingAssetsMutex.lock();
	mClothingAssets.clear();
	mClothingAssetsMutex.unlock();

#if APEX_CUDA_SUPPORT
	{
		if (mGpuFactory.factory != NULL && oldPhysXScene != NULL)
		{
			mSimulationTask->clearGpuSolver();
			PX_ASSERT(mApexScene->getTaskManager() == oldPhysXScene->getTaskManager());
			if (newPhysXScene != NULL)
			{
				mModule->releaseClothFactory(oldPhysXScene->getTaskManager()->getGpuDispatcher()->getCudaContextManager());
			}
			mGpuFactory.clear();
		}
	}
#else 
	{
		if (mCpuFactory.factory != NULL && oldPhysXScene != NULL)
		{
			if (newPhysXScene != NULL)
			{
				mModule->releaseClothFactory(NULL);
			}
			mCpuFactory.clear();
		}
	}
#endif
}

#endif

void ClothingScene::release()
{
	mModule->releaseModuleSceneIntl(*this);
}



void ClothingScene::visualize()
{
#ifdef WITHOUT_DEBUG_VISUALIZE
#else
	if (!mClothingDebugRenderParams->Actors)
	{
		return;
	}

	for (uint32_t i = 0; i < mActorArray.size(); i++)
	{
		// downcast
		ClothingActorImpl* actor = static_cast<ClothingActorImpl*>(mActorArray[i]);
		actor->visualize();
	}
#endif
}



Module* ClothingScene::getModule()
{
	return mModule;
}



bool ClothingScene::isSimulating() const
{
	if (mApexScene != NULL)
	{
		return mApexScene->isSimulating();
	}

	return false;
}



void ClothingScene::registerAsset(ClothingAssetImpl* asset)
{
	mClothingAssetsMutex.lock();
	for (uint32_t i = 0; i < mClothingAssets.size(); i++)
	{
		if (mClothingAssets[i] == asset)
		{
			mClothingAssetsMutex.unlock();
			return;
		}
	}
	mClothingAssets.pushBack(asset);
	mClothingAssetsMutex.unlock();
}



void ClothingScene::unregisterAsset(ClothingAssetImpl* asset)
{
	// remove assets from assets list
	mClothingAssetsMutex.lock();
	for (int32_t i = (int32_t)mClothingAssets.size() - 1; i >= 0; i--)
	{
		if (mClothingAssets[(uint32_t)i] == asset)
		{
			mClothingAssets.replaceWithLast((uint32_t)i);
		}
	}
	mClothingAssetsMutex.unlock();

	removeRenderProxies(asset);
}



void ClothingScene::removeRenderProxies(ClothingAssetImpl* asset)
{
	// delete all render proxies that have the RenderMeshAsset
	// of this ClothingAssetImpl
	mRenderProxiesLock.lock();
	uint32_t numGraphicalMeshes = asset->getNumGraphicalMeshes();
	for (uint32_t i = 0; i < numGraphicalMeshes; ++i)
	{
		RenderMeshAssetIntl* renderMeshAsset = asset->getGraphicalMesh(i);

		Array<ClothingRenderProxyImpl*>& renderProxies = mRenderProxies[renderMeshAsset];
		for (int32_t i = (int32_t)renderProxies.size()-1; i >= 0 ; --i)
		{
			ClothingRenderProxyImpl* renderProxy = renderProxies[(uint32_t)i];
			if (renderProxy->getTimeInPool() > 0)
			{
				PX_DELETE(renderProxies[(uint32_t)i]);
			}
			else
			{
				renderProxy->notifyAssetRelease();
			}
		}
		renderProxies.clear();
		mRenderProxies.erase(renderMeshAsset);
	}
	mRenderProxiesLock.unlock();
}



uint32_t ClothingScene::submitCookingTask(ClothingCookingTask* newTask)
{
	mCookingTaskMutex.lock();

	ClothingCookingTask** currPointer = &mCurrentCookingTask;
	ClothingCookingTask* lastTask = NULL;

	uint32_t numRunning = 0;
	uint32_t numReleased = 0;

	while (*currPointer != NULL)
	{
		PX_ASSERT(lastTask == NULL || currPointer == &lastTask->nextTask);
		if ((*currPointer)->readyForRelease())
		{
			ClothingCookingTask* releaseMe = *currPointer;
			*currPointer = releaseMe->nextTask;
			delete releaseMe;
			numReleased++;
		}
		else
		{
			lastTask = *currPointer;
			numRunning += lastTask->waitsForBeingScheduled() ? 0 : 1;
			currPointer = &(*currPointer)->nextTask;
		}
	}

	// set the linked list
	*currPointer = newTask;
	if (newTask != NULL)
	{
		PX_ASSERT(mApexScene->getTaskManager() != NULL);
		newTask->initCooking(*mApexScene->getTaskManager(), NULL);
	}

	if (numRunning == 0 && mCurrentCookingTask != NULL)
	{
		PX_ASSERT(mCurrentCookingTask->waitsForBeingScheduled());
		mCurrentCookingTask->removeReference();
	}

	mCookingTaskMutex.unlock();

	return numReleased;
}



void ClothingScene::destroy()
{
	for (uint32_t i = 0; i < mActorArray.size(); i++)
	{
		ClothingActorImpl* clothingActor = static_cast<ClothingActorImpl*>(mActorArray[i]);
		clothingActor->waitForFetchResults();
	}

	removeAllActors();

	mClothingAssetsMutex.lock();
	for (uint32_t i = 0 ; i < mClothingAssets.size(); i++)
	{
		// for PhysX3: making sure that fabrics (in assets) are released before the factories (in mSimulationTask)
		mClothingAssets[i]->releaseCookedInstances();
	}
	mClothingAssets.clear();
	mClothingAssetsMutex.unlock();

	// clear render list
	for (HashMap<RenderMeshAssetIntl*, Array<ClothingRenderProxyImpl*> >::Iterator iter = mRenderProxies.getIterator(); !iter.done(); ++iter)
	{
		Array<ClothingRenderProxyImpl*>& renderProxies = iter->second;

		for (int32_t i = (int32_t)renderProxies.size()-1; i >= 0 ; --i)
		{
			uint32_t timeInPool = renderProxies[(uint32_t)i]->getTimeInPool();
			if (timeInPool > 0)
			{
				PX_DELETE(renderProxies[(uint32_t)i]);
				renderProxies.replaceWithLast((uint32_t)i);
			}
			else
			{
				// actually the scene is released, but we just want to make sure
				// that the render proxy deletes itself when it's returned next time
				renderProxies[(uint32_t)i]->notifyAssetRelease();
			}
		}

		renderProxies.clear();
	}
	//mRenderProxies.clear();

	while (mCurrentCookingTask != NULL)
	{
		submitCookingTask(NULL);
		nvidia::Thread::sleep(0); // wait for remaining cooking tasks to finish
	}

	if (mSimulationTask != NULL)
	{
#if PX_PHYSICS_VERSION_MAJOR == 3
		setModulePhysXScene(NULL); // does some cleanup necessary here. Only needed when module gets deleted without the apex scene being deleted before!
#elif APEX_CUDA_SUPPORT
		if (mGpuFactory.factory != NULL)
		{
			mSimulationTask->clearGpuSolver();
			mGpuFactory.clear();
		}
#endif
		PX_DELETE(mSimulationTask);
		mSimulationTask = NULL;
	}

	if (mWaitForSolverTask != NULL)
	{
		PX_DELETE(mWaitForSolverTask);
		mWaitForSolverTask = NULL;
	}

	{
		if (mCpuFactory.factory != NULL)
		{
			mCpuFactory.clear();
		}

#if APEX_CUDA_SUPPORT
		PX_ASSERT(mGpuFactory.factory == NULL);

		ApexSDKIntl* apexSdk = GetInternalApexSDK();
		apexSdk->unregisterPhysXIndicatorGpuClient(mPhysXGpuIndicator);
		mPhysXGpuIndicator = NULL;
#endif
	}

	mApexScene->moduleReleased(*this);
	delete this;
}



void ClothingScene::ClothingBeforeTickStartTask::run()
{
#ifdef PROFILE
	PIXBeginNamedEvent(0, "ClothingBeforeTickStartTask");
#endif
	for (uint32_t i = 0; i < m_pScene->mActorArray.size(); ++i)
	{
		ClothingActorImpl* actor = static_cast<ClothingActorImpl*>(m_pScene->mActorArray[i]);

		actor->startBeforeTickTask();
	}
#ifdef PROFILE
	PIXEndNamedEvent();
#endif
}



const char* ClothingScene::ClothingBeforeTickStartTask::getName() const
{
#if APEX_UE4
	return CLOTHING_BEFORE_TICK_START_TASK_NAME;
#else
	return "ClothingScene::ClothingBeforeTickStartTask";
#endif
}



ClothFactory ClothingScene::getClothFactory(bool& useCuda)
{
#if APEX_CUDA_SUPPORT
	if (useCuda)
	{
		if (mGpuFactory.factory == NULL)
		{
			PxCudaContextManager* contextManager = NULL;
			PxGpuDispatcher* gpuDispatcher = mApexScene->getTaskManager()->getGpuDispatcher();
			if (gpuDispatcher != NULL)
			{
				contextManager = gpuDispatcher->getCudaContextManager();
			}

			if (contextManager != NULL)
			{
				mGpuFactory = mModule->createClothFactory(contextManager);
				if (mGpuFactory.factory != NULL)
				{
					ApexSDKIntl* apexSdk = GetInternalApexSDK();
					mPhysXGpuIndicator = apexSdk->registerPhysXIndicatorGpuClient();
				}
			}
		}

		//APEX_DEBUG_INFO("Gpu Factory %p", mGpuFactory);
		if (mGpuFactory.factory != NULL)
		{
			return mGpuFactory;
		}
		else
		{
			APEX_DEBUG_INFO("Gpu Factory could not be created");
			useCuda = false;
		}
	}
	
	if (!useCuda)
#else
	PX_UNUSED(useCuda);
#endif
	{
		if (mCpuFactory.factory == NULL)
		{
			mCpuFactory = mModule->createClothFactory(NULL);
		}

		//APEX_DEBUG_INFO("Cpu Factory %p", mCpuFactory.factory);
		return mCpuFactory;
	}

#if APEX_CUDA_SUPPORT
	PX_ALWAYS_ASSERT_MESSAGE("this code path is unreachable, at least it used to be.");
	return ClothFactory(NULL, NULL);
#endif
}



cloth::Solver* ClothingScene::getClothSolver(bool useCuda)
{
	ClothFactory factory(NULL, NULL);
#if APEX_CUDA_SUPPORT
	if (useCuda)
	{
		factory = mGpuFactory;
	}
	else
#else
	PX_UNUSED(useCuda);
#endif
	{
		factory = mCpuFactory;
	}

	PX_ASSERT(factory.factory != NULL);
	if (factory.factory != NULL)
	{
		return mSimulationTask->getSolver(factory);
	}

	return NULL;
}



void ClothingScene::lockScene()
{
	mSceneLock.lock();

	if (mSceneRunning == 1)
	{
		APEX_INVALID_OPERATION("The scene is running while the scene write lock is being acquired!");
		PX_ALWAYS_ASSERT();
	}
}



void ClothingScene::unlockScene()
{
	mSceneLock.unlock();
}



void ClothingScene::setSceneRunning(bool on)
{
#ifndef _DEBUG
	int32_t newValue;
	if (on)
	{
		APEX_CHECK_STAT_TIMER("--------- Start ClothingSimulationTime");
		mClothingSimulationTime.getElapsedSeconds();

		newValue = nvidia::atomicIncrement(&mSceneRunning);
	}
	else
	{
		StatValue dataVal;
		dataVal.Float = (float)(1000.0f * mClothingSimulationTime.getElapsedSeconds());
		APEX_CHECK_STAT_TIMER("--------- Stop ClothingSimulationTime");
		mApexScene->setApexStatValue(SceneIntl::ClothingSimulationTime, dataVal);

		// Warn if simulation time was bigger than timestep for 10 or more consecutive frames
		float simulatedTime = 1000.0f * mApexScene->getElapsedTime();
		if (simulatedTime < dataVal.Float)
		{
			mFramesCount++;
			mSimulatedTime	+= simulatedTime;
			mTimestep		+= dataVal.Float;
		}

		if (mFramesCount >= 10)
		{
			float averageSimulatedTime = mSimulatedTime / (float)mFramesCount;
			float averageTimestep = mTimestep / (float)mFramesCount;
			APEX_DEBUG_WARNING("Cloth complexity in scene is too high to be simulated in real time for 10 consecutive frames. (Average Delta Time: %f ms, Average Simulation Time: %f ms)", 
								averageSimulatedTime, averageTimestep);
			mFramesCount	= 0;
			mSimulatedTime	= 0.f;
			mTimestep		= 0.f;
		}

		newValue = nvidia::atomicDecrement(&mSceneRunning);
	}

	if (newValue != (on ? 1 : 0))
	{
		APEX_INTERNAL_ERROR("scene running state was not tracked properly!: on = %s, prevValue = %d", on ? "true" : "false", newValue);
	}
#else
	PX_UNUSED(on);
#endif
}



void ClothingScene::embeddedPostSim()
{
	for (uint32_t i = 0; i < mActorArray.size(); i++)
	{
		ClothingActorImpl* clothingActor = static_cast<ClothingActorImpl*>(mActorArray[i]);
		clothingActor->startFetchTasks();
	}
}



ClothingRenderProxyImpl* ClothingScene::getRenderProxy(RenderMeshAssetIntl* rma, bool useFallbackSkinning, bool useCustomVertexBuffer, const HashMap<uint32_t, ApexSimpleString>& overrideMaterials, const PxVec3* morphTargetNewPositions, const uint32_t* morphTargetVertexOffsets)
{
	if (rma == NULL)
	{
		return NULL;
	}

	ClothingRenderProxyImpl* renderProxy = NULL;


	mRenderProxiesLock.lock();
	Array<ClothingRenderProxyImpl*>& renderProxies = mRenderProxies[rma];
	for (uint32_t i = 0; i < renderProxies.size(); ++i)
	{
		ClothingRenderProxyImpl* proxyInPool = renderProxies[i];
		if (
			proxyInPool->getTimeInPool() > 0 && // proxy is available
			useFallbackSkinning == proxyInPool->usesFallbackSkinning() &&
			useCustomVertexBuffer == proxyInPool->usesCustomVertexBuffer() &&
			morphTargetNewPositions == proxyInPool->getMorphTargetBuffer() &&
			proxyInPool->overrideMaterialsEqual(overrideMaterials)
			)
		{
			renderProxy = proxyInPool;
			break;
		}
	}

	// no corresponding proxy in pool, so create one
	if (renderProxy == NULL)
	{
		renderProxy = PX_NEW(ClothingRenderProxyImpl)(rma, useFallbackSkinning, useCustomVertexBuffer, overrideMaterials, morphTargetNewPositions, morphTargetVertexOffsets, this);
		renderProxies.pushBack(renderProxy);
	}

	renderProxy->setTimeInPool(0);
	mRenderProxiesLock.unlock();

	return renderProxy;
}



void ClothingScene::tickRenderProxies()
{
	PX_PROFILE_ZONE("ClothingScene::tickRenderProxies", GetInternalApexSDK()->getContextId());
	mRenderProxiesLock.lock();

	for(HashMap<RenderMeshAssetIntl*, Array<ClothingRenderProxyImpl*> >::Iterator iter = mRenderProxies.getIterator(); !iter.done(); ++iter)
	{
		Array<ClothingRenderProxyImpl*>& renderProxies = iter->second;

		for (int32_t i = (int32_t)renderProxies.size()-1; i >= 0 ; --i)
		{
			uint32_t timeInPool = renderProxies[(uint32_t)i]->getTimeInPool();

			if (timeInPool > 0)
			{
				if (timeInPool > mModule->getMaxTimeRenderProxyInPool() + 1) // +1 because we add them with time 1
				{
					PX_DELETE(renderProxies[(uint32_t)i]);
					renderProxies.replaceWithLast((uint32_t)i);
				}
				else
				{
					renderProxies[(uint32_t)i]->setTimeInPool(timeInPool+1);
				}
			}
		}
	}

	mRenderProxiesLock.unlock();
}

}
} // namespace nvidia

Commits for Divide-Dependencies/physx/APEX_1.4/module/clothing/src/ClothingScene.cpp

Diff revisions: vs.
Revision Author Commited Message
105 IonutCava picture IonutCava Tue 16 Apr, 2019 19:55:41 +0000

Forgot to actually add physx