-
Notifications
You must be signed in to change notification settings - Fork 203
/
Copy pathlayerManager.cpp
1567 lines (1322 loc) · 52.7 KB
/
layerManager.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 "layerManager.h"
#include <mayaUsd/commands/abstractLayerEditorWindow.h>
#include <mayaUsd/listeners/notice.h>
#include <mayaUsd/listeners/proxyShapeNotice.h>
#include <mayaUsd/nodes/proxyShapeBase.h>
#include <mayaUsd/ufe/Utils.h>
#include <mayaUsd/undo/OpUndoItemMuting.h>
#include <mayaUsd/undo/OpUndoItems.h>
#include <mayaUsd/utils/util.h>
#include <mayaUsd/utils/utilFileSystem.h>
#include <mayaUsd/utils/utilSerialization.h>
#include <usdUfe/utils/layers.h>
#include <pxr/base/arch/env.h>
#include <pxr/base/tf/instantiateType.h>
#include <pxr/base/tf/weakBase.h>
#include <pxr/usd/ar/resolver.h>
#include <pxr/usd/sdf/textFileFormat.h>
#include <pxr/usd/usd/editTarget.h>
#include <pxr/usd/usd/usdFileFormat.h>
#include <pxr/usd/usd/usdaFileFormat.h>
#include <pxr/usd/usd/usdcFileFormat.h>
#include <pxr/usd/usdUtils/authoring.h>
#include <maya/MArrayDataBuilder.h>
#include <maya/MArrayDataHandle.h>
#include <maya/MDagPath.h>
#include <maya/MDagPathArray.h>
#include <maya/MDataBlock.h>
#include <maya/MDataHandle.h>
#include <maya/MFileIO.h>
#include <maya/MFnAttribute.h>
#include <maya/MFnCompoundAttribute.h>
#include <maya/MFnNumericAttribute.h>
#include <maya/MFnStringData.h>
#include <maya/MFnTypedAttribute.h>
#include <maya/MGlobal.h>
#include <maya/MItDag.h>
#include <maya/MItDependencyNodes.h>
#include <maya/MSceneMessage.h>
#include <ufe/globalSelection.h>
#include <ufe/observableSelection.h>
#include <ufe/selectionNotification.h>
#include <cstdio>
#include <iostream>
#include <set>
namespace {
static std::recursive_mutex findNodeMutex;
static MObjectHandle layerManagerHandle;
// Utility func to disconnect an array plug, and all it's element plugs, and all
// their child plugs.
// Not in Utils, because it's not generic - ie, doesn't handle general case
// where compound/array plugs may be nested arbitrarily deep...
MStatus disconnectCompoundArrayPlug(MPlug arrayPlug)
{
MStatus status;
MPlug elemPlug;
MPlug srcPlug;
MPlugArray destPlugs;
MDGModifier& dgmod = MayaUsd::MDGModifierUndoItem::create("Compound array plug disconnection");
auto disconnectPlug = [&](MPlug plug) -> MStatus {
MStatus status;
srcPlug = plug.source(&status);
if (!srcPlug.isNull()) {
dgmod.disconnect(srcPlug, plug);
}
destPlugs.clear();
plug.destinations(destPlugs, &status);
for (size_t i = 0; i < destPlugs.length(); ++i) {
dgmod.disconnect(plug, destPlugs[i]);
}
return status;
};
// Considered using numConnectedElements, but for arrays-of-compound attributes, not sure if
// this will also detect connections to a child-of-an-element... so just iterating through all
// plugs. Shouldn't be too many...
const size_t numElements = arrayPlug.evaluateNumElements();
// Iterate over all elements...
for (size_t elemI = 0; elemI < numElements; ++elemI) {
elemPlug = arrayPlug.elementByPhysicalIndex(elemI, &status);
// Disconnect the element compound attribute
disconnectPlug(elemPlug);
// ...then disconnect any children
if (elemPlug.numConnectedChildren() > 0) {
for (size_t childI = 0; childI < elemPlug.numChildren(); ++childI) {
disconnectPlug(elemPlug.child(childI));
}
}
}
return dgmod.doIt();
}
/// @brief Verify if the given node is from a reference.
static bool
isNodeFromDesiredOrigin(const MFnDependencyNode& node, MayaUsdProxyShapeBase* forProxyShape)
{
const bool proxyIsFromReference
= (forProxyShape && MFnDependencyNode(forProxyShape->thisMObject()).isFromReferencedFile());
return node.isFromReferencedFile() == proxyIsFromReference;
}
MayaUsd::LayerManager* findNode(MayaUsdProxyShapeBase* forProxyShape)
{
if (forProxyShape) {
if (MayaUsd::LayerManager* layerManager = forProxyShape->getLayerManager()) {
return layerManager;
}
}
// Check for cached layer manager before searching
MFnDependencyNode fn;
if (layerManagerHandle.isValid() && layerManagerHandle.isAlive()) {
MObject mobj { layerManagerHandle.object() };
if (!mobj.isNull()) {
fn.setObject(mobj);
return static_cast<MayaUsd::LayerManager*>(fn.userNode());
}
}
MItDependencyNodes iter(MFn::kPluginDependNode);
for (; !iter.isDone(); iter.next()) {
MObject mobj = iter.item();
fn.setObject(mobj);
if (fn.typeId() == MayaUsd::LayerManager::typeId) {
if (isNodeFromDesiredOrigin(fn, forProxyShape)) {
layerManagerHandle = mobj;
return static_cast<MayaUsd::LayerManager*>(fn.userNode());
}
}
}
return nullptr;
}
MayaUsd::LayerManager* findOrCreateNode(MayaUsdProxyShapeBase* forProxyShape)
{
MayaUsd::LayerManager* lm = findNode(forProxyShape);
if (!lm) {
MDGModifier& modifier = MayaUsd::MDGModifierUndoItem::create("Node find or creation");
MObject manager = modifier.createNode(MayaUsd::LayerManager::typeId);
modifier.doIt();
lm = static_cast<MayaUsd::LayerManager*>(MFnDependencyNode(manager).userNode());
}
return lm;
}
void convertAnonymousLayersRecursive(
SdfLayerRefPtr layer,
const std::string& basename,
UsdStageRefPtr stage)
{
auto currentTarget = stage->GetEditTarget().GetLayer();
std::vector<std::string> sublayers = layer->GetSubLayerPaths();
for (size_t i = 0, n = sublayers.size(); i < n; ++i) {
SdfLayerRefPtr subL = layer->Find(sublayers[i]);
if (subL) {
convertAnonymousLayersRecursive(subL, basename, stage);
if (subL->IsAnonymous()) {
MayaUsd::utils::LayerParent subLayerParent;
subLayerParent._layerParent = layer;
subLayerParent._proxyPath = basename;
SdfLayerRefPtr newLayer
= MayaUsd::utils::saveAnonymousLayer(stage, subL, subLayerParent, basename);
if (subL == currentTarget) {
stage->SetEditTarget(newLayer);
}
}
}
}
}
bool isCrashing()
{
#ifdef MAYA_HAS_CRASH_DETECTION
return MGlobal::isInCrashHandler();
#else
return false;
#endif
}
bool isCopyingSceneNodes()
{
// When Maya is copy nodes, it exports them and sets this environment
// variable during the export to let exporters know it is cutting or
// copying nodes in a temporary Maya scene file.
return PXR_NS::ArchHasEnv("MAYA_CUT_COPY_EXPORT");
}
constexpr auto kSaveOptionUICmd = "usdFileSaveOptions(true);";
} // namespace
namespace MAYAUSD_NS_DEF {
class LayerDatabase : public TfWeakBase
{
public:
LayerDatabase();
~LayerDatabase();
static LayerDatabase& instance();
static void setBatchSaveDelegate(BatchSaveDelegate delegate);
static void prepareForSaveCheck(bool*, void*);
static void cleanupForSave(void*);
static void prepareForExportCheck(bool*, void*);
static void prepareForWriteCheck(bool*, bool);
static void cleanupForWrite();
static void loadLayersPostRead(MayaUsdProxyShapeBase* forProxyShape);
static void cleanUpNewScene(void*);
static void clearManagerNode(MayaUsd::LayerManager* lm);
static void removeManagerNode(
MayaUsd::LayerManager* lm = nullptr,
MayaUsdProxyShapeBase* forProxyShape = nullptr);
bool getProxiesToSave(bool isExport, bool* hasAnyProxy);
bool saveInteractionRequired();
bool supportedNodeType(MTypeId type);
void addSupportForNodeType(MTypeId type);
void removeSupportForNodeType(MTypeId type);
bool remapSubLayerPaths(SdfLayerHandle parentLayer);
bool addLayer(SdfLayerRefPtr layer, const std::string& identifier = std::string());
bool removeLayer(SdfLayerRefPtr layer);
void removeAllLayers();
void setSelectedStage(const std::string& stage);
std::string getSelectedStage() const;
bool saveLayerManagerSelectedStage();
bool loadLayerManagerSelectedStage(MayaUsd::LayerManager& layerManager);
SdfLayerHandle findLayer(std::string identifier) const;
LayerManager::LayerNameMap getLayerNameMap() const;
static bool isSaving() { return _isSavingMayaFile; }
private:
void registerCallbacks();
void unregisterCallbacks();
void _addLayer(SdfLayerRefPtr layer, const std::string& identifier);
void onStageSet(const MayaUsdProxyStageSetNotice& notice);
bool saveUsd(bool isExport);
BatchSaveResult saveUsdToMayaFile();
BatchSaveResult saveUsdToUsdFiles();
void convertAnonymousLayers(
MayaUsdProxyShapeBase* pShape,
const MObject& proxyNode,
UsdStageRefPtr stage);
void saveUsdLayerToMayaFile(SdfLayerRefPtr layer, bool asAnonymous);
void clearProxies();
bool hasDirtyLayer() const;
void refreshProxiesToSave();
void updateLayerManagers();
std::map<std::string, SdfLayerRefPtr> _idToLayer;
TfNotice::Key _onStageSetKey;
std::set<unsigned int> _supportedTypes;
std::vector<StageSavingInfo> _proxiesToSave;
std::vector<StageSavingInfo> _internalProxiesToSave;
std::string _selectedStage;
static MCallbackId preSaveCallbackId;
static MCallbackId postSaveCallbackId;
static MCallbackId preExportCallbackId;
static MCallbackId postExportCallbackId;
static MCallbackId postNewCallbackId;
static MCallbackId preOpenCallbackId;
static MayaUsd::BatchSaveDelegate _batchSaveDelegate;
static bool _isSavingMayaFile;
};
MCallbackId LayerDatabase::preSaveCallbackId = 0;
MCallbackId LayerDatabase::postSaveCallbackId = 0;
MCallbackId LayerDatabase::preExportCallbackId = 0;
MCallbackId LayerDatabase::postExportCallbackId = 0;
MCallbackId LayerDatabase::postNewCallbackId = 0;
MCallbackId LayerDatabase::preOpenCallbackId = 0;
MayaUsd::BatchSaveDelegate LayerDatabase::_batchSaveDelegate = nullptr;
bool LayerDatabase::_isSavingMayaFile = false;
/*static*/
LayerDatabase& LayerDatabase::instance()
{
static LayerDatabase sLayerDB;
sLayerDB.registerCallbacks();
return sLayerDB;
}
LayerDatabase::LayerDatabase()
{
TfWeakPtr<LayerDatabase> me(this);
_onStageSetKey = TfNotice::Register(me, &LayerDatabase::onStageSet);
}
LayerDatabase::~LayerDatabase()
{
if (_onStageSetKey.IsValid()) {
TfNotice::Revoke(_onStageSetKey);
}
unregisterCallbacks();
}
void LayerDatabase::registerCallbacks()
{
if (0 == preSaveCallbackId) {
preSaveCallbackId = MSceneMessage::addCallback(
MSceneMessage::kBeforeSaveCheck, LayerDatabase::prepareForSaveCheck);
postSaveCallbackId
= MSceneMessage::addCallback(MSceneMessage::kAfterSave, LayerDatabase::cleanupForSave);
preExportCallbackId = MSceneMessage::addCallback(
MSceneMessage::kBeforeExportCheck, LayerDatabase::prepareForExportCheck);
postNewCallbackId
= MSceneMessage::addCallback(MSceneMessage::kAfterNew, LayerDatabase::cleanUpNewScene);
preOpenCallbackId = MSceneMessage::addCallback(
MSceneMessage::kBeforeOpen, LayerDatabase::cleanUpNewScene);
}
}
void LayerDatabase::unregisterCallbacks()
{
if (0 != preSaveCallbackId) {
MSceneMessage::removeCallback(preSaveCallbackId);
MSceneMessage::removeCallback(postSaveCallbackId);
MSceneMessage::removeCallback(preExportCallbackId);
MSceneMessage::removeCallback(postExportCallbackId);
MSceneMessage::removeCallback(postNewCallbackId);
MSceneMessage::removeCallback(preOpenCallbackId);
preSaveCallbackId = 0;
postSaveCallbackId = 0;
preExportCallbackId = 0;
postExportCallbackId = 0;
postNewCallbackId = 0;
preOpenCallbackId = 0;
}
}
void LayerDatabase::addSupportForNodeType(MTypeId type)
{
if (_supportedTypes.find(type.id()) == _supportedTypes.end()) {
_supportedTypes.insert(type.id());
}
}
void LayerDatabase::removeSupportForNodeType(MTypeId type) { _supportedTypes.erase(type.id()); }
bool LayerDatabase::supportedNodeType(MTypeId type)
{
return (_supportedTypes.find(type.id()) != _supportedTypes.end());
}
void LayerDatabase::onStageSet(const MayaUsdProxyStageSetNotice& notice)
{
const MayaUsdProxyShapeBase& psb = notice.GetProxyShape();
UsdStageRefPtr stage = psb.getUsdStage();
if (stage) {
removeLayer(stage->GetRootLayer());
removeLayer(stage->GetSessionLayer());
}
}
void LayerDatabase::setBatchSaveDelegate(BatchSaveDelegate delegate)
{
_batchSaveDelegate = delegate;
}
void LayerDatabase::prepareForSaveCheck(bool* retCode, void*)
{
// This is called during a Maya notification callback, so no undo supported.
OpUndoItemMuting muting;
prepareForWriteCheck(retCode, false);
}
void LayerDatabase::cleanupForSave(void*)
{
// This is call by Maya when the Maya save has finished.
cleanupForWrite();
}
namespace {
MString formatProxyShapeWarning(const char* message, const StageSavingInfo& info)
{
MString text;
text.format(message, info.dagPath.partialPathName());
return text;
}
// Handle a dirty stage during export as USD.
void handleDirtyStageDuringExport(const StageSavingInfo& info)
{
if (!info.stage)
return;
const UsdUfe::StageDirtyState dirty = UsdUfe::isStageDirty(*info.stage);
if (dirty == UsdUfe::StageDirtyState::kClean)
return;
if (info.stage->GetRootLayer()->IsAnonymous()) {
MGlobal::displayWarning(formatProxyShapeWarning(
"A reference to ^1s could not be exported because the root layer is anonymous."
" To include this stage, you will need to save the anonymous root layer to disk"
" and re-export the scene.",
info));
return;
}
if (dirty == UsdUfe::StageDirtyState::kDirtyRootLayers) {
MGlobal::displayWarning(formatProxyShapeWarning(
"^1s may not appear in the exported scene exactly as it appears in the scene"
" because there are layers that have not been saved to disk. Saving those"
" layers in the layer editor may be needed.",
info));
return;
}
if (dirty == UsdUfe::StageDirtyState::kDirtySessionLayers) {
MGlobal::displayWarning(formatProxyShapeWarning(
"^1s may not appear in the exported scene exactly as it appears in the scene"
" because there are opinions in the session layer which are not propagated"
" into the USD files.",
info));
return;
}
}
} // namespace
void LayerDatabase::prepareForExportCheck(bool* retCode, void*)
{
*retCode = true;
// This is called during a Maya notification callback, so no undo supported.
OpUndoItemMuting muting;
auto& layerDB = LayerDatabase::instance();
bool hasAnyProxy = false;
const bool isExport = true;
if (!layerDB.getProxiesToSave(isExport, &hasAnyProxy))
return;
for (const StageSavingInfo& info : layerDB._proxiesToSave)
handleDirtyStageDuringExport(info);
for (const auto& info : layerDB._internalProxiesToSave)
handleDirtyStageDuringExport(info);
layerDB.clearProxies();
}
void LayerDatabase::prepareForWriteCheck(bool* retCode, bool isExport)
{
_isSavingMayaFile = true;
cleanUpNewScene(nullptr);
LayerDatabase::instance().saveLayerManagerSelectedStage();
bool hasAnyProxy = false;
if (LayerDatabase::instance().getProxiesToSave(isExport, &hasAnyProxy)) {
int dialogResult = true;
if (!isCopyingSceneNodes()) {
if (MGlobal::kInteractive == MGlobal::mayaState() && !isCrashing()
&& LayerDatabase::instance().saveInteractionRequired()) {
MGlobal::executeCommand(kSaveOptionUICmd, dialogResult);
}
}
if (dialogResult) {
dialogResult = LayerDatabase::instance().saveUsd(isExport);
}
*retCode = dialogResult;
} else {
*retCode = true;
}
// Note: for now we only save USD change made in stage in the main
// Maya scene. We don't save changes made to stages in Maya
// references.
if (!hasAnyProxy)
removeManagerNode(nullptr, nullptr);
}
void LayerDatabase::cleanupForWrite()
{
// Reset the flag that records a Maya scene save is in progress.
// Used to avoid deleting the layer manager node mid-save if some
// other code happens to access the layers.
_isSavingMayaFile = false;
}
void LayerDatabase::clearProxies()
{
_proxiesToSave.clear();
_internalProxiesToSave.clear();
}
void LayerDatabase::updateLayerManagers()
{
auto creator = MayaUsd::AbstractLayerEditorCreator::instance();
if (!creator)
return;
for (const std::string& panelName : creator->getAllPanelNames()) {
AbstractLayerEditorWindow* window = creator->getWindow(panelName.c_str());
if (!window)
continue;
window->updateLayerModel();
}
}
bool LayerDatabase::hasDirtyLayer() const
{
for (const auto& info : _proxiesToSave) {
const UsdUfe::StageDirtyState dirty = UsdUfe::isStageDirty(*info.stage);
if (dirty != UsdUfe::StageDirtyState::kClean) {
return true;
}
}
for (const auto& info : _internalProxiesToSave) {
const UsdUfe::StageDirtyState dirty = UsdUfe::isStageDirty(*info.stage);
if (dirty != UsdUfe::StageDirtyState::kClean) {
return true;
}
}
return false;
}
bool LayerDatabase::getProxiesToSave(bool isExport, bool* hasAnyProxy)
{
if (hasAnyProxy)
*hasAnyProxy = false;
bool checkSelection = isExport && (MFileIO::kExportTypeSelected == MFileIO::exportType());
const Ufe::GlobalSelection::Ptr& ufeSelection = Ufe::GlobalSelection::get();
clearProxies();
MFnDependencyNode fn;
MItDependencyNodes iter(MFn::kPluginDependNode);
for (; !iter.isDone(); iter.next()) {
MObject mobj = iter.item();
fn.setObject(mobj);
if (!fn.isFromReferencedFile() && supportedNodeType(fn.typeId())) {
if (hasAnyProxy)
*hasAnyProxy = true;
MayaUsdProxyShapeBase* pShape = static_cast<MayaUsdProxyShapeBase*>(fn.userNode());
UsdStageRefPtr stage = pShape ? pShape->getUsdStage() : nullptr;
if (!stage) {
continue;
}
auto stagePath = MayaUsd::ufe::stagePath(stage);
if (!checkSelection
|| (ufeSelection->contains(stagePath)
|| ufeSelection->containsAncestor(stagePath))) {
// Should we save the stage?
// 1) Shareable Stage : In this case we case we only care about saving if the
// input is not an incoming connection, since in that case the node that "owns" the
// stage (upstream node) is responsible for saving. For example if you have multiple
// proxy shapes daisy chained one's out_stage feeding the other's in_stage. In that
// case only one proxy is responsible for saving (the first one).
// 2) Unshareable Stage: Similarly but in this case if the stage is unshared, it
// means we are responsible for saving the root layer (and stubs for the sublayers
// so we can put them back in the same spot). So doesn't matter if its incoming or
// not, we need to save.
if (!pShape->isShareableStage() || !pShape->isStageIncoming()) {
SdfLayerHandleVector allLayers = stage->GetUsedLayers(true);
for (auto layer : allLayers) {
if (TF_VERIFY(layer) && layer->IsDirty()) {
StageSavingInfo info;
MDagPath::getAPathTo(mobj, info.dagPath);
info.stage = stage;
info.shareable = pShape->isShareableStage();
info.isIncoming = pShape->isStageIncoming();
// Where should we save the stage?
// We handle unshared composition internally in Maya USD file
// The reason we have this distinction now is that some Layers are
// special case layers that should be saved to the maya file only.
// There are two examples currently of this, the session layer and
// unshared root layer. So since we have batchSave and a delegate which
// handles saving externally, we need to manage some proxies ourselves
// and control where they save
if (pShape->isShareableStage()) {
_proxiesToSave.emplace_back(std::move(info));
} else {
_internalProxiesToSave.emplace_back(std::move(info));
}
break;
}
}
}
}
}
}
return ((_proxiesToSave.size() + _internalProxiesToSave.size()) > 0);
}
bool LayerDatabase::saveInteractionRequired() { return _proxiesToSave.size() > 0; }
static void refreshSavingInfo(StageSavingInfo& info)
{
MFnDependencyNode fn;
MObject mobj = info.dagPath.node();
fn.setObject(mobj);
if (!fn.isFromReferencedFile() && LayerDatabase::instance().supportedNodeType(fn.typeId())) {
MayaUsdProxyShapeBase* pShape = static_cast<MayaUsdProxyShapeBase*>(fn.userNode());
info.stage = pShape ? pShape->getUsdStage() : nullptr;
}
}
void LayerDatabase::refreshProxiesToSave()
{
for (StageSavingInfo& info : _proxiesToSave) {
refreshSavingInfo(info);
}
for (StageSavingInfo& info : _internalProxiesToSave) {
refreshSavingInfo(info);
}
}
void LayerDatabase::setSelectedStage(const std::string& stage)
{
if (_selectedStage == stage)
return;
_selectedStage = stage;
// Mark the scene as modified.
MGlobal::executeCommand("file -modified 1");
}
std::string LayerDatabase::getSelectedStage() const { return _selectedStage; }
bool LayerDatabase::saveLayerManagerSelectedStage()
{
// Note: for now we only save USD change made in stage in the main
// Maya scene. We don't save changes made to stages in Maya
// references.
MayaUsd::LayerManager* lm = findOrCreateNode(nullptr);
if (!lm)
return false;
MStatus status;
MDataBlock dataBlock = lm->_forceCache();
MDataHandle selectedStageHandle = dataBlock.outputValue(lm->selectedStage, &status);
if (!status)
return false;
// Note: when empty, we clear the the selected stage attribute so that the
// attribute does not get written to the scene, which improve backward
// compatibility.
const std::string stageName = getSelectedStage();
if (stageName.size() > 0)
selectedStageHandle.setString(stageName.c_str());
else
selectedStageHandle.setMObject(MObject::kNullObj);
selectedStageHandle.setClean();
dataBlock.setClean(lm->selectedStage);
return true;
}
bool LayerDatabase::loadLayerManagerSelectedStage(MayaUsd::LayerManager& layerManager)
{
MStatus status;
MPlug selectedStagePlug(layerManager.thisMObject(), layerManager.selectedStage);
setSelectedStage(selectedStagePlug.asString(MDGContext::fsNormal, &status).asChar());
return status;
}
bool LayerDatabase::saveUsd(bool isExport)
{
BatchSaveResult result = MayaUsd::kNotHandled;
auto opt = MayaUsd::utils::serializeUsdEditsLocationOption();
if (MayaUsd::utils::kIgnoreUSDEdits != opt) {
// When Maya is crashing or copying/cutting scene nodes, we don't want to
// save the the USD file to avoid overwriting them with possibly unwanted
// data. Instead, we will save the USD data inside the temporary crash recovery Maya file.
if (isCrashing() || isCopyingSceneNodes()) {
result = kPartiallyCompleted;
opt = MayaUsd::utils::kSaveToMayaSceneFile;
} else if (_batchSaveDelegate && _proxiesToSave.size() > 0) {
result = _batchSaveDelegate(_proxiesToSave, isExport);
}
// kAbort: we should abort and return false, which Maya will take as
// an indication to abort the file operation.
//
// kCompleted: the delegate has completely handled the save operation,
// we should return true and do nothing else here.
//
// kPartiallyCompleted: the delegate has partialy handled the saving of
// files. In this case we will have to iterate over the scene again
// in order to find any unsaved stages that are still dirty.
if (result == kAbort) {
return false;
} else if (result == kCompleted && _internalProxiesToSave.size() == 0) {
return true;
} else if (result == kPartiallyCompleted && !hasDirtyLayer()) {
return true;
}
// After the potentially partial save, we need to refresh the stages
// to be saved because the saving might have modified the proxy shape
// attributes and we need to re-evaluate these nodes so that the stages
// are re-created with the new attribute values if needed.
refreshProxiesToSave();
if (MayaUsd::utils::kSaveToUSDFiles == opt) {
result = saveUsdToUsdFiles();
} else {
result = saveUsdToMayaFile();
}
} else {
result = MayaUsd::kCompleted;
}
clearProxies();
updateLayerManagers();
return (MayaUsd::kCompleted == result);
}
MStatus addLayerToBuilder(
MayaUsd::LayerManager* lm,
MArrayDataBuilder& builder,
SdfLayerHandle layer,
bool isAnon,
bool stubOnly = false,
bool exportOnlyIfDirty = false)
{
if (!lm)
return MS::kFailure;
MStatus status = MS::kSuccess;
MDataHandle layersElemHandle = builder.addLast(&status);
CHECK_MSTATUS_AND_RETURN_IT(status);
MDataHandle idHandle = layersElemHandle.child(lm->identifier);
MDataHandle fileFormatIdHandle = layersElemHandle.child(lm->fileFormatId);
MDataHandle serializedHandle = layersElemHandle.child(lm->serialized);
MDataHandle anonHandle = layersElemHandle.child(lm->anonymous);
idHandle.setString(UsdMayaUtil::convert(layer->GetIdentifier()));
anonHandle.setBool(isAnon);
auto fileFormatIdToken = layer->GetFileFormat()->GetFormatId();
fileFormatIdHandle.setString(UsdMayaUtil::convert(fileFormatIdToken.GetString()));
std::string temp;
if (!stubOnly && ((exportOnlyIfDirty && layer->IsDirty()) || !exportOnlyIfDirty)) {
if (!layer->ExportToString(&temp)) {
status = MS::kFailure;
}
}
serializedHandle.setString(UsdMayaUtil::convert(temp));
return status;
}
MStatus setValueForAttr(const MObject& node, const MObject& attribute, const std::string& value)
{
MString val = UsdMayaUtil::convert(value);
MPlug attrPlug(node, attribute);
return attrPlug.setValue(val);
}
struct SaveStageToMayaResult
{
bool _saveSuceeded { false };
bool _stageHasDirtyLayers { false };
};
template <typename T, typename IgnoreLayerFn>
void saveLayersToMayaFile(
const T&& allLayers,
const IgnoreLayerFn&& ignoreLayerFn,
MayaUsd::LayerManager* lm,
MArrayDataBuilder& builder,
MayaUsdProxyShapeBase& proxyShape,
SaveStageToMayaResult& result)
{
for (auto layer : allLayers) {
if (ignoreLayerFn(layer)) {
continue;
}
addLayerToBuilder(
lm,
builder,
layer,
layer->IsAnonymous(),
proxyShape.isIncomingLayer(layer->GetIdentifier()),
true);
if (layer->IsDirty()) {
result._stageHasDirtyLayers = true;
}
}
}
SaveStageToMayaResult saveStageToMayaFile(
MayaUsd::LayerManager* lm,
MArrayDataBuilder& builder,
const MObject& proxyNode,
UsdStageRefPtr stage)
{
SaveStageToMayaResult result;
if (!lm) {
return result;
}
const MFnDependencyNode depNodeFn(proxyNode);
MayaUsdProxyShapeBase* pShape = static_cast<MayaUsdProxyShapeBase*>(depNodeFn.userNode());
if (!pShape)
return result;
pShape->setLayerManager(nullptr);
std::unordered_set<std::string> localLayerIds;
// Save session layer and its sublayers
saveLayersToMayaFile(
UsdUfe::getAllSublayerRefs(stage->GetSessionLayer(), true),
[&localLayerIds](const auto& layer) {
localLayerIds.emplace(layer->GetIdentifier());
return false;
},
lm,
builder,
*pShape,
result);
// Save root layer and its sublayers
saveLayersToMayaFile(
UsdUfe::getAllSublayerRefs(stage->GetRootLayer(), true),
[&localLayerIds](const auto& layer) {
localLayerIds.emplace(layer->GetIdentifier());
return false;
},
lm,
builder,
*pShape,
result);
// Save non local layers (reference layers and sub layers in reference layers),
// skip those have been saved previously from local stack
saveLayersToMayaFile(
stage->GetUsedLayers(true),
[&localLayerIds](const auto& layer) {
return TF_VERIFY(layer)
&& localLayerIds.find(layer->GetIdentifier()) != localLayerIds.cend();
},
lm,
builder,
*pShape,
result);
if (result._stageHasDirtyLayers) {
setValueForAttr(
proxyNode,
MayaUsdProxyShapeBase::sessionLayerNameAttr,
stage->GetSessionLayer()->GetIdentifier());
setValueForAttr(
proxyNode,
MayaUsdProxyShapeBase::rootLayerNameAttr,
stage->GetRootLayer()->GetIdentifier());
}
pShape->setLayerManager(lm);
result._saveSuceeded = true;
return result;
}
SaveStageToMayaResult saveStageToMayaFile(const MObject& proxyNode, UsdStageRefPtr stage)
{
// Note: for now we only save USD change made in stage in the main
// Maya scene. We don't save changes made to stages in Maya
// references.
SaveStageToMayaResult result;
MayaUsd::LayerManager* lm = findOrCreateNode(nullptr);
if (!lm)
return result;
MStatus status;
MDataBlock dataBlock = lm->_forceCache();
MArrayDataHandle layersHandle = dataBlock.outputArrayValue(lm->layers, &status);
MArrayDataBuilder builder(&dataBlock, lm->layers, 1 /*maybe nb stages?*/, &status);
result = saveStageToMayaFile(lm, builder, proxyNode, stage);
layersHandle.set(builder);
layersHandle.setAllClean();
dataBlock.setClean(lm->layers);
return result;
}
BatchSaveResult LayerDatabase::saveUsdToMayaFile()
{
// Note: for now we only save USD change made in stage in the main
// Maya scene. We don't save changes made to stages in Maya
// references.
MayaUsd::LayerManager* lm = findOrCreateNode(nullptr);
if (!lm) {
return MayaUsd::kNotHandled;
}
MStatus status;
MDataBlock dataBlock = lm->_forceCache();
MArrayDataHandle layersHandle = dataBlock.outputArrayValue(lm->layers, &status);
MArrayDataBuilder builder(&dataBlock, lm->layers, 1 /*maybe nb stages?*/, &status);
bool atLeastOneDirty = false;
MFnDependencyNode fn;
for (size_t i = 0; i < _proxiesToSave.size() + _internalProxiesToSave.size(); i++) {
const StageSavingInfo& info = i < _proxiesToSave.size()
? _proxiesToSave[i]
: _internalProxiesToSave[i - _proxiesToSave.size()];
MObject mobj = info.dagPath.node();
fn.setObject(mobj);
if (!fn.isFromReferencedFile()
&& LayerDatabase::instance().supportedNodeType(fn.typeId())) {
// Here if its unshared or not an incoming connection we save otherwise skip
if (!info.shareable || !info.isIncoming) {
auto result = saveStageToMayaFile(lm, builder, mobj, info.stage);
if (result._stageHasDirtyLayers) {
atLeastOneDirty = true;
}
layersHandle.set(builder);
}
}
}
clearProxies();
layersHandle.setAllClean();
dataBlock.setClean(lm->layers);
if (!atLeastOneDirty) {
MDGModifier& modifier = MDGModifierUndoItem::create("Save USD to Maya node deletion");
modifier.deleteNode(lm->thisMObject());
modifier.doIt();
}
return MayaUsd::kCompleted;
}
BatchSaveResult LayerDatabase::saveUsdToUsdFiles()
{
MFnDependencyNode fn;