-
Notifications
You must be signed in to change notification settings - Fork 203
/
Copy pathmesh.cpp
2797 lines (2478 loc) · 122 KB
/
mesh.cpp
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 "mesh.h"
#include "bboxGeom.h"
#include "debugCodes.h"
#include "instancer.h"
#include "material.h"
#include "renderDelegate.h"
#include "tokens.h"
#include <mayaUsd/base/tokens.h>
#include <mayaUsd/render/vp2RenderDelegate/proxyRenderDelegate.h>
#include <mayaUsd/utils/colorSpace.h>
#include <pxr/base/gf/matrix4d.h>
#include <pxr/base/tf/getenv.h>
#include <pxr/imaging/hd/extComputation.h>
#include <pxr/imaging/hd/meshUtil.h>
#include <pxr/imaging/hd/sceneDelegate.h>
#include <pxr/imaging/hd/smoothNormals.h>
#include <pxr/imaging/hd/version.h>
#include <pxr/imaging/hd/vertexAdjacency.h>
#include <pxr/pxr.h>
#include <pxr/usdImaging/usdImaging/version.h>
#if !defined(USD_IMAGING_API_VERSION) || USD_IMAGING_API_VERSION < 18
#include <pxr/usdImaging/usdImaging/delegate.h>
#endif
#if !defined(HD_API_VERSION) || HD_API_VERSION < 49
#include <pxr/imaging/hd/extCompCpuComputation.h>
#else
#include <pxr/imaging/hdSt/extCompCpuComputation.h>
#endif
#include <maya/MFrameContext.h>
#include <maya/MMatrix.h>
#include <maya/MProfiler.h>
#include <maya/MSelectionMask.h>
#include <numeric>
#include <type_traits>
PXR_NAMESPACE_OPEN_SCOPE
namespace {
//! Required primvars when there is no material binding.
const TfTokenVector sFallbackShaderPrimvars
= { HdTokens->displayColor, HdTokens->displayOpacity, HdTokens->normals };
// Proper support for selection highlighting on/off switch in
// MRenderItem starts only beyond Maya 2024.1
#if MAYA_API_VERSION > 20240100
constexpr int sDrawModeSelectionHighlighting = MHWRender::MGeometry::kSelectionHighlighting;
#else
constexpr int sDrawModeSelectionHighlighting = 0;
#endif
//! Helper utility function to fill primvar data to vertex buffer.
template <class DEST_TYPE, class SRC_TYPE>
void _FillPrimvarData(
DEST_TYPE* vertexBuffer,
size_t numVertices,
size_t channelOffset,
const VtIntArray& renderingToSceneFaceVtxIds,
const MString& rprimId,
const HdMeshTopology& topology,
const TfToken& primvarName,
const VtArray<SRC_TYPE>& primvarData,
const HdInterpolation& primvarInterp)
{
const unsigned int dataSize = primvarData.size();
switch (primvarInterp) {
case HdInterpolationConstant: {
SRC_TYPE value {};
if (dataSize > 0) {
value = primvarData[0];
} else {
TF_DEBUG(HDVP2_DEBUG_MESH)
.Msg(
"Invalid Hydra prim '%s': "
"primvar %s has %u elements, while its topology "
"references face vertex index %u.\n",
rprimId.asChar(),
primvarName.GetText(),
dataSize,
0);
}
for (size_t v = 0; v < numVertices; v++) {
SRC_TYPE* pointer = reinterpret_cast<SRC_TYPE*>(
reinterpret_cast<float*>(&vertexBuffer[v]) + channelOffset);
*pointer = value;
}
break;
}
case HdInterpolationVarying:
case HdInterpolationVertex:
// The primvar has less data than needed, we issue a warning but
// don't skip update. Truncate the buffer to the lesser length.
if (numVertices > renderingToSceneFaceVtxIds.size()) {
TF_DEBUG(HDVP2_DEBUG_MESH)
.Msg(
"Invalid Hydra prim '%s': "
"requires %zu vertices, while the number of elements in "
"renderingToSceneFaceVtxIds is %zu.",
rprimId.asChar(),
numVertices,
renderingToSceneFaceVtxIds.size());
numVertices = renderingToSceneFaceVtxIds.size();
}
for (size_t v = 0; v < numVertices; v++) {
unsigned int index = renderingToSceneFaceVtxIds[v];
if (index < dataSize) {
SRC_TYPE* pointer = reinterpret_cast<SRC_TYPE*>(
reinterpret_cast<float*>(&vertexBuffer[v]) + channelOffset);
*pointer = primvarData[index];
} else {
TF_DEBUG(HDVP2_DEBUG_MESH)
.Msg(
"Invalid Hydra prim '%s': "
"primvar %s has %u elements, while its topology "
"references face vertex index %u.\n",
rprimId.asChar(),
primvarName.GetText(),
dataSize,
index);
}
}
break;
case HdInterpolationUniform: {
const VtIntArray& faceVertexCounts = topology.GetFaceVertexCounts();
size_t numFaces = faceVertexCounts.size();
// The primvar has less data than needed, we issue a warning but
// don't skip update. Truncate the buffer to the lesser length.
if (numFaces > dataSize) {
TF_DEBUG(HDVP2_DEBUG_MESH)
.Msg(
"Invalid Hydra prim '%s': "
"primvar %s has only %u elements, while its topology expects "
"at least %zu elements.\n",
rprimId.asChar(),
primvarName.GetText(),
dataSize,
numFaces);
numFaces = dataSize;
}
// The primvar has more data than needed, we issue a warning but
// don't skip update. Truncate the buffer to the expected length.
if (numFaces < dataSize) {
TF_DEBUG(HDVP2_DEBUG_MESH)
.Msg(
"Invalid Hydra prim '%s': "
"primvar %s has %u elements, while its topology "
"references only upto element index %zu.\n",
rprimId.asChar(),
primvarName.GetText(),
dataSize,
numFaces);
}
for (size_t f = 0, v = 0; f < numFaces; f++) {
const size_t faceVertexCount = faceVertexCounts[f];
const size_t faceVertexEnd = v + faceVertexCount;
for (; v < faceVertexEnd; v++) {
SRC_TYPE* pointer = reinterpret_cast<SRC_TYPE*>(
reinterpret_cast<float*>(&vertexBuffer[v]) + channelOffset);
*pointer = primvarData[f];
}
}
break;
}
case HdInterpolationFaceVarying:
// Unshared vertex layout is required for face-varying primvars, in
// this case renderingToSceneFaceVtxIds is a natural sequence starting
// from 0, thus we can save a lookup into the table. If the assumption
// about the natural sequence is changed, we will need the lookup and
// remap indices.
// The primvar has less data than needed, we issue a warning but
// don't skip update. Truncate the buffer to the lesser length.
if (numVertices > dataSize) {
TF_DEBUG(HDVP2_DEBUG_MESH)
.Msg(
"Invalid Hydra prim '%s': "
"primvar %s has only %u elements, while its topology expects "
"at least %zu elements.\n",
rprimId.asChar(),
primvarName.GetText(),
dataSize,
numVertices);
numVertices = dataSize;
}
// If the primvar has more data than needed, we issue a warning,
// but don't skip the primvar update. Truncate the buffer to the
// expected length.
if (numVertices < dataSize) {
TF_DEBUG(HDVP2_DEBUG_MESH)
.Msg(
"Invalid Hydra prim '%s': "
"primvar %s has %u elements, while its topology references "
"only upto element index %zu.\n",
rprimId.asChar(),
primvarName.GetText(),
dataSize,
numVertices);
}
if (channelOffset == 0 && std::is_same<DEST_TYPE, SRC_TYPE>::value) {
const void* source = static_cast<const void*>(primvarData.cdata());
memcpy(vertexBuffer, source, sizeof(DEST_TYPE) * numVertices);
} else {
for (size_t v = 0; v < numVertices; v++) {
SRC_TYPE* pointer = reinterpret_cast<SRC_TYPE*>(
reinterpret_cast<float*>(&vertexBuffer[v]) + channelOffset);
*pointer = primvarData[v];
}
}
break;
default:
TF_CODING_ERROR(
"Invalid Hydra prim '%s': "
"unimplemented interpolation %d for primvar %s",
rprimId.asChar(),
(int)primvarInterp,
primvarName.GetText());
break;
}
}
//! If there is uniform or face-varying primvar, we have to create unshared
//! vertex layout on CPU because SSBO technique is not widely supported by
//! GPUs and 3D APIs.
bool _IsUnsharedVertexLayoutRequired(const PrimvarInfoMap& primvarInfo)
{
for (const auto& it : primvarInfo) {
const HdInterpolation interp = it.second->_source.interpolation;
if (interp == HdInterpolationUniform || interp == HdInterpolationFaceVarying) {
return true;
}
}
return false;
}
//! Helper utility function to get number of edge indices
unsigned int _GetNumOfEdgeIndices(const HdMeshTopology& topology)
{
const VtIntArray& faceVertexCounts = topology.GetFaceVertexCounts();
unsigned int numIndex = 0;
for (std::size_t i = 0; i < faceVertexCounts.size(); i++) {
numIndex += faceVertexCounts[i];
}
numIndex *= 2; // each edge has two ends.
return numIndex;
}
//! Helper utility function to extract edge indices
void _FillEdgeIndices(int* indices, const HdMeshTopology& topology)
{
const VtIntArray& faceVertexCounts = topology.GetFaceVertexCounts();
const int* currentFaceStart = topology.GetFaceVertexIndices().cdata();
for (std::size_t faceId = 0; faceId < faceVertexCounts.size(); faceId++) {
int numVertexIndicesInFace = faceVertexCounts[faceId];
if (numVertexIndicesInFace >= 2) {
for (int faceVertexId = 0; faceVertexId < numVertexIndicesInFace; faceVertexId++) {
bool isLastVertex = faceVertexId == numVertexIndicesInFace - 1;
*(indices++) = *(currentFaceStart + faceVertexId);
*(indices++)
= isLastVertex ? *currentFaceStart : *(currentFaceStart + faceVertexId + 1);
}
}
currentFaceStart += numVertexIndicesInFace;
}
}
PrimvarInfo* _getInfo(const PrimvarInfoMap& infoMap, const TfToken& token)
{
auto it = infoMap.find(token);
if (it != infoMap.end()) {
return it->second.get();
}
return nullptr;
}
void _getColorData(
PrimvarInfoMap& infoMap,
VtVec3fArray& colorArray,
HdInterpolation& interpolation)
{
PrimvarInfo* info = _getInfo(infoMap, HdTokens->displayColor);
if (info) {
const VtValue& value = info->_source.data;
if (value.IsHolding<VtVec3fArray>() && value.GetArraySize() > 0) {
colorArray = value.UncheckedGet<VtVec3fArray>();
interpolation = info->_source.interpolation;
}
}
if (colorArray.empty()) {
// If color/opacity is not found, the 18% gray color will be used
// to match the default color of Hydra Storm.
colorArray.push_back(GfVec3f(0.18f, 0.18f, 0.18f));
interpolation = HdInterpolationConstant;
infoMap[HdTokens->displayColor] = std::make_unique<PrimvarInfo>(
PrimvarSource(VtValue(colorArray), interpolation, PrimvarSource::CPUCompute), nullptr);
} else {
for (size_t i = 0; i < colorArray.size(); ++i) {
colorArray[i] = MayaUsd::utils::ConvertLinearToMaya(colorArray[i]);
}
}
}
void _getOpacityData(
PrimvarInfoMap& infoMap,
VtFloatArray& opacityArray,
HdInterpolation& interpolation)
{
PrimvarInfo* info = _getInfo(infoMap, HdTokens->displayOpacity);
if (info) {
const VtValue& value = info->_source.data;
if (value.IsHolding<VtFloatArray>() && value.GetArraySize() > 0) {
opacityArray = value.UncheckedGet<VtFloatArray>();
interpolation = info->_source.interpolation;
}
}
if (opacityArray.empty()) {
opacityArray.push_back(1.0f);
interpolation = HdInterpolationConstant;
infoMap[HdTokens->displayOpacity] = std::make_unique<PrimvarInfo>(
PrimvarSource(VtValue(opacityArray), interpolation, PrimvarSource::CPUCompute),
nullptr);
}
}
//! Access the points
VtVec3fArray _points(PrimvarInfoMap& infoMap)
{
if (PrimvarInfo* info = _getInfo(infoMap, HdTokens->points)) {
VtValue data = info->_source.data;
TF_VERIFY(data.IsHolding<VtVec3fArray>());
return data.UncheckedGet<VtVec3fArray>();
}
return VtVec3fArray();
}
} // namespace
void HdVP2Mesh::_InitGPUCompute()
{
// check that the viewport is using OpenGL, we need it for the OpenGL normals computation
MRenderer* renderer = MRenderer::theRenderer();
// would also be nice to check the openGL version but renderer->drawAPIVersion() returns 4.
// Compute was added in 4.3 so I don't have enough information to make the check
if (renderer && renderer->drawAPIIsOpenGL()
&& (TfGetenvInt("HDVP2_USE_GPU_NORMAL_COMPUTATION", 0) > 0)) {
int threshold = TfGetenvInt("HDVP2_GPU_NORMAL_COMPUTATION_MINIMUM_THRESHOLD", 8000);
_gpuNormalsComputeThreshold = threshold >= 0 ? (size_t)threshold : SIZE_MAX;
} else
_gpuNormalsComputeThreshold = SIZE_MAX;
}
size_t HdVP2Mesh::_gpuNormalsComputeThreshold = SIZE_MAX;
//! \brief Constructor
#if defined(HD_API_VERSION) && HD_API_VERSION >= 36
HdVP2Mesh::HdVP2Mesh(HdVP2RenderDelegate* delegate, const SdfPath& id)
: HdMesh(id)
#else
HdVP2Mesh::HdVP2Mesh(HdVP2RenderDelegate* delegate, const SdfPath& id, const SdfPath& instancerId)
: HdMesh(id, instancerId)
#endif
, MayaUsdRPrim(delegate, id)
{
_meshSharedData = std::make_shared<HdVP2MeshSharedData>();
// HdChangeTracker::IsVarying() can check dirty bits to tell us if an object is animated or not.
// Not sure if it is correct on file load
#ifdef HDVP2_ENABLE_GPU_COMPUTE
static std::once_flag initGPUComputeOnce;
std::call_once(initGPUComputeOnce, _InitGPUCompute);
#endif
}
void HdVP2Mesh::_PrepareSharedVertexBuffers(
HdSceneDelegate* delegate,
const HdDirtyBits& rprimDirtyBits,
const TfToken& reprToken)
{
MProfilingScope profilingScope(
HdVP2RenderDelegate::sProfilerCategory,
MProfiler::kColorC_L2,
_rprimId.asChar(),
"HdVP2Mesh::_PrepareSharedVertexBuffers");
// Normals have two possible sources. They could be authored by the scene delegate,
// in which case we should find them in _primvarInfo, or they could be computed
// normals. Compute the normal buffer if necessary.
PrimvarInfo* normalsInfo = _getInfo(_meshSharedData->_primvarInfo, HdTokens->normals);
bool needNormals = _PrimvarIsRequired(HdTokens->normals);
bool computeCPUNormals = (!normalsInfo && !_gpuNormalsEnabled)
|| (normalsInfo && PrimvarSource::CPUCompute == normalsInfo->_source.dataSource);
bool computeGPUNormals = (!normalsInfo && _gpuNormalsEnabled)
|| (normalsInfo && PrimvarSource::GPUCompute == normalsInfo->_source.dataSource);
bool hasCleanNormals
= normalsInfo && (0 == (rprimDirtyBits & (DirtySmoothNormals | DirtyFlatNormals)));
if (needNormals && (computeCPUNormals || computeGPUNormals) && !hasCleanNormals) {
_MeshReprConfig::DescArray reprDescs = _GetReprDesc(reprToken);
// Iterate through all reprdescs for the current repr to figure out if any
// of them requires smooth normals or flat normals. If either (or both)
// are required, we will calculate them once and clean the bits.
bool requireSmoothNormals = false;
bool requireFlatNormals = false;
for (size_t descIdx = 0; descIdx < reprDescs.size(); ++descIdx) {
const HdMeshReprDesc& desc = reprDescs[descIdx];
if (desc.geomStyle == HdMeshGeomStyleHull) {
if (desc.flatShadingEnabled) {
requireFlatNormals = true;
} else {
requireSmoothNormals = true;
}
}
}
// If there are authored normals, prepare buffer only when it is dirty.
// otherwise, compute smooth normals from points and adjacency and we
// have a custom dirty bit to determine whether update is needed.
if (requireSmoothNormals && (rprimDirtyBits & DirtySmoothNormals)) {
if (computeGPUNormals) {
#ifdef HDVP2_ENABLE_GPU_COMPUTE
_meshSharedData->_viewportCompute->setNormalVertexBufferGPUDirty();
#endif
}
if (computeCPUNormals) {
// note: normals gets dirty when points are marked as dirty,
// at change tracker.
if (!_meshSharedData->_adjacency) {
MProfilingScope profilingScope(
HdVP2RenderDelegate::sProfilerCategory,
MProfiler::kColorC_L2,
_rprimId.asChar(),
"HdVP2Mesh::computeAdjacency");
_meshSharedData->_adjacency.reset(new Hd_VertexAdjacency());
_meshSharedData->_adjacency->BuildAdjacencyTable(&_meshSharedData->_topology);
}
// Only the points referenced by the topology are used to compute
// smooth normals.
VtValue normals(Hd_SmoothNormals::ComputeSmoothNormals(
_meshSharedData->_adjacency.get(),
_points(_meshSharedData->_primvarInfo).size(),
_points(_meshSharedData->_primvarInfo).cdata()));
if (!normalsInfo) {
_meshSharedData->_primvarInfo[HdTokens->normals]
= std::make_unique<PrimvarInfo>(
PrimvarSource(
normals, HdInterpolationVertex, PrimvarSource::CPUCompute),
nullptr);
} else {
normalsInfo->_source.data = normals;
normalsInfo->_source.interpolation = HdInterpolationVertex;
}
}
}
if (requireFlatNormals && (rprimDirtyBits & DirtyFlatNormals)) {
// TODO:
}
}
// Prepare color buffer.
if (((rprimDirtyBits
& (HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyInstancer
| HdChangeTracker::DirtyInstanceIndex))
!= 0)
&& (_PrimvarIsRequired(HdTokens->displayColor)
|| _PrimvarIsRequired(HdTokens->displayOpacity))) {
HdInterpolation colorInterp = HdInterpolationConstant;
HdInterpolation alphaInterp = HdInterpolationConstant;
VtVec3fArray colorArray;
VtFloatArray alphaArray;
_getColorData(_meshSharedData->_primvarInfo, colorArray, colorInterp);
_getOpacityData(_meshSharedData->_primvarInfo, alphaArray, alphaInterp);
PrimvarInfo* colorAndOpacityInfo
= _getInfo(_meshSharedData->_primvarInfo, HdVP2Tokens->displayColorAndOpacity);
if (!colorAndOpacityInfo) {
_meshSharedData->_primvarInfo[HdVP2Tokens->displayColorAndOpacity]
= std::make_unique<PrimvarInfo>(
PrimvarSource(VtValue(), HdInterpolationConstant, PrimvarSource::CPUCompute),
nullptr);
colorAndOpacityInfo
= _getInfo(_meshSharedData->_primvarInfo, HdVP2Tokens->displayColorAndOpacity);
}
if (colorInterp == HdInterpolationInstance || alphaInterp == HdInterpolationInstance) {
TF_VERIFY(!GetInstancerId().IsEmpty());
VtIntArray instanceIndices = delegate->GetInstanceIndices(GetInstancerId(), GetId());
size_t numInstances = instanceIndices.size();
colorAndOpacityInfo->_extraInstanceData.setLength(
numInstances * kNumColorChannels); // the data is a vec4
void* bufferData = &colorAndOpacityInfo->_extraInstanceData[0];
colorAndOpacityInfo->_source.interpolation = HdInterpolationInstance;
size_t alphaChannelOffset = 3;
for (size_t instance = 0; instance < numInstances; instance++) {
int index = instanceIndices[instance];
GfVec3f* color = reinterpret_cast<GfVec3f*>(
reinterpret_cast<float*>(&static_cast<GfVec4f*>(bufferData)[instance]));
float* alpha
= reinterpret_cast<float*>(&static_cast<GfVec4f*>(bufferData)[instance])
+ alphaChannelOffset;
if (colorInterp == HdInterpolationInstance) {
*color = colorArray[index];
} else if (colorInterp == HdInterpolationConstant) {
*color = colorArray[0];
} else {
TF_WARN("Unsupported combination of display color interpolation and display "
"opacity interpolation instance.");
}
if (alphaInterp == HdInterpolationInstance) {
*alpha = alphaArray[index];
} else if (alphaInterp == HdInterpolationConstant) {
*alpha = alphaArray[0];
} else {
TF_WARN("Unsupported combination of display color interpolation instance and "
"display opacity interpolation.");
}
}
} else {
if (!colorAndOpacityInfo->_buffer) {
const MHWRender::MVertexBufferDescriptor vbDesc(
"", MHWRender::MGeometry::kColor, MHWRender::MGeometry::kFloat, 4);
colorAndOpacityInfo->_buffer.reset(new MHWRender::MVertexBuffer(vbDesc));
}
void* bufferData = _meshSharedData->_numVertices > 0
? colorAndOpacityInfo->_buffer->acquire(_meshSharedData->_numVertices, true)
: nullptr;
// Fill color and opacity into the float4 color stream.
if (bufferData) {
_FillPrimvarData(
static_cast<GfVec4f*>(bufferData),
_meshSharedData->_numVertices,
0,
_meshSharedData->_renderingToSceneFaceVtxIds,
_rprimId,
_meshSharedData->_topology,
HdTokens->displayColor,
colorArray,
colorInterp);
_FillPrimvarData(
static_cast<GfVec4f*>(bufferData),
_meshSharedData->_numVertices,
3,
_meshSharedData->_renderingToSceneFaceVtxIds,
_rprimId,
_meshSharedData->_topology,
HdTokens->displayOpacity,
alphaArray,
alphaInterp);
_CommitMVertexBuffer(colorAndOpacityInfo->_buffer.get(), bufferData);
}
}
}
// prepare the other primvar buffers
// Prepare primvar buffers.
if (rprimDirtyBits
& (HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyNormals
| HdChangeTracker::DirtyPrimvar)) {
for (const auto& it : _meshSharedData->_primvarInfo) {
const TfToken& token = it.first;
// Color, opacity have been prepared separately.
if ((token == HdTokens->displayColor) || (token == HdTokens->displayOpacity)
|| (token == HdVP2Tokens->displayColorAndOpacity))
continue;
MHWRender::MGeometry::Semantic semantic = MHWRender::MGeometry::kTexture;
if (token == HdTokens->points) {
if ((rprimDirtyBits & HdChangeTracker::DirtyPoints) == 0)
continue;
semantic = MHWRender::MGeometry::kPosition;
} else if (token == HdTokens->normals) {
if ((rprimDirtyBits & (HdChangeTracker::DirtyNormals | DirtySmoothNormals)) == 0)
continue;
semantic = MHWRender::MGeometry::kNormal;
} else if ((rprimDirtyBits & HdChangeTracker::DirtyPrimvar) == 0) {
continue;
}
const VtValue& value = it.second->_source.data;
const HdInterpolation& interp = it.second->_source.interpolation;
if (!value.IsArrayValued() || value.GetArraySize() == 0)
continue;
MHWRender::MVertexBuffer* buffer = _meshSharedData->_primvarInfo[token]->_buffer.get();
void* bufferData = nullptr;
if (value.IsHolding<VtFloatArray>()) {
if (!buffer) {
const MHWRender::MVertexBufferDescriptor vbDesc(
"", semantic, MHWRender::MGeometry::kFloat, 1);
buffer = new MHWRender::MVertexBuffer(vbDesc);
_meshSharedData->_primvarInfo[token]->_buffer.reset(buffer);
}
if (buffer) {
bufferData = _meshSharedData->_numVertices > 0
? buffer->acquire(_meshSharedData->_numVertices, true)
: nullptr;
if (bufferData) {
_FillPrimvarData(
static_cast<float*>(bufferData),
_meshSharedData->_numVertices,
0,
_meshSharedData->_renderingToSceneFaceVtxIds,
_rprimId,
_meshSharedData->_topology,
token,
value.UncheckedGet<VtFloatArray>(),
interp);
}
}
} else if (value.IsHolding<VtVec2fArray>()) {
if (!buffer) {
const MHWRender::MVertexBufferDescriptor vbDesc(
"", semantic, MHWRender::MGeometry::kFloat, 2);
buffer = new MHWRender::MVertexBuffer(vbDesc);
_meshSharedData->_primvarInfo[token]->_buffer.reset(buffer);
}
if (buffer) {
bufferData = _meshSharedData->_numVertices > 0
? buffer->acquire(_meshSharedData->_numVertices, true)
: nullptr;
if (bufferData) {
_FillPrimvarData(
static_cast<GfVec2f*>(bufferData),
_meshSharedData->_numVertices,
0,
_meshSharedData->_renderingToSceneFaceVtxIds,
_rprimId,
_meshSharedData->_topology,
token,
value.UncheckedGet<VtVec2fArray>(),
interp);
}
}
} else if (value.IsHolding<VtVec3fArray>()) {
if (!buffer) {
const MHWRender::MVertexBufferDescriptor vbDesc(
"", semantic, MHWRender::MGeometry::kFloat, 3);
buffer = new MHWRender::MVertexBuffer(vbDesc);
_meshSharedData->_primvarInfo[token]->_buffer.reset(buffer);
}
if (buffer) {
bufferData = _meshSharedData->_numVertices > 0
? buffer->acquire(_meshSharedData->_numVertices, true)
: nullptr;
if (bufferData) {
_FillPrimvarData(
static_cast<GfVec3f*>(bufferData),
_meshSharedData->_numVertices,
0,
_meshSharedData->_renderingToSceneFaceVtxIds,
_rprimId,
_meshSharedData->_topology,
token,
value.UncheckedGet<VtVec3fArray>(),
interp);
}
}
} else if (value.IsHolding<VtVec4fArray>()) {
if (!buffer) {
const MHWRender::MVertexBufferDescriptor vbDesc(
"", semantic, MHWRender::MGeometry::kFloat, 4);
buffer = new MHWRender::MVertexBuffer(vbDesc);
_meshSharedData->_primvarInfo[token]->_buffer.reset(buffer);
}
if (buffer) {
bufferData = _meshSharedData->_numVertices > 0
? buffer->acquire(_meshSharedData->_numVertices, true)
: nullptr;
if (bufferData) {
_FillPrimvarData(
static_cast<GfVec4f*>(bufferData),
_meshSharedData->_numVertices,
0,
_meshSharedData->_renderingToSceneFaceVtxIds,
_rprimId,
_meshSharedData->_topology,
token,
value.UncheckedGet<VtVec4fArray>(),
interp);
}
}
} else if (value.IsHolding<VtIntArray>()) {
if (!buffer) {
const MHWRender::MVertexBufferDescriptor vbDesc(
"", semantic, MHWRender::MGeometry::kFloat, 1); // kInt32
buffer = new MHWRender::MVertexBuffer(vbDesc);
_meshSharedData->_primvarInfo[token]->_buffer.reset(buffer);
}
if (buffer) {
bufferData = _meshSharedData->_numVertices > 0
? buffer->acquire(_meshSharedData->_numVertices, true)
: nullptr;
if (bufferData) {
const VtIntArray& primvarData = value.UncheckedGet<VtIntArray>();
VtFloatArray convertedPrimvarData;
convertedPrimvarData.reserve(primvarData.size());
for (auto& source : primvarData) {
convertedPrimvarData.push_back(static_cast<float>(source));
}
_FillPrimvarData(
static_cast<float*>(bufferData),
_meshSharedData->_numVertices,
0,
_meshSharedData->_renderingToSceneFaceVtxIds,
_rprimId,
_meshSharedData->_topology,
token,
convertedPrimvarData,
interp);
}
}
} else {
TF_WARN("Unsupported primvar array");
}
_CommitMVertexBuffer(buffer, bufferData);
}
}
}
bool HdVP2Mesh::_PrimvarIsRequired(const TfToken& primvar) const
{
const TfTokenVector& allRequiredPrimvars = _meshSharedData->_allRequiredPrimvars;
TfTokenVector::const_iterator begin = allRequiredPrimvars.cbegin();
TfTokenVector::const_iterator end = allRequiredPrimvars.cend();
return (std::find(begin, end, primvar) != end);
}
void HdVP2Mesh::_ResetRenderingTopology()
{
_meshSharedData->_renderingTopology = HdMeshTopology();
RenderItemFunc setIndexBufferDirty = [](HdVP2DrawItem::RenderItemData& renderItemData) {
renderItemData._indexBufferValid = false;
};
_ForEachRenderItem(_reprs, setIndexBufferDirty);
}
//! \brief Synchronize VP2 state with scene delegate state based on dirty bits and representation
void HdVP2Mesh::Sync(
HdSceneDelegate* delegate,
HdRenderParam* renderParam,
HdDirtyBits* dirtyBits,
TfToken const& reprToken)
{
if (!_SyncCommon(*this, delegate, renderParam, dirtyBits, _GetRepr(reprToken), reprToken)) {
return;
}
MProfilingScope profilingScope(
HdVP2RenderDelegate::sProfilerCategory,
MProfiler::kColorC_L2,
_rprimId.asChar(),
"HdVP2Mesh::Sync");
const SdfPath& id = GetId();
HdRenderIndex& renderIndex = delegate->GetRenderIndex();
#if !defined(USD_IMAGING_API_VERSION) || USD_IMAGING_API_VERSION < 18
auto* const param = static_cast<HdVP2RenderParam*>(_delegate->GetRenderParam());
ProxyRenderDelegate& drawScene = param->GetDrawScene();
UsdImagingDelegate* usdImagingDelegate = drawScene.GetUsdImagingDelegate();
#endif
// Geom subsets are accessed through the mesh topology. I need to know about
// the additional materialIds that get bound by geom subsets before we build the
// _primvaInfo. So the very first thing I need to do is grab the topology.
if (HdChangeTracker::IsTopologyDirty(*dirtyBits, id)) {
// unsubscribe from material TopoChanged updates from the old geom subset materials
for (const auto& geomSubset : _meshSharedData->_topology.GetGeomSubsets()) {
if (!geomSubset.materialId.IsEmpty()) {
const SdfPath materialId
#if !defined(USD_IMAGING_API_VERSION) || USD_IMAGING_API_VERSION < 18
= usdImagingDelegate->ConvertCachePathToIndexPath(geomSubset.materialId);
#else
= geomSubset.materialId;
#endif
HdVP2Material* material = static_cast<HdVP2Material*>(
renderIndex.GetSprim(HdPrimTypeTokens->material, materialId));
if (material) {
material->UnsubscribeFromMaterialUpdates(id);
}
}
}
{
MProfilingScope profilingScope(
HdVP2RenderDelegate::sProfilerCategory,
MProfiler::kColorC_L2,
_rprimId.asChar(),
"HdVP2Mesh::GetMeshTopology");
HdMeshTopology newTopology = GetMeshTopology(delegate);
// Test to see if the topology actually changed. If not, we don't have to do anything!
// Don't test IsTopologyDirty anywhere below this because it is not accurate. Instead
// using the _indexBufferValid flag on render item data.
if (!(newTopology == _meshSharedData->_topology)) {
_meshSharedData->_topology = newTopology;
_meshSharedData->_adjacency.reset();
_ResetRenderingTopology();
}
}
// subscribe to material TopoChanged updates from the new geom subset materials
for (const auto& geomSubset : _meshSharedData->_topology.GetGeomSubsets()) {
if (!geomSubset.materialId.IsEmpty()) {
const SdfPath materialId
#if !defined(USD_IMAGING_API_VERSION) || USD_IMAGING_API_VERSION < 18
= usdImagingDelegate->ConvertCachePathToIndexPath(geomSubset.materialId);
#else
= geomSubset.materialId;
#endif
HdVP2Material* material = static_cast<HdVP2Material*>(
renderIndex.GetSprim(HdPrimTypeTokens->material, materialId));
if (material) {
material->SubscribeForMaterialUpdates(id);
}
}
}
}
if (*dirtyBits & HdChangeTracker::DirtyMaterialId) {
const SdfPath materialId = _GetUpdatedMaterialId(this, delegate);
#if HD_API_VERSION < 37
_SetMaterialId(renderIndex.GetChangeTracker(), materialId);
#else
SetMaterialId(materialId);
#endif
}
#if defined(HD_API_VERSION) && HD_API_VERSION >= 36
// Update our instance topology if necessary.
_UpdateInstancer(delegate, dirtyBits);
#endif
// if the instancer is dirty then any streams with instance interpolation need to be updated.
// We don't necessarily know if there ARE any streams with instance interpolation, so call
// _UpdatePrimvarSources to check.
bool instancerDirty
= ((*dirtyBits
& (HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyInstancer
| HdChangeTracker::DirtyInstanceIndex))
!= 0);
if (HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->points)
|| HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->normals)
|| HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->primvar) || instancerDirty) {
auto addRequiredPrimvars = [&](const SdfPath& materialId) {
TfTokenVector requiredPrimvars;
if (!_GetMaterialPrimvars(renderIndex, materialId, requiredPrimvars)
|| ((reprToken == HdVP2ReprTokens->smoothHullUntextured)
&& (MGlobal::optionVarIntValue(
MayaUsdOptionVars->ShowDisplayColorTextureOff.GetText())
!= 0))) {
// if user selected present display color in untextured mode, use fallback shader as
// well
requiredPrimvars = sFallbackShaderPrimvars;
}
for (const auto& requiredPrimvar : requiredPrimvars) {
if (!_PrimvarIsRequired(requiredPrimvar)) {
_meshSharedData->_allRequiredPrimvars.push_back(requiredPrimvar);
}
}
};
// there is a chance that the geom subsets cover all the faces of the
// mesh and that the overall material id is unused. I don't figure that
// out until much later, so for now just accept that we might pull unnecessary
// primvars required by the overall material but not by any of the geom subset
// materials.
addRequiredPrimvars(GetMaterialId());
for (const auto& geomSubset : _meshSharedData->_topology.GetGeomSubsets()) {
addRequiredPrimvars(
#if !defined(USD_IMAGING_API_VERSION) || USD_IMAGING_API_VERSION < 18
usdImagingDelegate->ConvertCachePathToIndexPath(geomSubset.materialId)
#else
geomSubset.materialId
#endif
);
}
// also, we always require points
if (!_PrimvarIsRequired(HdTokens->points))
_meshSharedData->_allRequiredPrimvars.push_back(HdTokens->points);
_UpdatePrimvarSources(delegate, *dirtyBits, _meshSharedData->_allRequiredPrimvars);
// update the type of vertex layout to use (shared/unshared)
bool requireUnsharedVertexLayout
= _IsUnsharedVertexLayoutRequired(_meshSharedData->_primvarInfo);
if (_meshSharedData->_isVertexLayoutUnshared != requireUnsharedVertexLayout) {
_meshSharedData->_isVertexLayoutUnshared = requireUnsharedVertexLayout;
_ResetRenderingTopology();
}
}
if (_meshSharedData->_renderingTopology == HdMeshTopology()) {
MProfilingScope profilingScope(
HdVP2RenderDelegate::sProfilerCategory,
MProfiler::kColorC_L2,
_rprimId.asChar(),
"HdVP2Mesh Create Rendering Topology");
const HdMeshTopology& topology = _meshSharedData->_topology;
const VtIntArray& faceVertexIndices = topology.GetFaceVertexIndices();
const size_t numFaceVertexIndices = faceVertexIndices.size();
VtIntArray newFaceVertexIndices;
newFaceVertexIndices.resize(numFaceVertexIndices);
if (_meshSharedData->_isVertexLayoutUnshared) {
_meshSharedData->_numVertices = numFaceVertexIndices;
_meshSharedData->_renderingToSceneFaceVtxIds = faceVertexIndices;
_meshSharedData->_sceneToRenderingFaceVtxIds.clear();
_meshSharedData->_sceneToRenderingFaceVtxIds.resize(topology.GetNumPoints(), -1);
for (size_t i = 0; i < numFaceVertexIndices; i++) {
const int sceneFaceVtxId = faceVertexIndices[i];
// Scene index is actually greater than anticipated, increase the buffer size.
if (size_t(sceneFaceVtxId) >= _meshSharedData->_sceneToRenderingFaceVtxIds.size()) {
_meshSharedData->_sceneToRenderingFaceVtxIds.resize(sceneFaceVtxId + 1, -1);
}
_meshSharedData->_sceneToRenderingFaceVtxIds[sceneFaceVtxId]
= i; // could check if the existing value is -1, but it doesn't matter.
// we just need to map to a vertex in the position buffer that has
// the correct value.
}
// Fill with sequentially increasing values, starting from 0. The new
// face vertex indices will be used to populate index data for unshared
// vertex layout. Note that _FillPrimvarData assumes this sequence to
// be used for face-varying primvars and saves lookup and remapping