-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathrenderOverride.cpp
More file actions
3168 lines (2743 loc) · 132 KB
/
Copy pathrenderOverride.cpp
File metadata and controls
3168 lines (2743 loc) · 132 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
//
// Copyright 2019 Luma Pictures
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright 2024 Autodesk, Inc. All rights reserved.
//
// GL loading library needs to be included before any other OpenGL headers.
#include <pxr/imaging/garch/glApi.h>
#include "renderOverride.h"
#include "renderRegionCommand.h"
#include "setVisibleFramePassesCommand.h"
#include "mayaColorPreferencesTranslator.h"
#include "pluginDebugCodes.h"
#include "renderOverrideUtils.h"
#include "renderSettingsUtils.h"
#include <mayaHydraLib/mayaHydraLibInterface.h>
#include <mayaHydraLib/sceneIndex/registration.h>
#include <mayaHydraLib/sceneIndex/mhGenerativeProceduralResolvingSceneIndex.h>
#include <mayaHydraLib/pick/mhPickHit.h>
#include <mayaHydraLib/pick/mhPickHandler.h>
#include <mayaHydraLib/pick/mhPickHandlerRegistry.h>
#include <mayaHydraLib/profilingUtils.h>
#include <mayaHydraLib/hydraUtils.h>
#include <mayaHydraLib/mixedUtils.h>
#include <mayaHydraLib/tokens.h>
#include <flowViewport/tokens.h>
#include <flowViewport/colorPreferences/fvpColorPreferences.h>
#include <flowViewport/colorPreferences/fvpColorPreferencesTokens.h>
#include <flowViewport/debugCodes.h>
#include <flowViewport/selection/fvpSelection.h>
#include <flowViewport/API/renderViewData/fvpFilteringSceneIndicesChainManager.h>
#ifdef MAYA_HAS_VIEW_SELECTED_OBJECT_API
#include <flowViewport/API/renderViewData/fvpIsolateSelectManager.h>
#include <flowViewport/sceneIndex/fvpIsolateSelectSceneIndex.h>
#include <flowViewport/fvpInstruments.h>
#endif
#include <flowViewport/API/renderViewData/fvpRenderViewDataManager.h>
#include <flowViewport/API/interfacesImp/fvpDataProducerSceneIndexInterfaceImp.h>
#include <flowViewport/API/interfacesImp/fvpFilteringSceneIndexInterfaceImp.h>
#include <flowViewport/sceneIndex/fvpBBoxSceneIndex.h>
#include <flowViewport/sceneIndex/fvpReprSelectorSceneIndex.h>
#include <flowViewport/sceneIndex/fvpPassFilteringSceneIndex.h>
#include <flowViewport/selection/fvpPathMapperRegistry.h>
#include <flowViewport/imageWriter/fvpImageBufferWriter.h>
#include <flowViewport/fvpPurposeRenderTagsForPasses.h>
#include <hvt/engine/framePass.h>
#include <hvt/engine/framePassUtils.h>
#include <hvt/engine/renderIndexProxy.h>
#include <hvt/engine/taskCreationHelpers.h>
#include <hvt/engine/viewportEngine.h>
#include <hvt/tasks/resources.h>
#include <pxr/base/plug/plugin.h>
#include <pxr/base/plug/registry.h>
#include <pxr/base/tf/type.h>
#include <pxr/base/gf/vec3f.h>
#include <pxr/base/tf/staticTokens.h>
#include <pxr/base/tf/token.h>
#include <ufe/camera.h>
#include <ufe/hierarchy.h>
#include <ufe/selection.h>
#include <ufe/namedSelection.h>
#include <ufe/path.h>
#include <ufe/pathString.h>
#include <ufe/observableSelection.h>
#include <ufe/globalSelection.h>
#include <ufe/selectionNotification.h>
#include <ufe/observer.h>
#include <ufeExtensions/Global.h>
#include <pxr/base/gf/matrix4d.h>
#include <pxr/base/tf/instantiateSingleton.h>
#include <pxr/base/vt/value.h>
#include <pxr/imaging/glf/contextCaps.h>
#include <pxr/imaging/hd/camera.h>
#include <pxr/imaging/hd/rendererPluginRegistry.h>
#include <pxr/imaging/hd/rprim.h>
#include <pxr/imaging/hd/sceneIndexPluginRegistry.h>
#include <pxr/imaging/hd/dataSource.h>
#include <pxr/imaging/hd/sceneIndexPrimView.h>
#include <pxr/imaging/hd/mesh.h>
#include <pxr/imaging/hd/basisCurves.h>
#include <pxr/imaging/hd/points.h>
#include <pxr/imaging/hdx/pickTask.h>
#include <pxr/imaging/hdx/renderTask.h>
#include <pxr/imaging/hdx/tokens.h>
#include <pxr/imaging/hgi/hgi.h>
#include <pxr/imaging/hgi/tokens.h>
#include <pxr/imaging/hd/purposeSchema.h>
#include <pxr/imaging/hd/meshSchema.h>
#include <pxr/imaging/hd/basisCurvesSchema.h>
#include <pxr/usd/kind/registry.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/modelAPI.h>
#include <pxr/usd/usdGeom/imageable.h>
#include <pxr/usd/usdLux/lightAPI.h>
#include <pxr/usdImaging/usdImagingGL/engine.h>
#include <mayaUsdAPI/proxyStage.h>
#include <maya/MDagPath.h>
#include <maya/M3dView.h>
#include <maya/MConditionMessage.h>
#include <maya/MDGMessage.h>
#include <maya/MDrawContext.h>
#include <maya/MFrameContext.h>
#include <maya/MEventMessage.h>
#include <maya/MGlobal.h>
#include <maya/MNodeMessage.h>
#include <maya/MAnimControl.h>
#include <maya/MObjectHandle.h>
#include <maya/MSceneMessage.h>
#include <maya/MSelectionList.h>
#include <maya/MTimerMessage.h>
#include <maya/MUiMessage.h>
#include <maya/MFnCamera.h>
#include <maya/MFileIO.h>
#include <maya/MTypes.h>
#include <atomic>
#include <chrono>
#include <cstring>
#include <exception>
#include <limits>
#include <pxr/base/tf/getenv.h>
#include <pxr/base/tf/envSetting.h>
#include <pxr/base/tf/hashset.h>
#include "envSettings.h"
using namespace MayaHydra;
namespace {
PXR_NAMESPACE_USING_DIRECTIVE
const SdfPath MAYA_NATIVE_ROOT = SdfPath("/MayaHydraViewportRenderer");
inline bool isInComponentsPickingMode(const MHWRender::MSelectionInfo& selectInfo)
{
return selectInfo.selectable(MSelectionMask::kSelectMeshVerts)
|| selectInfo.selectable(MSelectionMask::kSelectMeshEdges)
|| selectInfo.selectable(MSelectionMask::kSelectMeshFreeEdges)
|| selectInfo.selectable(MSelectionMask::kSelectMeshFaces)
|| selectInfo.selectable(MSelectionMask::kSelectVertices)
|| selectInfo.selectable(MSelectionMask::kSelectEdges)
|| selectInfo.selectable(MSelectionMask::kSelectFacets);
}
#ifdef MAYA_HAS_VIEW_SELECTED_OBJECT_API
std::string getRenderingDestination(
const MHWRender::MFrameContext* frameContext
)
{
TF_AXIOM(frameContext);
MString viewportId;
frameContext->renderingDestination(viewportId);
return std::string(viewportId.asChar());
}
#endif
inline Fvp::LightsManagementSceneIndex::LightingMode convertFromMayaLightingModeToFlowViewportLightMode(MFrameContext::LightingMode mayaLightingMode)
{
switch (mayaLightingMode) {
case MFrameContext::kLightDefault: return Fvp::LightsManagementSceneIndex::LightingMode::kDefaultLighting;
case MFrameContext::kAmbientLight:
TF_WARN("Ambient/Flat lighting mode is not supported");//Fall into next switch/case as we want to return kSceneLighting
case MFrameContext::kSceneLights: return Fvp::LightsManagementSceneIndex::LightingMode::kSceneLighting;
case MFrameContext::kSelectedLights:
return Fvp::LightsManagementSceneIndex::LightingMode::kSelectedLightsOnly;
case MFrameContext::kNoLighting: return Fvp::LightsManagementSceneIndex::LightingMode::kNoLighting;
default: return Fvp::LightsManagementSceneIndex::LightingMode::kSceneLighting;
}
}
}
PXR_NAMESPACE_OPEN_SCOPE
// Bring the MayaHydra namespace into scope.
// The following code currently lives inside the pxr namespace, but it would make more sense to
// have it inside the MayaHydra namespace. This using statement allows us to use MayaHydra symbols
// from within the pxr namespace as if we were in the MayaHydra namespace.
// Remove this once the code has been moved to the MayaHydra namespace.
using namespace MayaHydra;
namespace {
// Not sure if we actually need a mutex guarding _allInstances, but
// everywhere that uses it isn't a "frequent" operation, so the
// extra speed loss should be fine, and I'd rather be safe.
std::mutex _allInstancesMutex;
std::vector<MtohRenderOverride*> _allInstances;
//! \brief Get the index of the hit nearest to a given cursor point.
int GetNearestHitIndex(
const MHWRender::MFrameContext& frameContext,
const PickHitVector& hits,
int cursor_x,
int cursor_y)
{
int nearestHitIndex = -1;
double dist2_min = std::numeric_limits<double>::max();
float depth_min = std::numeric_limits<float>::max();
for (unsigned int i = 0; i < hits.size(); i++) {
const PickHit& hit = hits[i];
const MPoint worldSpaceHitPoint(
hit.hdxPickHit.worldSpaceHitPoint[0], hit.hdxPickHit.worldSpaceHitPoint[1], hit.hdxPickHit.worldSpaceHitPoint[2]);
// Calculate the (x, y) coordinate relative to the lower left corner of the viewport.
double hit_x, hit_y;
frameContext.worldToViewport(worldSpaceHitPoint, hit_x, hit_y);
// Calculate the 2D distance between the hit and the cursor
double dist_x = hit_x - (double)cursor_x;
double dist_y = hit_y - (double)cursor_y;
double dist2 = dist_x * dist_x + dist_y * dist_y;
// Find the hit nearest to the cursor.
if ((dist2 < dist2_min) || (dist2 == dist2_min && hit.hdxPickHit.normalizedDepth < depth_min)) {
dist2_min = dist2;
depth_min = hit.hdxPickHit.normalizedDepth;
nearestHitIndex = (int)i;
}
}
return nearestHitIndex;
}
} // namespace
class MtohRenderOverride::SelectionObserver : public Ufe::Observer
{
public:
SelectionObserver(MtohRenderOverride& renderOverride)
: Ufe::Observer(), _renderOverride(renderOverride)
{}
void operator()(const Ufe::Notification& notification) override
{
// During Maya file read, each node will be selected in turn, so we get
// notified for each node in the scene. Prune this out.
if (MFileIO::isOpeningFile()) {
return;
}
_renderOverride.SelectionChanged(
dynamic_cast<const Ufe::SelectionChanged&>(notification));
}
private:
MtohRenderOverride& _renderOverride;
};
// MtohRenderOverride is a rendering override class for the viewport to use Hydra instead of VP2.0.
MtohRenderOverride::MtohRenderOverride(const MtohRendererDescription& desc)
: MHWRender::MRenderOverride(desc.overrideName.GetText())
, _rendererDesc(desc)
, _sceneIndexRegistry(nullptr)
, _globals(MtohRenderGlobals::GetInstance())
, _hgi(Hgi::CreatePlatformDefaultHgi())
, _hgiDriver { HgiTokens->renderDriver, VtValue(_hgi.get()) }
, _fvpSelectionTracker(new Fvp::SelectionTracker)
, _ufeSn(Ufe::NamedSelection::get("MayaSelectTool"))
, _mayaSelectionObserver(std::make_shared<SelectionObserver>(*this))
, _isUsingHdSt(desc.rendererName == MtohTokens->HdStormRendererPlugin)
{
TF_DEBUG(MAYAHYDRALIB_RENDEROVERRIDE_RESOURCES)
.Msg(
"MtohRenderOverride created (%s - %s - %s)\n",
_rendererDesc.rendererName.GetText(),
_rendererDesc.overrideName.GetText(),
_rendererDesc.displayName.GetText());
_ID = MAYA_NATIVE_ROOT.AppendChild(
TfToken(TfStringPrintf("_MayaHydra_%s_%p", desc.rendererName.GetText(), this)));
MStatus status;
auto id
= MSceneMessage::addCallback(MSceneMessage::kBeforeNew, _ClearHydraCallback, this, &status);
if (status) {
_callbacks.append(id);
}
id = MSceneMessage::addCallback(MSceneMessage::kBeforeOpen, _ClearHydraCallback, this, &status);
if (status) {
_callbacks.append(id);
}
// Observe the UFE selection.
auto sn = Ufe::GlobalSelection::get();
TF_AXIOM(sn);
sn->addObserver(_mayaSelectionObserver);
// Setup the playblast watch.
// _playBlasting is forced to true here so we can just use _PlayblastingChanged below
//
_playBlasting = true;
MConditionMessage::addConditionCallback(
"playblasting", &MtohRenderOverride::_PlayblastingChanged, this, &status);
MtohRenderOverride::_PlayblastingChanged(false, this);
_defaultLight.SetSpecular(GfVec4f(0.0f));
_defaultLight.SetAmbient(GfVec4f(0.0f));
{
std::lock_guard<std::mutex> lock(_allInstancesMutex);
_allInstances.push_back(this);
}
#ifdef MAYA_HAS_VIEW_SELECTED_OBJECT_API
Fvp::Instruments::instance().set(kNbViewSelectedChangedCalls, VtValue(_nbViewSelectedChangedCalls));
#endif
// Tell the Viewport Toolbox where to find its resources.
std::filesystem::path pluginPath = MtohGetMayaHydraPluginLocation();
// Go up 2 folders from plugin path and add /include/hvt/resources
if (!pluginPath.empty()) {
const std::filesystem::path resourcePath = pluginPath.parent_path().parent_path() / "include" / "hvt" / "resources";
// Check if the resource path exists and warn if it doesn't
if (!std::filesystem::exists(resourcePath)) {
TF_WARN(
"MayaHydra: Viewport Toolbox resource directory does not exist: %s",
resourcePath.string().c_str());
} else {
hvt::SetResourceDirectory(resourcePath);
}
}
}
MtohRenderOverride::~MtohRenderOverride()
{
TF_DEBUG(MAYAHYDRALIB_RENDEROVERRIDE_RESOURCES)
.Msg(
"MtohRenderOverride destroyed (%s - %s - %s)\n",
_rendererDesc.rendererName.GetText(),
_rendererDesc.overrideName.GetText(),
_rendererDesc.displayName.GetText());
if (_mayaSelectionObserver) {
if (auto sn = Ufe::GlobalSelection::get()) {
sn->removeObserver(_mayaSelectionObserver);
}
}
if (_timerCallback) {
MMessage::removeCallback(_timerCallback);
}
if (_timeChangeCallback) {
MMessage::removeCallback(_timeChangeCallback);
_timeChangeCallback = 0;
}
#ifdef MAYA_HAS_VIEW_SELECTED_OBJECT_API
if (_viewSelectedChangedCb) {
MMessage::removeCallback(_viewSelectedChangedCb);
}
#endif
constexpr bool fullReset = true;
ClearHydraResources(fullReset);
_operations.clear();
MMessage::removeCallbacks(_callbacks);
_callbacks.clear();
for (auto& panelAndCallbacks : _renderPanelCallbacks) {
MMessage::removeCallbacks(panelAndCallbacks.second);
}
if (!_allInstances.empty()) {
std::lock_guard<std::mutex> lock(_allInstancesMutex);
_allInstances.erase(
std::remove(_allInstances.begin(), _allInstances.end(), this), _allInstances.end());
}
}
HdRenderDelegate* MtohRenderOverride::_GetRenderDelegate(int framePassIndex /*= 0*/)
{
if (framePassIndex < 0 || framePassIndex >= static_cast<int> (_framePassesData.size())) {
TF_CODING_ERROR("Invalid pass index: %d", framePassIndex);
return nullptr;
}
const auto& renderIndexProxy = (_framePassesData[framePassIndex] && _framePassesData[framePassIndex]->HasRenderIndexProxy())
? _framePassesData[framePassIndex]->GetRenderIndexProxy()
: nullptr;
return renderIndexProxy ? renderIndexProxy->RenderIndex()->GetRenderDelegate() : nullptr;
}
HdRenderDelegate* MtohRenderOverride::_GetRenderDelegate(int framePassIndex /*= 0*/) const
{
if (framePassIndex < 0 || framePassIndex >= static_cast<int> (_framePassesData.size())) {
TF_CODING_ERROR("Invalid pass index: %d", framePassIndex);
return nullptr;
}
const auto& renderIndexProxy = (_framePassesData[framePassIndex] && _framePassesData[framePassIndex]->HasRenderIndexProxy())
? _framePassesData[framePassIndex]->GetRenderIndexProxy()
: nullptr;
return renderIndexProxy ? renderIndexProxy->RenderIndex()->GetRenderDelegate()
: nullptr;
}
void MtohRenderOverride::UpdateRenderGlobals(
const MtohRenderGlobals& globals,
const TfToken& attrName)
{
// If no attribute or attribute starts with 'mayaHydra', these setting wil be applied on the
// next call to MtohRenderOverride::Render, so just force an invalidation
// XXX: This will need to change if mayaHydra settings should ever make it to the delegate
// itself.
// If the attribute name does not start with mayaHydra, or mayaHydra is
// not found.
if (attrName.GetString().find("mayaHydra") != 0) {
std::lock_guard<std::mutex> lock(_allInstancesMutex);
for (auto* instance : _allInstances) {
const auto& rendererName = instance->_rendererDesc.rendererName;
// If no attrName or the attrName is the renderer, then update everything
const size_t attrFilter = (attrName.IsEmpty() || attrName == rendererName) ? 0 : 1;
if (attrFilter && !instance->_globals.AffectsRenderer(attrName, rendererName)) {
continue;
}
// Will be applied in _InitHydraResources later anyway
if (auto* renderDelegate = instance->_GetRenderDelegate()) {
instance->_globals.ApplySettings(
renderDelegate,
instance->_rendererDesc.rendererName,
TfTokenVector(attrFilter, attrName));
if (attrFilter) {
break;
}
}
}
}
else {
if (attrName.GetString().find("Purpose") != 0) {
//One of the render purpose attributes just changed
//Get purpose render tag from attribute name
const PXR_NS::TfToken purposeRenderTag
= RenderGlobalsUtils::GetPurposeRenderTagFromAttrName(attrName);
if (!purposeRenderTag.IsEmpty()) {
std::lock_guard<std::mutex> lock(_allInstancesMutex);
for (auto* instance : _allInstances) {
Fvp::FramePassDataPtrVector& framePassDataArray
= instance->_framePassesData;
for (auto& framePassData : framePassDataArray) {
if (framePassData && framePassData->IsValid()) {
auto params = instance->_globals.delegateParams;
framePassData->_renderTagsUpdateFn(params.renderPurpose, params.proxyPurpose, params.guidePurpose);
framePassData->DirtyPrimsFromPurposeRenderTag(purposeRenderTag);
}
}
}
}
}
}
// Less than ideal still
MGlobal::executeCommandOnIdle("refresh -f");
}
VtValue MtohRenderOverride::_GetUsedGPUMemory() const
{
// Currently, only Storm is the known/tested renderer that provides GPU stats
// via the Render Delegate.
HdRenderDelegate* renderDelegate = _GetRenderDelegate();
if (_isUsingHdSt && renderDelegate)
{
VtDictionary hdStRenderStat = renderDelegate->GetRenderStats();
return hdStRenderStat[HdPerfTokens->gpuMemoryUsed.GetString()];
}
return VtValue();
}
int MtohRenderOverride::GetUsedGPUMemory()
{
int totalGPUMemory = 0;
std::lock_guard<std::mutex> lock(_allInstancesMutex);
for (auto* instance : _allInstances) {
totalGPUMemory += instance->_GetUsedGPUMemory().UncheckedGet<int>();
}
return totalGPUMemory / (1024*1024);
}
std::map<std::string, int> MtohRenderOverride::GetSceneStatistics()
{
std::map<std::string, int> stats = {
{"primitives", 0},
{"mesh", 0},
{"mesh.points", 0},
{"mesh.faces", 0},
{"curve", 0},
{"curve.points", 0},
{"point", 0},
};
MtohRenderOverride* instance = nullptr;
{
std::lock_guard<std::mutex> lock(_allInstancesMutex);
for (auto* inst : _allInstances) {
if (inst->_initializationSucceeded && inst->renderIndex()) {
instance = inst;
break;
}
}
}
if (!instance || !instance->renderIndex()) {
return stats;
}
// Get stats for all passes, avoiding double-counting when passes share the same render index
const int numFramePasses = instance->_GetNumFramePasses();
// Track which prims we've already counted to avoid double-counting
std::set<SdfPath> seenPrims;
// We are going to get the prims from all passes, but avoid double counting
// the geometry (topology/verts) is defined in only one of the passes
for (int i = 0; i < numFramePasses; ++i) {
auto* renderIndex = instance->renderIndex(i);
if (!renderIndex) {
continue;
}
auto primIds = renderIndex->GetRprimIds();
for (const auto& primId : primIds) {
auto* rprim = renderIndex->GetRprim(primId);
if (!rprim) {
continue;
}
// Check if we've already counted this prim
bool isNewPrim = (seenPrims.find(primId) == seenPrims.end());
if (isNewPrim) {
seenPrims.insert(primId);
stats["primitives"]++;
}
auto* mesh = dynamic_cast<const HdMesh*>(rprim);
if (mesh) {
if (isNewPrim) {
stats["mesh"]++;
}
auto sceneIndexPrim = renderIndex->GetTerminalSceneIndex()->GetPrim(primId);
auto meshSchema = HdMeshSchema::GetFromParent(sceneIndexPrim.dataSource);
if (meshSchema.IsDefined()) {
auto meshTopology = meshSchema.GetTopology();
if (meshTopology.IsDefined()) {
auto faceVertexCounts = meshTopology.GetFaceVertexCounts();
auto faceVertexIndices = meshTopology.GetFaceVertexIndices();
if (faceVertexCounts && faceVertexIndices) {
auto counts = faceVertexCounts->GetTypedValue(0.0f);
auto indices = faceVertexIndices->GetTypedValue(0.0f);
stats["mesh.faces"] += counts.size();
if (!indices.empty()) {
int maxIndex = *std::max_element(indices.begin(), indices.end());
stats["mesh.points"] += maxIndex + 1;
}
}
}
}
continue;
}
auto* curves = dynamic_cast<const HdBasisCurves*>(rprim);
if (curves) {
if (isNewPrim) {
stats["curve"]++;
}
auto sceneIndexPrim = renderIndex->GetTerminalSceneIndex()->GetPrim(primId);
auto curvesSchema = HdBasisCurvesSchema::GetFromParent(sceneIndexPrim.dataSource);
if (curvesSchema.IsDefined()) {
auto curvesTopology = curvesSchema.GetTopology();
if (curvesTopology.IsDefined()) {
auto curveIndices = curvesTopology.GetCurveIndices();
if (curveIndices) {
auto indices = curveIndices->GetTypedValue(0.0f);
if (!indices.empty()) {
int maxIndex = *std::max_element(indices.begin(), indices.end());
stats["curve.points"] += maxIndex + 1;
}
}
}
}
continue;
}
auto* points = dynamic_cast<const HdPoints*>(rprim);
if (points) {
if (isNewPrim) {
stats["point"]++;
}
continue;
}
}
}
return stats;
}
std::vector<MString> MtohRenderOverride::AllActiveRendererNames()
{
std::vector<MString> renderers;
std::lock_guard<std::mutex> lock(_allInstancesMutex);
for (auto* instance : _allInstances) {
if (instance->_initializationSucceeded) {
renderers.push_back(instance->_rendererDesc.rendererName.GetText());
}
}
return renderers;
}
TfTokenVector MtohRenderOverride::GetAvailableFramePassAovs(int passIndex)
{
TfTokenVector aovs;
std::lock_guard<std::mutex> lock(_allInstancesMutex);
for (auto* instance : _allInstances) {
if (instance->_initializationSucceeded
&& passIndex < static_cast<int>(instance->_framePassesData.size())) {
// Can't rely on UsdImagingGLEngine::GetRenderAovs() as creating a temp UsdImagingGLEngine with same hgi
// may interfere with the current renderer, just copy the same implementation here
TfTokenVector currAovs;
const auto renderIndex = instance->renderIndex(passIndex);
if (renderIndex && renderIndex->IsBprimTypeSupported(HdPrimTypeTokens->renderBuffer)) {
static const TfToken candidates[] = { HdAovTokens->primId,
HdAovTokens->depth,
HdAovTokens->normal,
#if PXR_VERSION > 2411
HdAovTokens->Neye,
#endif
HdAovTokensMakePrimvar(TfToken("st")) };
currAovs = { HdAovTokens->color };
for (auto const& aov : candidates) {
if (renderIndex->GetRenderDelegate()->GetDefaultAovDescriptor(aov).format
!= HdFormatInvalid) {
currAovs.push_back(aov);
}
}
}
aovs.insert(aovs.end(), currAovs.begin(), currAovs.end());
}
}
return aovs;
}
SdfPathVector MtohRenderOverride::RendererRprims(TfToken rendererName, bool visibleOnly)
{
MtohRenderOverride* instance = GetByName(rendererName);
if (!instance) {
return SdfPathVector();
}
// We need to find the right render index from a framePassData and get its RPrims.
SdfPathVector primIds;
const int numFramePassesData = static_cast<int>(instance->_framePassesData.size());
for (int i = 0; i < numFramePassesData; ++i) {
const auto& framePassData = instance->_framePassesData[i];
if (!framePassData) {
continue;
}
const std::string& rendererNameFromPass = framePassData->_rendererName.GetString();
if (rendererName != rendererNameFromPass){
continue;
}
auto* renderIndex = (framePassData->_renderIndexProxy)
? framePassData->_renderIndexProxy->RenderIndex()
: nullptr;
if (!renderIndex) {
continue;
}
//Do a copy as we may remove some of them
SdfPathVector tempPrimIds = renderIndex->GetRprimIds();
if (visibleOnly) {
tempPrimIds.erase(
std::remove_if(
tempPrimIds.begin(),
tempPrimIds.end(),
[renderIndex](const SdfPath& primId) {
auto* rprim = renderIndex->GetRprim(primId);
if (!rprim)
return true;
return !rprim->IsVisible();
}),
tempPrimIds.end());
}
// Concatenate results
if (tempPrimIds.size()) {
primIds.reserve(
primIds.size() + tempPrimIds.size()); // Reserve space to avoid reallocations
primIds.insert(
primIds.end(), tempPrimIds.begin(), tempPrimIds.end()); // Insert all elements
}
}
// Sort them by lexicographically order
std::sort(primIds.begin(), primIds.end(), std::less<SdfPath>());
return primIds;
}
SdfPath MtohRenderOverride::RendererSceneDelegateId(TfToken rendererName, TfToken sceneDelegateName)
{
MtohRenderOverride* instance = GetByName(rendererName);
if (!instance) {
return SdfPath();
}
if (instance->_mayaHydraSceneIndex) {
return instance->_mayaHydraSceneIndex->GetDelegateID(sceneDelegateName);
}
return SdfPath();
}
bool MtohRenderOverride::HasConverged(TfToken rendererName)
{
MtohRenderOverride* instance = GetByName(rendererName);
if (!instance) {
return false;
}
return instance->_isConverged;
}
void MtohRenderOverride::_DetectMayaDefaultLighting(const MHWRender::MDrawContext& drawContext)
{
constexpr auto considerAllSceneLights = MHWRender::MDrawContext::kFilteredIgnoreLightLimit;
const auto numLights = drawContext.numberOfActiveLights(considerAllSceneLights);
auto foundMayaDefaultLight = false;
if (numLights == 1) {
auto* lightParam = drawContext.getLightParameterInformation(0, considerAllSceneLights);
if (lightParam != nullptr && !lightParam->lightPath().isValid()) {
// This light does not exist so it must be the
// default maya light
MFloatPointArray positions;
MFloatVector direction;
auto intensity = 0.0f;
MColor color;
auto hasDirection = false;
auto hasPosition = false;
// Maya default light has no position, only direction
drawContext.getLightInformation(
0,
positions,
direction,
intensity,
color,
hasDirection,
hasPosition,
considerAllSceneLights);
if (hasDirection && !hasPosition) {
#if defined(HD_API_VERSION) && HD_API_VERSION >= 74 // For USD 24.11+
intensity /= M_PI;//Is a HdPrimTypeTokens->simpleLight
#endif
// Note for devs : if you update more parameters in the default light, don't forget
// to update MtohDefaultLightDelegate::SetDefaultLight and MayaViewportSceneIndex::SetDefaultLight, currently there are only 3 :
// position, diffuse, specular
GfVec3f position;
GetDirectionalLightPositionFromDirectionVector(position, {direction.x, direction.y, direction.z});
_defaultLight.SetPosition({ position.data()[0], position.data()[1], position.data()[2], 0.0f });
_defaultLight.SetDiffuse(
{ intensity * color.r, intensity * color.g, intensity * color.b, 1.0f });
_defaultLight.SetSpecular(
{ intensity * color.r, intensity * color.g, intensity * color.b, 1.0f });
foundMayaDefaultLight = true;
}
}
}
TF_DEBUG(MAYAHYDRALIB_RENDEROVERRIDE_DEFAULT_LIGHTING)
.Msg(
"MtohRenderOverride::"
"_DetectMayaDefaultLighting() "
"foundMayaDefaultLight=%i\n",
foundMayaDefaultLight);
if (foundMayaDefaultLight != _hasDefaultLighting) {
_hasDefaultLighting = foundMayaDefaultLight;
TF_DEBUG(MAYAHYDRALIB_RENDEROVERRIDE_DEFAULT_LIGHTING)
.Msg(
"MtohRenderOverride::"
"_DetectMayaDefaultLighting() clearing! "
"_hasDefaultLighting=%i\n",
_hasDefaultLighting);
}
}
MStatus MtohRenderOverride::Render(
const MHWRender::MDrawContext& drawContext,
const MHWRender::MDataServerOperation::MViewportScene& scene)
{
// It would be good to clear the resources of the overrides that are
// not in active use, but I'm not sure if we have a better way than
// the idle time we use currently. The approach below would break if
// two render overrides were used at the same time.
// for (auto* override: _allInstances) {
// if (override != this) {
// override->ClearHydraResources();
// }
// }
MH_PROFILE_FUNCTION();
TF_DEBUG(MAYAHYDRALIB_RENDEROVERRIDE_RENDER).Msg("MtohRenderOverride::Render()\n");
// We can use the mayaHydraSetVisibleFramePasses command to set the visible passes
auto renderFrame = [&](bool markTime = false) {
MH_PROFILE_SCOPE("MtohRenderOverride::Render renderFrame lambda");
if (scene.changed()) {
if (_mayaHydraSceneIndex) {
_mayaHydraSceneIndex->UpdateRenderItems(scene);
}
}
if (_mayaViewportSceneIndex) {
_mayaViewportSceneIndex->Update(drawContext);
}
// Update shadow collection for lights
if (_mayaHydraSceneIndex) {
_mayaHydraSceneIndex->UpdateLightsShadowCollection();
}
// Update plugin data producers
for (auto& viewportData : Fvp::RenderViewDataManager::Get().GetAllViewData()) {
for (auto& dataProducer : viewportData.GetDataProducerSceneIndicesData()) {
dataProducer->UpdateVisibility();
dataProducer->UpdateTransform();
}
}
//Apply any pending update from MayaUsd proxy shape nodes
_sceneIndexRegistry->ApplyPendingUpdates();
// Update plugin filtering scene indices
std::string rendererNamesToUpdate;
for (auto& sceneFilteringSceneIndexData :
Fvp::FilteringSceneIndexInterfaceImp::get().getSceneFilteringSceneIndicesData()) {
if (sceneFilteringSceneIndexData->UpdateVisibility()) {
rendererNamesToUpdate
+= sceneFilteringSceneIndexData->GetClient()->getRendererNames();
}
}
for (auto& selectionHighlightFilteringSceneIndexData :
Fvp::FilteringSceneIndexInterfaceImp::get()
.getSelectionHighlightFilteringSceneIndicesData()) {
if (selectionHighlightFilteringSceneIndexData->UpdateVisibility()) {
rendererNamesToUpdate
+= selectionHighlightFilteringSceneIndexData->GetClient()->getRendererNames();
}
}
if (!rendererNamesToUpdate.empty()) {
Fvp::FilteringSceneIndicesChainManager::get().updateFilteringSceneIndicesChain(
rendererNamesToUpdate);
}
const MIntArray& framePassesVisible =
MayaHydraSetVisibleFramePasses::getVisibleFramePasses();
int numVisibleFramePasses = framePassesVisible.length();
const MString visibleAOVName = MayaHydraSetVisibleFramePasses::getAovName();
const int numFramePasses = _GetNumFramePasses();
if (numVisibleFramePasses > numFramePasses) {
numVisibleFramePasses
= numFramePasses;
}
// Iterate over visible passes
for (int visibleIdx = 0; visibleIdx < numVisibleFramePasses; ++visibleIdx) {
MH_PROFILE_SCOPE("MayaHydra frame pass");
const int actualPassIndex = framePassesVisible[visibleIdx]; // Get the actual pass index
const hvt::FramePassPtr& currentPass = _GetFramePass(actualPassIndex);
if (!currentPass) {
continue;
}
const bool isPass0 = (actualPassIndex == 0);
const bool isFirstVisiblePass = (visibleIdx == 0);
const bool isLastVisiblePass = (visibleIdx == numVisibleFramePasses - 1);//Put me back later
// Clear background for the first visible pass only
currentPass->params().clearBackgroundColor = isFirstVisiblePass;
currentPass->params().clearBackgroundDepth = isFirstVisiblePass;
// Enable presentation for the last visible pass only
currentPass->params().enablePresentation = isLastVisiblePass;
// Set the AOV to visualize
// Per HVT, the AOV to visualize must be set on the last visible pass, and HdAovTokens->color must be set on other passes
TfToken visualizeAOV = HdAovTokens->color;
if (isLastVisiblePass) {
const TfToken aovName = TfToken(visibleAOVName.asChar());
// Can't rely on GetRenderBuffer(aovName) here as the AOV may not have been created yet
const auto renderDelegate = _GetRenderDelegate(actualPassIndex);
const bool aovNameExists = renderDelegate
? renderDelegate->GetDefaultAovDescriptor(aovName).format != HdFormatInvalid
: false;
visualizeAOV = (aovNameExists) ? aovName : HdAovTokens->color;
}
currentPass->params().visualizeAOV = visualizeAOV;
if (visibleIdx > 0) {
currentPass->params().renderParams.depthBiasEnable = true;
currentPass->params().renderParams.depthBiasUseDefault = false;
currentPass->params().renderParams.depthBiasConstantFactor = -1.0f;
currentPass->params().renderParams.depthBiasSlopeFactor = -1.0f;
}
if (isPass0) {
// Do not share the AOVs, for the first pass only
HdTaskSharedPtrVector passTasks = currentPass->GetRenderTasks();
#if PXR_VERSION >= 2605
if (_sceneGlobalsSceneIndex) {
const SdfPath& cameraPath = currentPass->params().renderParams.camera;
if (!cameraPath.IsEmpty()) {
_sceneGlobalsSceneIndex->SetPrimaryCameraPrimPath(cameraPath);
}
}
#endif
/*Debug code left here if needed later
hvt::FramePass& framePassToDebug = *currentPass;
std::ostringstream content;
content << framePassToDebug;
std::string framePassParameters = content.str();
OutputDebugStringA("Main Frame Pass parameters:");
OutputDebugStringA(framePassParameters.c_str());
*/
currentPass->Render(passTasks);
} else {
// Share AOVs from the previous visible pass or pass0
const int previousPassIndex = (visibleIdx > 0) ?framePassesVisible[visibleIdx - 1] : 0;
hvt::FramePassPtr& previousPass = _GetFramePass(previousPassIndex);
if (previousPass) {
const hvt::RenderBufferBindings inputAOVs = previousPass->GetRenderBufferBindingsForNextPass(
{ PXR_NS::HdAovTokens->color, PXR_NS::HdAovTokens->depth }
);
HdTaskSharedPtrVector passTasks = currentPass->GetRenderTasks(inputAOVs);
#if PXR_VERSION >= 2605
if (_sceneGlobalsSceneIndex) {
const SdfPath& cameraPath = currentPass->params().renderParams.camera;
if (!cameraPath.IsEmpty()) {
_sceneGlobalsSceneIndex->SetPrimaryCameraPrimPath(cameraPath);
}
}
#endif
/*Debug code left here if needed later
hvt::FramePass& framePassToDebug = *currentPass;
std::ostringstream content;
content << framePassToDebug;
std::string framePassParameters = content.str();
OutputDebugStringA("Second Frame Pass parameters:");
OutputDebugStringA(framePassParameters.c_str());
*/
currentPass->Render(passTasks);
}
}
}
const auto fileName = Fvp::ImageBufferWriter::GetFileName();
if (!fileName.empty()) {