forked from Autodesk/maya-usd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxyRenderDelegate.cpp
More file actions
2363 lines (2059 loc) · 88.1 KB
/
Copy pathproxyRenderDelegate.cpp
File metadata and controls
2363 lines (2059 loc) · 88.1 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 2020 Autodesk
//
// 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.
//
#include "proxyRenderDelegate.h"
#include "drawItem.h"
#include "material.h"
#include "mayaPrimCommon.h"
#include "renderDelegate.h"
#include "tokens.h"
#include <mayaUsd/base/tokens.h>
#include <mayaUsd/nodes/proxyShapeBase.h>
#include <mayaUsd/nodes/stageData.h>
#include <mayaUsd/render/px_vp20/utils.h>
#include <mayaUsd/utils/diagnosticDelegate.h>
#include <mayaUsd/utils/selectability.h>
#include <usdUfe/ufe/Utils.h>
#include <pxr/base/tf/diagnostic.h>
#include <pxr/base/tf/staticTokens.h>
#include <pxr/base/tf/stringUtils.h>
#include <pxr/base/tf/token.h>
#include <pxr/imaging/hd/basisCurves.h>
#include <pxr/imaging/hd/changeTracker.h>
#include <pxr/imaging/hd/enums.h>
#include <pxr/imaging/hd/material.h>
#include <pxr/imaging/hd/mesh.h>
#include <pxr/imaging/hd/points.h>
#include <pxr/imaging/hd/primGather.h>
#include <pxr/imaging/hd/repr.h>
#include <pxr/imaging/hd/rprimCollection.h>
#include <pxr/imaging/hd/sceneDelegate.h>
#include <pxr/imaging/hdx/renderTask.h>
#include <pxr/imaging/hdx/selectionTracker.h>
#include <pxr/imaging/hdx/taskController.h>
#include <pxr/pxr.h>
#include <pxr/usd/kind/registry.h>
#include <pxr/usd/sdf/path.h>
#include <pxr/usd/usd/modelAPI.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usdGeom/gprim.h>
#include <pxr/usdImaging/usdImaging/delegate.h>
#include <maya/MColorPickerUtilities.h>
#ifdef MAYA_HAS_DISPLAY_LAYER_API
#include <maya/MDGMessage.h>
#include <maya/MDisplayLayerMessage.h>
#endif
#include <maya/M3dView.h>
#include <maya/MEventMessage.h>
#include <maya/MFileIO.h>
#include <maya/MFnPluginData.h>
#include <maya/MHWGeometryUtilities.h>
#include <maya/MProfiler.h>
#include <maya/MSelectionContext.h>
#ifdef MAYA_HAS_DISPLAY_LAYER_API
#include <maya/MFnDisplayLayer.h>
#include <maya/MFnDisplayLayerManager.h>
#include <maya/MNodeMessage.h>
#endif
#include <mayaUsd/ufe/Global.h>
#include <mayaUsd/ufe/Utils.h>
#include <usdUfe/ufe/UsdSceneItem.h>
#include <ufe/globalSelection.h>
#include <ufe/namedSelection.h>
#include <ufe/observableSelection.h>
#ifdef MAYA_HAS_DISPLAY_LAYER_API
#include <ufe/pathString.h>
#include <ufe/pathStringExcept.h>
#endif
#include <ufe/pathSegment.h>
#include <ufe/runTimeMgr.h>
#include <ufe/scene.h>
#include <ufe/sceneItem.h>
#include <ufe/sceneNotification.h>
#include <ufe/selectionNotification.h>
#if defined(BUILD_HDMAYA)
#include <mayaUsd/render/mayaToHydra/utils.h>
#endif
PXR_NAMESPACE_OPEN_SCOPE
namespace {
//! Representation selector for point snapping
const HdReprSelector kPointsReprSelector(TfToken(), TfToken(), HdReprTokens->points);
//! \brief Query the global selection list adjustment.
MGlobal::ListAdjustment GetListAdjustment()
{
// Keyboard modifiers can be queried from QApplication::keyboardModifiers()
// in case running MEL command leads to performance hit. On the other hand
// the advantage of using MEL command is the platform-agnostic state of the
// CONTROL key that it provides for aligning to Maya's implementation.
int modifiers = 0;
MGlobal::executeCommand("getModifiers", modifiers);
const bool shiftHeld = (modifiers % 2);
const bool ctrlHeld = (modifiers / 4 % 2);
MGlobal::ListAdjustment listAdjustment = MGlobal::kReplaceList;
if (shiftHeld && ctrlHeld) {
listAdjustment = MGlobal::kAddToList;
} else if (ctrlHeld) {
listAdjustment = MGlobal::kRemoveFromList;
} else if (shiftHeld) {
listAdjustment = MGlobal::kXORWithList;
}
return listAdjustment;
}
//! \brief Query the Kind to be selected from viewport.
//! \return A Kind token (https://graphics.pixar.com/usd/docs/api/kind_page_front.html). If the
//! token is empty or non-existing in the hierarchy, the exact prim that gets picked
//! in the viewport will be selected.
TfToken GetSelectionKind()
{
static const MString kOptionVarName(MayaUsdOptionVars->SelectionKind.GetText());
if (MGlobal::optionVarExists(kOptionVarName)) {
MString optionVarValue = MGlobal::optionVarStringValue(kOptionVarName);
return TfToken(optionVarValue.asChar());
}
return TfToken();
}
// clang-format off
TF_DEFINE_PRIVATE_TOKENS(
_pointInstancesPickModeTokens,
(PointInstancer)
(Instances)
(Prototypes)
);
// clang-format on
//! \brief Query the pick mode to use when picking point instances in the viewport.
//! \return A UsdPointInstancesPickMode enum value indicating the pick mode behavior
//! to employ when the picked object is a point instance.
//!
//! This function retrieves the value for the point instances pick mode optionVar
//! and converts it into a UsdPointInstancesPickMode enum value. If the optionVar
//! has not been set or otherwise has an invalid value, the default pick mode of
//! PointInstancer is returned.
UsdPointInstancesPickMode GetPointInstancesPickMode()
{
static const MString kOptionVarName(MayaUsdOptionVars->PointInstancesPickMode.GetText());
UsdPointInstancesPickMode pickMode = UsdPointInstancesPickMode::PointInstancer;
if (MGlobal::optionVarExists(kOptionVarName)) {
const MString optionVarValue = MGlobal::optionVarStringValue(kOptionVarName);
const TfToken pickModeToken(UsdMayaUtil::convert(optionVarValue));
if (pickModeToken == _pointInstancesPickModeTokens->Instances) {
pickMode = UsdPointInstancesPickMode::Instances;
} else if (pickModeToken == _pointInstancesPickModeTokens->Prototypes) {
pickMode = UsdPointInstancesPickMode::Prototypes;
}
}
return pickMode;
}
//! \brief Returns the prim or an ancestor of it that is of the given kind.
//
// If neither the prim itself nor any of its ancestors above it in the
// namespace hierarchy have an authored kind that matches, an invalid null
// prim is returned.
UsdPrim GetPrimOrAncestorWithKind(const UsdPrim& prim, const TfToken& kind)
{
UsdPrim iterPrim = prim;
TfToken primKind;
while (iterPrim) {
if (UsdModelAPI(iterPrim).GetKind(&primKind) && KindRegistry::IsA(primKind, kind)) {
break;
}
iterPrim = iterPrim.GetParent();
}
return iterPrim;
}
//! \brief Populate Rprims into the Hydra selection from the UFE scene item.
void PopulateSelection(
const Ufe::SceneItem::Ptr& item,
const Ufe::Path& proxyPath,
UsdImagingDelegate& sceneDelegate,
const HdSelectionSharedPtr& result)
{
// Filter out items which are not under the current proxy shape.
if (!item->path().startsWith(proxyPath)) {
return;
}
// Filter out non-USD items.
auto usdItem = UsdUfe::downcast(item);
if (!usdItem) {
return;
}
SdfPath usdPath = usdItem->prim().GetPath();
const int instanceIndex = usdItem->instanceIndex();
#if !defined(USD_IMAGING_API_VERSION) || USD_IMAGING_API_VERSION < 11
usdPath = sceneDelegate.ConvertCachePathToIndexPath(usdPath);
#endif
sceneDelegate.PopulateSelection(
HdSelection::HighlightModeSelect, usdPath, instanceIndex, result);
}
//! \brief Append the selected prim paths to the result list.
void AppendSelectedPrimPaths(const HdSelectionSharedPtr& selection, SdfPathVector& result)
{
if (!selection) {
return;
}
SdfPathVector paths = selection->GetSelectedPrimPaths(HdSelection::HighlightModeSelect);
if (paths.empty()) {
return;
}
if (result.empty()) {
result.swap(paths);
} else {
result.reserve(result.size() + paths.size());
result.insert(result.end(), paths.begin(), paths.end());
}
}
//! \brief Configure repr descriptions
void _ConfigureReprs()
{
const HdMeshReprDesc reprDescHull(
HdMeshGeomStyleHull,
HdCullStyleDontCare,
HdMeshReprDescTokens->surfaceShader,
/*flatShadingEnabled=*/false,
/*blendWireframeColor=*/false);
#ifdef HAS_DEFAULT_MATERIAL_SUPPORT_API
const HdMeshReprDesc reprDescHullDefaultMaterial(
HdMeshGeomStyleHull,
HdCullStyleDontCare,
HdMeshReprDescTokens->constantColor,
/*flatShadingEnabled=*/false,
/*blendWireframeColor=*/false);
#endif
const HdMeshReprDesc reprDescEdge(
HdMeshGeomStyleHullEdgeOnly,
HdCullStyleDontCare,
HdMeshReprDescTokens->surfaceShader,
/*flatShadingEnabled=*/false,
/*blendWireframeColor=*/false);
const HdMeshReprDesc reprDescWire(
HdMeshGeomStyleHullEdgeOnly,
HdCullStyleDontCare,
HdMeshReprDescTokens->surfaceShader,
/*flatShadingEnabled=*/false,
/*blendWireframeColor=*/true);
// Hull desc for shaded display, edge desc for selection highlight.
HdMesh::ConfigureRepr(HdReprTokens->smoothHull, reprDescHull, reprDescEdge);
HdMesh::ConfigureRepr(HdVP2ReprTokens->smoothHullUntextured, reprDescHull, reprDescEdge);
#ifdef HAS_DEFAULT_MATERIAL_SUPPORT_API
// Hull desc for default material display, edge desc for selection highlight.
HdMesh::ConfigureRepr(
HdVP2ReprTokens->defaultMaterial, reprDescHullDefaultMaterial, reprDescEdge);
#endif
// Edge desc for bbox display.
HdMesh::ConfigureRepr(HdVP2ReprTokens->bbox, reprDescEdge);
// Forced representations are used for instanced geometry with display layer overrides
HdMesh::ConfigureRepr(HdVP2ReprTokens->forcedBbox, reprDescEdge);
HdMesh::ConfigureRepr(HdVP2ReprTokens->forcedWire, reprDescWire);
// forcedUntextured repr doesn't use reprDescEdge descriptor because
// its selection highlight will be drawn through a non-forced repr
HdMesh::ConfigureRepr(HdVP2ReprTokens->forcedUntextured, reprDescHull);
// smooth hull for untextured display
HdBasisCurves::ConfigureRepr(
HdVP2ReprTokens->smoothHullUntextured, HdBasisCurvesGeomStylePatch);
// Wireframe desc for bbox display.
HdBasisCurves::ConfigureRepr(HdVP2ReprTokens->bbox, HdBasisCurvesGeomStyleWire);
#ifdef HAS_DEFAULT_MATERIAL_SUPPORT_API
// Wire for default material:
HdBasisCurves::ConfigureRepr(HdVP2ReprTokens->defaultMaterial, HdBasisCurvesGeomStyleWire);
#endif
HdPoints::ConfigureRepr(HdVP2ReprTokens->smoothHullUntextured, HdPointsGeomStylePoints);
}
class UfeObserver : public Ufe::Observer
{
public:
UfeObserver(ProxyRenderDelegate& proxyRenderDelegate)
: Ufe::Observer()
, _proxyRenderDelegate(proxyRenderDelegate)
{
}
void operator()(const Ufe::Notification& notification) override
{
// Handle path change notifications here
#ifdef MAYA_HAS_DISPLAY_LAYER_API
#ifdef UFE_V4_FEATURES_AVAILABLE
if (const auto sceneChanged = dynamic_cast<const Ufe::SceneChanged*>(¬ification)) {
if (Ufe::SceneChanged::SceneCompositeNotification == sceneChanged->opType()) {
const auto& compNotification
= notification.staticCast<Ufe::SceneCompositeNotification>();
for (const auto& op : compNotification) {
handleSceneOp(op);
}
} else {
handleSceneOp(*sceneChanged);
}
}
#else
if (auto objectRenamed = dynamic_cast<const Ufe::ObjectRename*>(¬ification)) {
_proxyRenderDelegate.DisplayLayerPathChanged(
objectRenamed->previousPath(), objectRenamed->item()->path());
} else if (
auto objectReparented = dynamic_cast<const Ufe::ObjectReparent*>(¬ification)) {
_proxyRenderDelegate.DisplayLayerPathChanged(
objectReparented->previousPath(), objectReparented->item()->path());
} else if (
auto compositeNotification
= dynamic_cast<const Ufe::SceneCompositeNotification*>(¬ification)) {
for (const auto& op : compositeNotification->opsList()) {
if (op.opType == Ufe::SceneCompositeNotification::OpType::ObjectRename
|| op.opType == Ufe::SceneCompositeNotification::OpType::ObjectReparent) {
_proxyRenderDelegate.DisplayLayerPathChanged(op.path, op.item->path());
}
}
}
#endif
#endif
// Handle selection change notifications here
// 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;
}
if (dynamic_cast<const Ufe::SelectionChanged*>(¬ification)
|| dynamic_cast<const Ufe::ObjectAdd*>(¬ification)) {
_proxyRenderDelegate.SelectionChanged();
}
}
#ifdef MAYA_HAS_DISPLAY_LAYER_API
#ifdef UFE_V4_FEATURES_AVAILABLE
void handleSceneOp(const Ufe::SceneCompositeNotification::Op& op)
{
if (op.opType == Ufe::SceneChanged::ObjectPathChange) {
if (op.subOpType == Ufe::ObjectPathChange::ObjectReparent
|| op.subOpType == Ufe::ObjectPathChange::ObjectRename) {
_proxyRenderDelegate.DisplayLayerPathChanged(op.path, op.item->path());
}
}
}
#endif
#endif
private:
ProxyRenderDelegate& _proxyRenderDelegate;
};
#ifdef MAYA_HAS_DISPLAY_LAYER_API
#ifdef MAYA_HAS_NEW_DISPLAY_LAYER_MESSAGING_API
void displayLayerMembershipChangedCB(void* data, const MString& memberPath)
{
ProxyRenderDelegate* prd = static_cast<ProxyRenderDelegate*>(data);
if (prd) {
prd->DisplayLayerMembershipChanged(memberPath);
}
}
#else
void displayLayerMembershipChangedCB(void* data)
{
ProxyRenderDelegate* prd = static_cast<ProxyRenderDelegate*>(data);
if (prd) {
for (const auto& stage : MayaUsd::ufe::getAllStages()) {
auto stagePath = Ufe::PathString::string(MayaUsd::ufe::stagePath(stage));
prd->DisplayLayerMembershipChanged(MString(stagePath.c_str()));
}
}
}
#endif
void displayLayerDirtyCB(MObject& node, void* clientData)
{
ProxyRenderDelegate* prd = static_cast<ProxyRenderDelegate*>(clientData);
if (prd && node.hasFn(MFn::kDisplayLayer)) {
MFnDisplayLayer displayLayer(node);
prd->DisplayLayerDirty(displayLayer);
}
}
#endif
void colorPrefsChangedCB(void* clientData)
{
ProxyRenderDelegate* prd = static_cast<ProxyRenderDelegate*>(clientData);
if (prd) {
prd->ColorPrefsChanged();
}
}
void colorManagementRefreshCB(void* clientData)
{
ProxyRenderDelegate* prd = static_cast<ProxyRenderDelegate*>(clientData);
if (prd) {
prd->ColorManagementRefresh();
}
}
// Copied from renderIndex.cpp, the code that does HdRenderIndex::GetDrawItems. But I just want the
// rprimIds, I don't want to go all the way to draw items.
#if defined(HD_API_VERSION) && HD_API_VERSION >= 42
struct _FilterParam
{
const TfTokenVector& renderTags;
const HdRenderIndex* renderIndex;
};
bool _DrawItemFilterPredicate(const SdfPath& rprimID, const void* predicateParam)
{
const _FilterParam* filterParam = static_cast<const _FilterParam*>(predicateParam);
const TfTokenVector& renderTags = filterParam->renderTags;
const HdRenderIndex* renderIndex = filterParam->renderIndex;
//
// Render Tag Filter
//
if (renderTags.empty()) {
// An empty render tag set means everything passes the filter
// Primary user is tests, but some single task render delegates
// that don't support render tags yet also use it.
return true;
} else {
// As the number of tags is expected to be low (<10)
// use a simple linear search.
TfToken primRenderTag = renderIndex->GetRenderTag(rprimID);
size_t numRenderTags = renderTags.size();
size_t tagNum = 0;
while (tagNum < numRenderTags) {
if (renderTags[tagNum] == primRenderTag) {
return true;
}
++tagNum;
}
}
return false;
}
#else
struct _FilterParam
{
const HdRprimCollection& collection;
const TfTokenVector& renderTags;
const HdRenderIndex* renderIndex;
};
bool _DrawItemFilterPredicate(const SdfPath& rprimID, const void* predicateParam)
{
const _FilterParam* filterParam = static_cast<const _FilterParam*>(predicateParam);
const HdRprimCollection& collection = filterParam->collection;
const TfTokenVector& renderTags = filterParam->renderTags;
const HdRenderIndex* renderIndex = filterParam->renderIndex;
//
// Render Tag Filter
//
bool passedRenderTagFilter = false;
if (renderTags.empty()) {
// An empty render tag set means everything passes the filter
// Primary user is tests, but some single task render delegates
// that don't support render tags yet also use it.
passedRenderTagFilter = true;
} else {
// As the number of tags is expected to be low (<10)
// use a simple linear search.
TfToken primRenderTag = renderIndex->GetRenderTag(rprimID);
size_t numRenderTags = renderTags.size();
size_t tagNum = 0;
while (!passedRenderTagFilter && tagNum < numRenderTags) {
if (renderTags[tagNum] == primRenderTag) {
passedRenderTagFilter = true;
}
++tagNum;
}
}
//
// Material Tag Filter
//
bool passedMaterialTagFilter = false;
// Filter out rprims that do not match the collection's materialTag.
// E.g. We may want to gather only opaque or translucent prims.
// An empty materialTag on collection means: ignore material-tags.
// This is important for tasks such as the selection-task which wants
// to ignore materialTags and receive all prims in its collection.
TfToken const& collectionMatTag = collection.GetMaterialTag();
if (collectionMatTag.IsEmpty() || renderIndex->GetMaterialTag(rprimID) == collectionMatTag) {
passedMaterialTagFilter = true;
}
return (passedRenderTagFilter && passedMaterialTagFilter);
}
#endif
bool _longDurationRendering = false;
} // namespace
//! \brief Draw classification used during plugin load to register in VP2
const MString ProxyRenderDelegate::drawDbClassification(
TfStringPrintf(
"drawdb/subscene/vp2RenderDelegate/%s",
MayaUsdProxyShapeBaseTokens->MayaTypeName.GetText())
.c_str());
//! \brief Factory method registered at plugin load
MHWRender::MPxSubSceneOverride* ProxyRenderDelegate::Creator(const MObject& obj)
{
return new ProxyRenderDelegate(obj);
}
//! \brief Constructor
ProxyRenderDelegate::ProxyRenderDelegate(const MObject& obj)
: Autodesk::Maya::OPENMAYA_MPXSUBSCENEOVERRIDE_LATEST_NAMESPACE::MHWRender::MPxSubSceneOverride(
obj)
{
MDagPath proxyDagPath;
MDagPath::getAPathTo(obj, proxyDagPath);
const MFnDependencyNode fnDepNode(obj);
_proxyShapeData.reset(new ProxyShapeData(
static_cast<MayaUsdProxyShapeBase*>(fnDepNode.userNode()), proxyDagPath));
}
//! \brief Destructor
ProxyRenderDelegate::~ProxyRenderDelegate()
{
_ClearRenderDelegate();
#ifdef MAYA_HAS_DISPLAY_LAYER_API
if (_mayaDisplayLayerAddedCallbackId != 0)
MMessage::removeCallback(_mayaDisplayLayerAddedCallbackId);
if (_mayaDisplayLayerRemovedCallbackId != 0)
MMessage::removeCallback(_mayaDisplayLayerRemovedCallbackId);
if (_mayaDisplayLayerMembersCallbackId != 0)
MMessage::removeCallback(_mayaDisplayLayerMembersCallbackId);
for (auto cb : _mayaDisplayLayerDirtyCallbackIds) {
MMessage::removeCallback(cb.second);
}
#endif
for (auto id : _mayaColorPrefsCallbackIds) {
MMessage::removeCallback(id);
}
for (auto id : _mayaColorManagementCallbackIds) {
MMessage::removeCallback(id);
}
}
//! \brief This drawing routine supports all devices (DirectX and OpenGL)
MHWRender::DrawAPI ProxyRenderDelegate::supportedDrawAPIs() const { return MHWRender::kAllDevices; }
//! \brief Enable subscene update in selection passes for deferred update of selection render
//! items.
bool ProxyRenderDelegate::enableUpdateForSelection() const { return true; }
//! \brief Always requires update since changes are tracked by Hydraw change tracker and it will
//! guarantee minimal update; only exception is if rendering through Maya-to-Hydra
bool ProxyRenderDelegate::requiresUpdate(
const MSubSceneContainer& container,
const MFrameContext& frameContext) const
{
// Hydra-based render overrides already take care of USD data,
// so avoid duplicating the effort.
if (px_vp20Utils::HasHydraRenderOverride(frameContext)) {
return false;
}
return true;
}
void ProxyRenderDelegate::_ClearRenderDelegate()
{
// The order of deletion matters. Some orders cause crashes.
_sceneDelegate.reset();
_taskController.reset();
_renderIndex.reset();
_renderDelegate.reset();
_dummyTasks.clear();
// reset any version ids or dirty information that doesn't make sense if we clear
// the render index.
_changeVersions.reset();
_taskRenderTagsValid = false;
_isPopulated = false;
}
//! \brief Clear data which is now stale because proxy shape attributes have changed
void ProxyRenderDelegate::_ClearInvalidData(MSubSceneContainer& container)
{
TF_VERIFY(_proxyShapeData->ProxyShape());
// We have to clear everything when the stage changes because the new stage doesn't necessarily
// have anything in common with the old stage.
// When excluded prims changes we don't have a way to know which (if any) prims were removed
// from excluded prims & so must be re-added to the render index, so we take the easy way out
// and clear everything. If this is a performance problem we can probably store the old value
// of excluded prims, compare it to the new value and only add back the difference.
if (!_proxyShapeData->IsUsdStageUpToDate() || !_proxyShapeData->IsExcludePrimsUpToDate()) {
// Tell texture loading tasks to terminate (exit) if they have not finished yet
if (_renderDelegate) {
dynamic_cast<HdVP2RenderDelegate*>(_renderDelegate.get())->CleanupMaterials();
}
// delete everything so we can re-initialize with the new stage
_ClearRenderDelegate();
container.clear();
}
}
//! \brief Initialize the render delegate
void ProxyRenderDelegate::_InitRenderDelegate()
{
TF_VERIFY(_proxyShapeData->ProxyShape());
// Initialize the optionVar ShowDisplayColorTextureOff, which will decide if display color will
// be used when untextured mode is selected
const MString optionVarName(MayaUsdOptionVars->ShowDisplayColorTextureOff.GetText());
if (!MGlobal::optionVarExists(optionVarName)) {
MGlobal::setOptionVarValue(optionVarName, 0);
}
// No need to run all the checks if we got till the end
if (_isInitialized())
return;
_proxyShapeData->UpdateUsdStage();
_proxyShapeData->UsdStageUpdated();
if (!_renderDelegate) {
MProfilingScope subProfilingScope(
HdVP2RenderDelegate::sProfilerCategory,
MProfiler::kColorD_L1,
"Allocate VP2RenderDelegate");
_renderDelegate.reset(new HdVP2RenderDelegate(*this));
}
if (!_renderIndex) {
MProfilingScope subProfilingScope(
HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorD_L1, "Allocate RenderIndex");
_renderIndex.reset(HdRenderIndex::New(_renderDelegate.get(), HdDriverVector()));
// Sync the _changeVersions so that we don't trigger a needlessly large update them on the
// first frame.
_changeVersions.sync(_renderIndex->GetChangeTracker());
// Add additional configurations after render index creation.
static std::once_flag reprsOnce;
std::call_once(reprsOnce, _ConfigureReprs);
}
if (!_sceneDelegate) {
MProfilingScope subProfilingScope(
HdVP2RenderDelegate::sProfilerCategory,
MProfiler::kColorD_L1,
"Allocate SceneDelegate");
// Make sure the delegate name is a valid identifier, since it may
// include colons if the proxy node is in a Maya namespace.
const std::string delegateName = TfMakeValidIdentifier(TfStringPrintf(
"Proxy_%s_%p",
_proxyShapeData->ProxyShape()->name().asChar(),
_proxyShapeData->ProxyShape()));
const SdfPath delegateID = SdfPath::AbsoluteRootPath().AppendChild(TfToken(delegateName));
_sceneDelegate.reset(new UsdImagingDelegate(_renderIndex.get(), delegateID));
_taskController.reset(new HdxTaskController(
_renderIndex.get(),
delegateID.AppendChild(TfToken(TfStringPrintf("_UsdImaging_VP2_%p", this)))));
_defaultCollection.reset(new HdRprimCollection());
_defaultCollection->SetName(HdTokens->geometry);
if (!_observer) {
_observer = std::make_shared<UfeObserver>(*this);
auto globalSelection = Ufe::GlobalSelection::get();
if (TF_VERIFY(globalSelection)) {
globalSelection->addObserver(_observer);
}
Ufe::Scene::instance().addObserver(_observer);
}
#ifdef MAYA_HAS_DISPLAY_LAYER_API
// Display layers maybe loaded before us, so make sure to track/cache them
_usdStageDisplayLayersDirty = true;
MFnDisplayLayerManager displayLayerManager(
MFnDisplayLayerManager::currentDisplayLayerManager());
auto layers = displayLayerManager.getAllDisplayLayers();
for (unsigned int j = 0; j < layers.length(); ++j) {
DisplayLayerAdded(layers[j], this);
AddDisplayLayerToCache(layers[j]);
}
// Monitor display layers
if (!_mayaDisplayLayerAddedCallbackId) {
_mayaDisplayLayerAddedCallbackId
= MDGMessage::addNodeAddedCallback(DisplayLayerAdded, "displayLayer", this);
}
if (!_mayaDisplayLayerRemovedCallbackId) {
_mayaDisplayLayerRemovedCallbackId
= MDGMessage::addNodeRemovedCallback(DisplayLayerRemoved, "displayLayer", this);
}
if (!_mayaDisplayLayerMembersCallbackId) {
_mayaDisplayLayerMembersCallbackId
#ifdef MAYA_HAS_NEW_DISPLAY_LAYER_MESSAGING_API
= MDisplayLayerMessage::addDisplayLayerMemberChangedCallback(
#else
= MDisplayLayerMessage::addDisplayLayerMembersChangedCallback(
#endif
displayLayerMembershipChangedCB, this);
}
#endif
// Monitor color prefs.
_mayaColorPrefsCallbackIds.push_back(
MEventMessage::addEventCallback("ColorIndexChanged", colorPrefsChangedCB, this));
_mayaColorPrefsCallbackIds.push_back(
MEventMessage::addEventCallback("DisplayColorChanged", colorPrefsChangedCB, this));
_mayaColorPrefsCallbackIds.push_back(
MEventMessage::addEventCallback("DisplayRGBColorChanged", colorPrefsChangedCB, this));
// Monitor color management prefs.
_mayaColorManagementCallbackIds.push_back(MEventMessage::addEventCallback(
"colorMgtEnabledChanged", colorManagementRefreshCB, this));
_mayaColorManagementCallbackIds.push_back(MEventMessage::addEventCallback(
"colorMgtWorkingSpaceChanged", colorManagementRefreshCB, this));
_mayaColorManagementCallbackIds.push_back(MEventMessage::addEventCallback(
"colorMgtConfigChanged", colorManagementRefreshCB, this));
_mayaColorManagementCallbackIds.push_back(MEventMessage::addEventCallback(
"colorMgtConfigFilePathChanged", colorManagementRefreshCB, this));
// We don't really need any HdTask because VP2RenderDelegate uses Hydra
// engine for data preparation only, but we have to add a dummy render
// task to bootstrap data preparation.
const HdTaskSharedPtrVector tasks = _taskController->GetRenderingTasks();
for (const HdTaskSharedPtr& task : tasks) {
if (dynamic_cast<const HdxRenderTask*>(task.get())) {
_dummyTasks.push_back(task);
break;
}
}
}
}
//! \brief Populate render index with prims coming from scene delegate.
//! \return True when delegate is ready to draw
bool ProxyRenderDelegate::_Populate()
{
TF_VERIFY(_proxyShapeData->ProxyShape());
if (!_isInitialized())
return false;
if (_proxyShapeData->UsdStage() && !_isPopulated) {
MProfilingScope subProfilingScope(
HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorD_L1, "Populate");
// Remove any excluded prims before populating
SdfPathVector excludePrimPaths = _proxyShapeData->ProxyShape()->getExcludePrimPaths();
for (auto& excludePrim : excludePrimPaths) {
SdfPath indexPath = _sceneDelegate->ConvertCachePathToIndexPath(excludePrim);
if (_renderIndex->HasRprim(indexPath)) {
_renderIndex->RemoveRprim(indexPath);
}
}
_proxyShapeData->ExcludePrimsUpdated();
_sceneDelegate->Populate(_proxyShapeData->ProxyShape()->usdPrim(), excludePrimPaths);
_isPopulated = true;
}
return _isPopulated;
}
//! \brief Synchronize USD scene delegate with Maya's proxy shape.
void ProxyRenderDelegate::_UpdateSceneDelegate()
{
TF_VERIFY(_proxyShapeData->ProxyShape());
if (!_sceneDelegate)
return;
MProfilingScope profilingScope(
HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L1, "UpdateSceneDelegate");
{
MProfilingScope subProfilingScope(
HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L1, "SetTime");
const UsdTimeCode timeCode = _proxyShapeData->ProxyShape()->getTime();
_sceneDelegate->SetTime(timeCode);
}
// Update the root transform used to render by the delegate.
// When using a primPath as the root prim, USD treats it as identity, so we
// compensate by including its world transform in the root transform — unless
// the Maya DAG already accounts for it (isRootPrimTransformInDagPath).
const MMatrix inclusiveMatrix = _proxyShapeData->ProxyDagPath().inclusiveMatrix();
GfMatrix4d transform(inclusiveMatrix.matrix);
if (_proxyShapeData->ProxyShape()->usdPrim().GetPath() != SdfPath::AbsoluteRootPath()
&& !_proxyShapeData->ProxyShape()->isRootPrimTransformInDagPath()) {
const UsdTimeCode timeCode = _proxyShapeData->ProxyShape()->getTime();
UsdGeomXformCache xformCache(timeCode);
GfMatrix4d m
= xformCache.GetLocalToWorldTransform(_proxyShapeData->ProxyShape()->usdPrim());
transform = m * transform;
}
constexpr double tolerance = 1e-9;
if (!GfIsClose(transform, _sceneDelegate->GetRootTransform(), tolerance)) {
MProfilingScope subProfilingScope(
HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L1, "SetRootTransform");
_sceneDelegate->SetRootTransform(transform);
}
const bool isVisible = _proxyShapeData->ProxyDagPath().isVisible();
if (isVisible != _sceneDelegate->GetRootVisibility()) {
MProfilingScope subProfilingScope(
HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L1, "SetRootVisibility");
_sceneDelegate->SetRootVisibility(isVisible);
// Trigger selection update when a hidden proxy shape gets shown.
if (isVisible) {
SelectionChanged();
}
}
const int refineLevel = _proxyShapeData->ProxyShape()->getComplexity();
if (refineLevel != _sceneDelegate->GetRefineLevelFallback()) {
MProfilingScope subProfilingScope(
HdVP2RenderDelegate::sProfilerCategory,
MProfiler::kColorC_L1,
"SetRefineLevelFallback");
_sceneDelegate->SetRefineLevelFallback(refineLevel);
}
}
void ProxyRenderDelegate::_PopulateCleanup()
{
// Get rid of shaders no longer in use.
HdVP2ShaderUniquePtr::cleanupDeadShaders();
}
InstancePrototypePath ProxyRenderDelegate::GetPathInPrototype(const SdfPath& id)
{
HdInstancerContext instancerContext;
auto usdInstancePath = GetScenePrimPath(id, 0, &instancerContext);
// In case of point instancer, we already have the path in prototype, return it.
if (!instancerContext.empty()) {
return InstancePrototypePath(usdInstancePath, kPointInstancing);
}
// In case of a native instance, obtain the path in prototype and return it.
auto usdInstancePrim = _proxyShapeData->UsdStage()->GetPrimAtPath(usdInstancePath);
auto usdPrototypePath = usdInstancePrim.GetPrimInPrototype().GetPath();
return InstancePrototypePath(usdPrototypePath, kNativeInstancing);
}
void ProxyRenderDelegate::UpdateInstancingMapEntry(
const InstancePrototypePath& oldPathInPrototype,
const InstancePrototypePath& newPathInPrototype,
const SdfPath& rprimId)
{
if (oldPathInPrototype != newPathInPrototype) {
// remove the old entry from the map
if (!oldPathInPrototype.first.IsEmpty()) {
auto range = _instancingMap.equal_range(oldPathInPrototype);
auto it = std::find(
range.first,
range.second,
std::pair<const InstancePrototypePath, SdfPath>(oldPathInPrototype, rprimId));
if (it != range.second) {
_instancingMap.erase(it);
}
}
// add new entry to the map
if (!newPathInPrototype.first.IsEmpty()) {
_instancingMap.insert(std::make_pair(newPathInPrototype, rprimId));
}
}
}
#ifdef MAYA_HAS_DISPLAY_LAYER_API
void ProxyRenderDelegate::_DirtyUsdSubtree(const UsdPrim& prim)
{
if (!prim.IsValid())
return;
HdChangeTracker& changeTracker = _renderIndex->GetChangeTracker();
auto markRprimDirty = [this, &changeTracker](const UsdPrim& prim) {
constexpr HdDirtyBits dirtyBits = HdChangeTracker::DirtyVisibility
| HdChangeTracker::DirtyRepr | HdChangeTracker::DirtyDisplayStyle
| MayaUsdRPrim::DirtySelectionHighlight | MayaUsdRPrim::DirtyDisplayLayers
| HdChangeTracker::DirtyMaterialId;
if (prim.IsA<UsdGeomGprim>()) {
auto range = _instancingMap.equal_range(
InstancePrototypePath(prim.GetPath(), kPointInstancing));
if (range.first != range.second) {
// Point instancing prim
for (auto it = range.first; it != range.second; ++it) {
if (_renderIndex->HasRprim(it->second)) {
changeTracker.MarkRprimDirty(it->second, dirtyBits);
}
}
} else if (prim.IsInstanceProxy()) {
// Native instancing prim
range = _instancingMap.equal_range(
InstancePrototypePath(prim.GetPrimInPrototype().GetPath(), kNativeInstancing));
for (auto it = range.first; it != range.second; ++it) {
if (_renderIndex->HasRprim(it->second)) {
changeTracker.MarkRprimDirty(it->second, dirtyBits);
}
}
} else {
// Non-instanced prim
auto indexPath = _sceneDelegate->ConvertCachePathToIndexPath(prim.GetPath());
if (_renderIndex->HasRprim(indexPath)) {
changeTracker.MarkRprimDirty(indexPath, dirtyBits);
}
}
}
};
markRprimDirty(prim);
auto range = prim.GetFilteredDescendants(UsdTraverseInstanceProxies());
for (auto iter = range.begin(); iter != range.end(); ++iter) {
markRprimDirty(iter->GetPrim());
}
}
bool ProxyRenderDelegate::_DirtyUfeSubtree(const Ufe::Path& rootPath)
{
Ufe::Path proxyShapePath = MayaUsd::ufe::stagePath(_proxyShapeData->UsdStage());
if (rootPath.runTimeId() == MayaUsd::ufe::getUsdRunTimeId()) {
if (rootPath.startsWith(proxyShapePath)) {
_DirtyUsdSubtree(MayaUsd::ufe::ufePathToPrim(rootPath));
return true;
}
} else if (rootPath.runTimeId() == MayaUsd::ufe::getMayaRunTimeId()) {
if (proxyShapePath.startsWith(rootPath)) {
_DirtyUsdSubtree(_proxyShapeData->UsdStage()->GetPseudoRoot());
return true;
}
}