-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMayaLiveLinkPlugin.cpp
1055 lines (831 loc) · 28.1 KB
/
MayaLiveLinkPlugin.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 1998-2019 Epic Games, Inc. All Rights Reserved.
// #include "Definitions.h"
#include "RequiredProgramMainCPPInclude.h"
#include "Misc/CommandLine.h"
#include "Async/TaskGraphInterfaces.h"
#include "Modules/ModuleManager.h"
#include "UObject/Object.h"
#include "Misc/ConfigCacheIni.h"
#include "LiveLinkProvider.h"
#include "LiveLinkRefSkeleton.h"
#include "LiveLinkTypes.h"
#include "Misc/OutputDevice.h"
DEFINE_LOG_CATEGORY_STATIC(LogBlankMayaPlugin, Log, All);
IMPLEMENT_APPLICATION(MayaLiveLinkPlugin, "MayaLiveLinkPlugin");
// Maya includes
#define DWORD BananaFritters
#include <maya/MObject.h>
#include <maya/MGlobal.h>
#include <maya/MFnPlugin.h>
#include <maya/MPxCommand.h> //command
#include <maya/MCommandResult.h> //command
#include <maya/MPxNode.h> //node
#include <maya/MFnNumericAttribute.h>
#include <maya/MCallbackIdArray.h>
#include <maya/MEventMessage.h>
#include <maya/MDagMessage.h>
#include <maya/MItDag.h>
#include <maya/MDagPath.h>
#include <maya/MFnDagNode.h>
#include <maya/MMatrix.h>
#include <maya/MTransformationMatrix.h>
#include <maya/MQuaternion.h>
#include <maya/MVector.h>
#include <maya/MFnTransform.h>
#include <maya/MFnIkJoint.h>
#include <maya/MFnCamera.h>
#include <maya/MEulerRotation.h>
#include <maya/MSelectionList.h>
#include <maya/MAnimControl.h>
#include <maya/MTimerMessage.h>
#include <maya/MDGMessage.h>
#include <maya/MNodeMessage.h>
#include <maya/MSceneMessage.h>
#include <maya/M3dView.h>
#include <maya/MUiMessage.h>
#include <maya/MSyntax.h>
#include <maya/MArgDatabase.h>
#undef DWORD
#define MCHECKERROR(STAT,MSG) \
if (!STAT) { \
perror(MSG); \
return MS::kFailure; \
}
#define MREPORTERROR(STAT,MSG) \
if (!STAT) { \
perror(MSG); \
}
class FLiveLinkStreamedSubjectManager;
TSharedPtr<ILiveLinkProvider> LiveLinkProvider;
TSharedPtr<FLiveLinkStreamedSubjectManager> LiveLinkStreamManager;
FDelegateHandle ConnectionStatusChangedHandle;
MCallbackIdArray myCallbackIds;
MSpace::Space G_TransformSpace = MSpace::kTransform;
bool bUEInitialized = false;
// Execute the python command to refresh our UI
void RefreshUI()
{
MGlobal::executeCommand("MayaLiveLinkRefreshUI");
}
void SetMatrixRow(double* Row, MVector Vec)
{
Row[0] = Vec.x;
Row[1] = Vec.y;
Row[2] = Vec.z;
}
double RadToDeg(double Rad)
{
const double E_PI = 3.1415926535897932384626433832795028841971693993751058209749445923078164062;
return (Rad*180.0) / E_PI;
}
MMatrix GetScale(const MFnIkJoint& Joint)
{
double Scale[3];
Joint.getScale(Scale);
MTransformationMatrix M;
M.setScale(Scale, G_TransformSpace);
return M.asMatrix();
}
MMatrix GetRotationOrientation(const MFnIkJoint& Joint, MTransformationMatrix::RotationOrder& RotOrder)
{
double ScaleOrientation[3];
Joint.getScaleOrientation(ScaleOrientation, RotOrder);
MTransformationMatrix M;
M.setRotation(ScaleOrientation, RotOrder);
return M.asMatrix();
}
MMatrix GetRotation(const MFnIkJoint& Joint, MTransformationMatrix::RotationOrder& RotOrder)
{
double Rotation[3];
Joint.getRotation(Rotation, RotOrder);
MTransformationMatrix M;
M.setRotation(Rotation, RotOrder);
return M.asMatrix();
}
MMatrix GetJointOrientation(const MFnIkJoint& Joint, MTransformationMatrix::RotationOrder& RotOrder)
{
double JointOrientation[3];
Joint.getOrientation(JointOrientation, RotOrder);
MTransformationMatrix M;
M.setRotation(JointOrientation, RotOrder);
return M.asMatrix();
}
MMatrix GetTranslation(const MFnIkJoint& Joint)
{
MVector Translation = Joint.getTranslation(G_TransformSpace);
MTransformationMatrix M;
M.setTranslation(Translation, G_TransformSpace);
return M.asMatrix();
}
FTransform BuildUETransformFromMayaTransform(MMatrix& InMatrix)
{
MMatrix UnrealSpaceJointMatrix;
// from FFbxDataConverter::ConvertMatrix
for (int i = 0; i < 4; ++i)
{
double* Row = InMatrix[i];
if (i == 1)
{
UnrealSpaceJointMatrix[i][0] = -Row[0];
UnrealSpaceJointMatrix[i][1] = Row[1];
UnrealSpaceJointMatrix[i][2] = -Row[2];
UnrealSpaceJointMatrix[i][3] = -Row[3];
}
else
{
UnrealSpaceJointMatrix[i][0] = Row[0];
UnrealSpaceJointMatrix[i][1] = -Row[1];
UnrealSpaceJointMatrix[i][2] = Row[2];
UnrealSpaceJointMatrix[i][3] = Row[3];
}
}
//OutputRotation(FinalJointMatrix);
MTransformationMatrix UnrealSpaceJointTransform(UnrealSpaceJointMatrix);
// getRotation is MSpace::kTransform
double tx, ty, tz, tw;
UnrealSpaceJointTransform.getRotationQuaternion(tx, ty, tz, tw, MSpace::kWorld);
FTransform UETrans;
UETrans.SetRotation(FQuat(tx, ty, tz, tw));
MVector Translation = UnrealSpaceJointTransform.getTranslation(MSpace::kWorld);
UETrans.SetTranslation(FVector(Translation.x, Translation.y, Translation.z));
double Scale[3];
UnrealSpaceJointTransform.getScale(Scale, MSpace::kWorld);
UETrans.SetScale3D(FVector((float)Scale[0], (float)Scale[1], (float)Scale[2]));
return UETrans;
}
void OutputRotation(const MMatrix& M)
{
MTransformationMatrix TM(M);
MEulerRotation Euler = TM.eulerRotation();
FVector V;
V.X = RadToDeg(Euler[0]);
V.Y = RadToDeg(Euler[1]);
V.Z = RadToDeg(Euler[2]);
std::string test2 = std::string(TCHAR_TO_UTF8(*V.ToString()));
MGlobal::displayInfo(test2.c_str());
}
struct IStreamedEntity
{
public:
virtual ~IStreamedEntity() {};
virtual bool ShouldDisplayInUI() const { return false; }
virtual MString GetDisplayText() const = 0;
virtual bool ValidateSubject() const = 0;
virtual void RebuildSubjectData() = 0;
virtual void OnStream(double StreamTime, int32 FrameNumber) = 0;
};
struct FStreamHierarchy
{
FName JointName;
MFnIkJoint JointObject;
int32 ParentIndex;
FStreamHierarchy() {}
FStreamHierarchy(const FStreamHierarchy& Other)
: JointName(Other.JointName)
, JointObject(Other.JointObject.dagPath())
, ParentIndex(Other.ParentIndex)
{}
FStreamHierarchy(FName InJointName, const MDagPath& InJointPath, int32 InParentIndex)
: JointName(InJointName)
, JointObject(InJointPath)
, ParentIndex(InParentIndex)
{}
};
struct FLiveLinkStreamedJointHeirarchySubject : IStreamedEntity
{
FLiveLinkStreamedJointHeirarchySubject(FName InSubjectName, MDagPath InRootPath)
: SubjectName(InSubjectName)
, RootDagPath(InRootPath)
{}
virtual bool ShouldDisplayInUI() const { return true; }
virtual MString GetDisplayText() const
{
std::string test2 = std::string(TCHAR_TO_UTF8(*SubjectName.ToString()));
return MString("Character: ") + MString(test2.c_str()) + " ( " + RootDagPath.fullPathName() + " )";
}
virtual bool ValidateSubject() const
{
MStatus stat;
bool bIsValid = RootDagPath.isValid(&stat);
std::string StatusMessage("Unset");
if (stat == MS::kSuccess)
{
StatusMessage = std::string("Success");
}
else if (stat == MS::kFailure)
{
StatusMessage = std::string("Failure");
}
else
{
StatusMessage = std::string("Other");
}
FPlatformMisc::LowLevelOutputDebugStringf(TEXT("Testing %s for removal Path:%s Valid:%s Status:%s\n"),
*SubjectName.ToString(), RootDagPath.fullPathName().asWChar(), bIsValid ? TEXT("true") : TEXT("false"), StatusMessage.c_str());
if (stat != MS::kFailure && bIsValid)
{
//Path checks out as valid
MFnIkJoint Joint(RootDagPath, &stat);
MVector returnvec = Joint.getTranslation(MSpace::kWorld, &stat);
if (stat == MS::kSuccess)
{
StatusMessage = std::string("Success");
}
else if (stat == MS::kFailure)
{
StatusMessage = std::string("Failure");
}
else
{
StatusMessage = std::string("Other");
}
FPlatformMisc::LowLevelOutputDebugStringf(TEXT("\tTesting %s for removal Path:%s Valid:%s Status:%s\n"),
*SubjectName.ToString(), RootDagPath.fullPathName().asWChar(), bIsValid ? TEXT("true") : TEXT("false"), StatusMessage.c_str());
}
return bIsValid;
}
virtual void RebuildSubjectData()
{
JointsToStream.Reset();
MItDag::TraversalType traversalType = MItDag::kBreadthFirst;
MFn::Type filter = MFn::kJoint;
MStatus status;
MItDag JointIterator;
JointIterator.reset(RootDagPath, MItDag::kDepthFirst, MFn::kJoint);
//Build Hierarchy
TArray<int32> ParentIndexStack;
ParentIndexStack.SetNum(100, false);
TArray<FName> JointNames;
TArray<int32> JointParents;
int32 Index = 0;
for (; !JointIterator.isDone(); JointIterator.next())
{
uint32 Depth = JointIterator.depth();
if (Depth >= (uint32)ParentIndexStack.Num())
{
ParentIndexStack.SetNum(Depth + 1);
}
ParentIndexStack[Depth] = Index++;
int32 ParentIndex = Depth == 0 ? -1 : ParentIndexStack[Depth - 1];
MDagPath JointPath;
status = JointIterator.getPath(JointPath);
MFnIkJoint JointObject(JointPath);
//MGlobal::displayInfo(MString("Iter: ") + JointPath.fullPathName() + JointIterator.depth());
FName JointName(JointObject.name().asChar());
JointsToStream.Add(FStreamHierarchy(JointName, JointPath, ParentIndex));
JointNames.Add(JointName);
JointParents.Add(ParentIndex);
}
LiveLinkProvider->UpdateSubject(SubjectName, JointNames, JointParents);
}
virtual void OnStream(double StreamTime, int32 FrameNumber)
{
TArray<FTransform> JointTransforms;
JointTransforms.Reserve(JointsToStream.Num());
TArray<MMatrix> InverseScales;
InverseScales.Reserve(JointsToStream.Num());
for (int32 Idx = 0; Idx < JointsToStream.Num(); ++Idx)
{
const FStreamHierarchy& H = JointsToStream[Idx];
MTransformationMatrix::RotationOrder RotOrder = H.JointObject.rotationOrder();
MMatrix JointScale = GetScale(H.JointObject);
InverseScales.Add(JointScale.inverse());
MMatrix ParentInverseScale = (H.ParentIndex == -1) ? MMatrix::identity : InverseScales[H.ParentIndex];
MMatrix MayaSpaceJointMatrix = JointScale *
GetRotationOrientation(H.JointObject, RotOrder) *
GetRotation(H.JointObject, RotOrder) *
GetJointOrientation(H.JointObject, RotOrder) *
ParentInverseScale *
GetTranslation(H.JointObject);
//OutputRotation(GetRotation(jointObject, RotOrder));
//OutputRotation(GetRotationOrientation(jointObject, RotOrder));
//OutputRotation(GetJointOrientation(jointObject, RotOrder));
//OutputRotation(TempJointMatrix);
JointTransforms.Add(BuildUETransformFromMayaTransform(MayaSpaceJointMatrix));
}
TArray<FLiveLinkCurveElement> Curves;
#if 0
double CurFrame = CurrentTime.value();
double CurveValue = CurFrame / 200.0;
Curves.AddDefaulted();
Curves[0].CurveName = FName(TEXT("Test"));
Curves[0].CurveValue = static_cast<float>(FMath::Clamp(CurveValue, 0.0, 1.0));
if (CurFrame > 100.0)
{
double Curve2Value = (CurFrame - 100.0) / 100.0;
Curves.AddDefaulted();
Curves[1].CurveName = FName(TEXT("Test2"));
Curves[1].CurveValue = static_cast<float>(FMath::Clamp(Curve2Value, 0.0, 1.0));
}
//MGlobal::displayInfo(MString("CURVE TEST:") + CurFrame + " " + CurveValue);
if (CurFrame > 201.0)
{
LiveLinkProvider->ClearSubject(SubjectToStream.SubjectName);
}
else
{
LiveLinkProvider->UpdateSubjectFrame(SubjectToStream.SubjectName, JointTransforms, Curves, StreamTime);
}
#else
LiveLinkProvider->UpdateSubjectFrame(SubjectName, JointTransforms, Curves, StreamTime);
#endif
}
private:
FName SubjectName;
MDagPath RootDagPath;
TArray<FStreamHierarchy> JointsToStream;
};
struct FLiveLinkBaseCameraStreamedSubject : public IStreamedEntity
{
public:
FLiveLinkBaseCameraStreamedSubject(FName InSubjectName) : SubjectName(InSubjectName) {}
virtual bool ValidateSubject() const { return true; }
virtual void RebuildSubjectData()
{
LiveLinkProvider->UpdateSubject(SubjectName, ActiveCameraBoneNames, ActiveCameraBoneParents);
}
void StreamCamera(MDagPath CameraPath, double StreamTime, int32 FrameNumber)
{
MStatus stat;
bool bIsValid = CameraPath.isValid(&stat);
if (bIsValid && stat == MStatus::kSuccess)
{
MFnCamera C(CameraPath);
MPoint EyeLocation = C.eyePoint(MSpace::kWorld);
MMatrix CameraTransformMatrix;
SetMatrixRow(CameraTransformMatrix[0], C.rightDirection(MSpace::kWorld));
SetMatrixRow(CameraTransformMatrix[1], C.viewDirection(MSpace::kWorld));
SetMatrixRow(CameraTransformMatrix[2], C.upDirection(MSpace::kWorld));
SetMatrixRow(CameraTransformMatrix[3], EyeLocation);
TArray<FTransform> CameraTransform = { BuildUETransformFromMayaTransform(CameraTransformMatrix) };
// Convert Maya Camera orientation to Unreal
CameraTransform[0].SetRotation(CameraTransform[0].GetRotation() * FRotator(0.f, -90.f, 0.f).Quaternion());
TArray<FLiveLinkCurveElement> Curves;
LiveLinkProvider->UpdateSubjectFrame(SubjectName, CameraTransform, Curves, StreamTime);
}
}
protected:
FName SubjectName;
static TArray<FName> ActiveCameraBoneNames;
static TArray<int32> ActiveCameraBoneParents;
};
TArray<FName> FLiveLinkBaseCameraStreamedSubject::ActiveCameraBoneNames = { FName("root") };
TArray<int32> FLiveLinkBaseCameraStreamedSubject::ActiveCameraBoneParents = { -1 };
struct FLiveLinkStreamedActiveCamera : public FLiveLinkBaseCameraStreamedSubject
{
public:
FLiveLinkStreamedActiveCamera() : FLiveLinkBaseCameraStreamedSubject(ActiveCameraName) {}
MDagPath CurrentActiveCameraDag;
virtual MString GetDisplayText() const { return MString(); }
virtual void OnStream(double StreamTime, int32 FrameNumber)
{
MStatus stat;
M3dView ActiveView = M3dView::active3dView(&stat);
if (stat == MStatus::kSuccess)
{
MDagPath CameraDag;
if (ActiveView.getCamera(CameraDag) == MStatus::kSuccess)
{
CurrentActiveCameraDag = CameraDag;
}
}
StreamCamera(CurrentActiveCameraDag, StreamTime, FrameNumber);
}
private:
static FName ActiveCameraName;
};
struct FLiveLinkStreamedCameraSubject : FLiveLinkBaseCameraStreamedSubject
{
public:
FLiveLinkStreamedCameraSubject(FName InSubjectName, MDagPath InDagPath) : FLiveLinkBaseCameraStreamedSubject(InSubjectName), CameraPath(InDagPath) {}
virtual bool ShouldDisplayInUI() const { return true; }
virtual MString GetDisplayText() const
{
std::string test2 = std::string(TCHAR_TO_UTF8(*SubjectName.ToString()));
return MString("Camera: ") + *test2.c_str() + " ( " + CameraPath.fullPathName() + " )";
}
virtual void OnStream(double StreamTime, int32 FrameNumber)
{
StreamCamera(CameraPath, StreamTime, FrameNumber);
}
private:
MDagPath CameraPath;
};
FName FLiveLinkStreamedActiveCamera::ActiveCameraName("EditorActiveCamera");
struct FLiveLinkStreamedPropSubject : IStreamedEntity
{
public:
FLiveLinkStreamedPropSubject(FName InSubjectName, MDagPath InRootPath)
: SubjectName(InSubjectName)
, RootDagPath(InRootPath)
{}
virtual bool ShouldDisplayInUI() const { return true; }
virtual MString GetDisplayText() const
{
std::string test2 = std::string(TCHAR_TO_UTF8(*SubjectName.ToString()));
return MString("Prop: ") + MString(test2.c_str()) + " ( " + RootDagPath.fullPathName() + " )";
}
virtual bool ValidateSubject() const {return true;}
virtual void RebuildSubjectData()
{
LiveLinkProvider->UpdateSubject(SubjectName, PropBoneNames, PropBoneParents);
}
virtual void OnStream(double StreamTime, int32 FrameNumber)
{
MFnTransform TransformNode(RootDagPath);
MMatrix Transform = TransformNode.transformation().asMatrix();
TArray<FTransform> UETransforms = { BuildUETransformFromMayaTransform(Transform) };
// Convert Maya Camera orientation to Unreal
TArray<FLiveLinkCurveElement> Curves;
LiveLinkProvider->UpdateSubjectFrame(SubjectName, UETransforms, Curves, StreamTime);
}
private:
FName SubjectName;
MDagPath RootDagPath;
static TArray<FName> PropBoneNames;
static TArray<int32> PropBoneParents;
};
TArray<FName> FLiveLinkStreamedPropSubject::PropBoneNames = { FName("root") };
TArray<int32> FLiveLinkStreamedPropSubject::PropBoneParents = { -1 };
class FLiveLinkStreamedSubjectManager
{
private:
TArray<TSharedPtr<IStreamedEntity>> Subjects;
void ValidateSubjects()
{
Subjects.RemoveAll([](const TSharedPtr<IStreamedEntity>& Item)
{
return !Item->ValidateSubject();
});
RefreshUI();
}
public:
FLiveLinkStreamedSubjectManager()
{
Reset();
}
void GetSubjectEntries(TArray<MString>& Entries) const
{
for (const TSharedPtr<IStreamedEntity>& Subject : Subjects)
{
if (Subject->ShouldDisplayInUI())
{
Entries.Add(Subject->GetDisplayText());
}
}
}
template<class SubjectType, typename... ArgsType>
TSharedPtr<SubjectType> AddSubjectOfType(ArgsType&&... Args)
{
TSharedPtr<SubjectType> Subject = MakeShareable(new SubjectType(Args...));
Subject->RebuildSubjectData();
int32 FrameNumber = MAnimControl::currentTime().value();
Subject->OnStream(FPlatformTime::Seconds(), FrameNumber);
Subjects.Add(Subject);
return Subject;
}
void AddJointHeirarchySubject(FName SubjectName, MDagPath RootPath)
{
AddSubjectOfType<FLiveLinkStreamedJointHeirarchySubject>(SubjectName, RootPath);
}
void AddCameraSubject(FName SubjectName, MDagPath RootPath)
{
AddSubjectOfType<FLiveLinkStreamedCameraSubject>(SubjectName, RootPath);
}
void AddPropSubject(FName SubjectName, MDagPath RootPath)
{
AddSubjectOfType<FLiveLinkStreamedPropSubject>(SubjectName, RootPath);
}
void RemoveSubject(MString SubjectToRemove)
{
TArray<MString> Entries;
GetSubjectEntries(Entries);
int32 Index = Entries.IndexOfByKey(SubjectToRemove);
Subjects.RemoveAt(Index);
}
void Reset()
{
Subjects.Reset();
AddSubjectOfType<FLiveLinkStreamedActiveCamera>();
}
void RebuildSubjects()
{
ValidateSubjects();
for (const TSharedPtr<IStreamedEntity>& Subject : Subjects)
{
Subject->RebuildSubjectData();
}
}
void StreamSubjects() const
{
double StreamTime = FPlatformTime::Seconds();
int32 FrameNumber = MAnimControl::currentTime().value();
for (const TSharedPtr<IStreamedEntity>& Subject : Subjects)
{
Subject->OnStream(StreamTime, FrameNumber);
}
}
};
const MString LiveLinkSubjectsCommandName("LiveLinkSubjects");
class LiveLinkSubjectsCommand : public MPxCommand
{
public:
static void cleanup() {}
static void* creator() { return new LiveLinkSubjectsCommand(); }
MStatus doIt(const MArgList& args)
{
TArray<MString> SubjectEntries;
LiveLinkStreamManager->GetSubjectEntries(SubjectEntries);
for (const MString& Entry : SubjectEntries)
{
appendToResult(Entry);
}
return MS::kSuccess;
}
};
const MString LiveLinkAddSubjectCommandName("LiveLinkAddSubject");
class LiveLinkAddSubjectCommand : public MPxCommand
{
public:
static void cleanup() {}
static void* creator() { return new LiveLinkAddSubjectCommand(); }
MStatus doIt(const MArgList& args)
{
MSyntax Syntax;
Syntax.addArg(MSyntax::kString);
MArgDatabase argData(Syntax, args);
MString Name;
argData.getCommandArgument(0, Name);
FName SubjectFName(Name.asChar());
MSelectionList selected;
MGlobal::getActiveSelectionList(selected);
// Find selected joint
for (unsigned int i = 0; i < selected.length(); ++i)
{
MObject obj;
selected.getDependNode(i, obj);
if (obj.hasFn(MFn::kJoint))
{
MFnIkJoint JointObject(obj);
MDagPath Path;
JointObject.getPath(Path);
LiveLinkStreamManager->AddJointHeirarchySubject(SubjectFName, Path);
}
else if (obj.hasFn(MFn::kCamera))
{
MFnCamera CameraObject(obj);
MDagPath Path;
CameraObject.getPath(Path);
LiveLinkStreamManager->AddCameraSubject(SubjectFName, Path);
}
else if(obj.hasFn(MFn::kTransform))
{
MFnTransform TransformNode(obj);
MDagPath Path;
TransformNode.getPath(Path);
LiveLinkStreamManager->AddPropSubject(SubjectFName, Path);
}
}
MGlobal::displayInfo(MString("LiveLinkAddSubjectCommand ") + Name);
return MS::kSuccess;
}
};
const MString LiveLinkRemoveSubjectCommandName("LiveLinkRemoveSubject");
class LiveLinkRemoveSubjectCommand : public MPxCommand
{
public:
static void cleanup() {}
static void* creator() { return new LiveLinkRemoveSubjectCommand(); }
MStatus doIt(const MArgList& args)
{
MSyntax Syntax;
Syntax.addArg(MSyntax::kString);
MArgDatabase argData(Syntax, args);
MString SubjectToRemove;
argData.getCommandArgument(0, SubjectToRemove);
LiveLinkStreamManager->RemoveSubject(SubjectToRemove);
return MS::kSuccess;
}
};
const MString LiveLinkConnectionStatusCommandName("LiveLinkConnectionStatus");
class LiveLinkConnectionStatusCommand : public MPxCommand
{
public:
static void cleanup() {}
static void* creator() { return new LiveLinkConnectionStatusCommand(); }
MStatus doIt(const MArgList& args)
{
MString ConnectionStatus("No Provider (internal error)");
bool bConnection = false;
if(LiveLinkProvider.IsValid())
{
if (LiveLinkProvider->HasConnection())
{
ConnectionStatus = "Connected";
bConnection = true;
}
else
{
ConnectionStatus = "No Connection";
}
}
appendToResult(ConnectionStatus);
appendToResult(bConnection);
return MS::kSuccess;
}
};
void OnForceChange(MTime& time, void* clientData)
{
LiveLinkStreamManager->StreamSubjects();
}
class FMayaOutputDevice : public FOutputDevice
{
public:
FMayaOutputDevice() : bAllowLogVerbosity(false) {}
virtual void Serialize(const TCHAR* V, ELogVerbosity::Type Verbosity, const class FName& Category) override
{
if ((bAllowLogVerbosity && Verbosity <= ELogVerbosity::Log) || (Verbosity <= ELogVerbosity::Display))
{
std::string test2 = std::string(TCHAR_TO_UTF8(V));
MGlobal::displayInfo(test2.c_str());
}
}
private:
bool bAllowLogVerbosity;
};
void OnScenePreOpen(void* client)
{
LiveLinkStreamManager->Reset();
RefreshUI();
}
void OnSceneOpen(void* client)
{
//BuildStreamHierarchyData();
}
void AllDagChangesCallback(
MDagMessage::DagMessage msgType,
MDagPath &child,
MDagPath &parent,
void *clientData)
{
LiveLinkStreamManager->RebuildSubjects();
}
void OnConnectionStatusChanged()
{
MGlobal::executeCommand("MayaLiveLinkRefreshConnectionUI");
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TMap<uint64, MCallbackId> PostRenderCallbackIds;
TMap<uint64, MCallbackId> ViewportDeletedCallbackIds;
void OnPostRenderViewport(const MString &str, void* ClientData)
{
LiveLinkStreamManager->StreamSubjects();
}
void OnViewportClosed(void* ClientData)
{
uint64 ViewIndex = reinterpret_cast<uint64>(ClientData);
MMessage::removeCallback(PostRenderCallbackIds[ViewIndex]);
PostRenderCallbackIds.Remove(ViewIndex);
MMessage::removeCallback(ViewportDeletedCallbackIds[ViewIndex]);
ViewportDeletedCallbackIds.Remove(ViewIndex);
}
void ClearViewportCallbacks()
{
for (TPair<uint64, MCallbackId>& Pair : PostRenderCallbackIds)
{
MMessage::removeCallback(Pair.Value);
}
PostRenderCallbackIds.Reset();
for (TPair<uint64, MCallbackId>& Pair : ViewportDeletedCallbackIds)
{
MMessage::removeCallback(Pair.Value);
}
ViewportDeletedCallbackIds.Reset();
}
MStatus RefreshViewportCallbacks()
{
MStatus ExitStatus;
if (int(M3dView::numberOf3dViews()) != PostRenderCallbackIds.Num())
{
ClearViewportCallbacks();
static MString ListEditorPanelsCmd = "gpuCacheListModelEditorPanels";
MStringArray EditorPanels;
ExitStatus = MGlobal::executeCommand(ListEditorPanelsCmd, EditorPanels);
MCHECKERROR(ExitStatus, "gpuCacheListModelEditorPanels");
if (ExitStatus == MStatus::kSuccess)
{
for (uint64 i = 0; i < EditorPanels.length(); ++i)
{
MStatus stat;
MCallbackId CallbackId = MUiMessage::add3dViewPostRenderMsgCallback(EditorPanels[i], OnPostRenderViewport, NULL, &stat);
MREPORTERROR(stat, "MUiMessage::add3dViewPostRenderMsgCallback()");
if (stat != MStatus::kSuccess)
{
ExitStatus = MStatus::kFailure;
continue;
}
PostRenderCallbackIds.Add(i, CallbackId);
CallbackId = MUiMessage::addUiDeletedCallback(EditorPanels[i], OnViewportClosed, reinterpret_cast<void*>(i), &stat);
MREPORTERROR(stat, "MUiMessage::addUiDeletedCallback()");
if (stat != MStatus::kSuccess)
{
ExitStatus = MStatus::kFailure;
continue;
}
ViewportDeletedCallbackIds.Add(i, CallbackId);
}
}
}
return ExitStatus;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
void OnInterval(float elapsedTime, float lastTime, void* clientData)
{
//No good way to check for new views being created, so just periodically refresh our list
RefreshViewportCallbacks();
OnConnectionStatusChanged();
FTicker::GetCoreTicker().Tick(elapsedTime);
}
/**
* This function is called by Maya when the plugin becomes loaded
*
* @param MayaPluginObject The Maya object that represents our plugin
*
* @return MS::kSuccess if everything went OK and the plugin is ready to use
*/
DLLEXPORT MStatus initializePlugin(MObject MayaPluginObject)
{
if(!bUEInitialized)
{
GEngineLoop.PreInit(TEXT("MayaLiveLinkPlugin -Messaging"));
ProcessNewlyLoadedUObjects();
// Tell the module manager is may now process newly-loaded UObjects when new C++ modules are loaded
FModuleManager::Get().StartProcessingNewlyLoadedObjects();
FModuleManager::Get().LoadModule(TEXT("UdpMessaging"));
GLog->TearDown(); //clean up existing output devices
GLog->AddOutputDevice(new FMayaOutputDevice()); //Add Maya output device
bUEInitialized = true; // Dont redo this part if someone unloads and reloads our plugin
}
// Tell Maya about our plugin
MFnPlugin MayaPlugin(
MayaPluginObject,
"MayaLiveLinkPlugin",
"v1.0");
LiveLinkProvider = ILiveLinkProvider::CreateLiveLinkProvider(TEXT("Maya Live Link"));
ConnectionStatusChangedHandle = LiveLinkProvider->RegisterConnStatusChangedHandle(FLiveLinkProviderConnectionStatusChanged::FDelegate::CreateStatic(&OnConnectionStatusChanged));
// We do not tick the core engine but we need to tick the ticker to make sure the message bus endpoint in LiveLinkProvider is
// up to date
FTicker::GetCoreTicker().Tick(1.f);
LiveLinkStreamManager = MakeShareable(new FLiveLinkStreamedSubjectManager());
MCallbackId forceUpdateCallbackId = MDGMessage::addForceUpdateCallback((MMessage::MTimeFunction)OnForceChange);
myCallbackIds.append(forceUpdateCallbackId);
MCallbackId ScenePreOpenedCallbackID = MSceneMessage::addCallback(MSceneMessage::kBeforeOpen, (MMessage::MBasicFunction)OnScenePreOpen);
myCallbackIds.append(ScenePreOpenedCallbackID);
MCallbackId SceneOpenedCallbackId = MSceneMessage::addCallback(MSceneMessage::kAfterOpen, (MMessage::MBasicFunction)OnSceneOpen);
myCallbackIds.append(SceneOpenedCallbackId);
MCallbackId dagChangedCallbackId = MDagMessage::addAllDagChangesCallback(AllDagChangesCallback);
myCallbackIds.append(dagChangedCallbackId);
// Update function every 5 seconds
MCallbackId timerCallback = MTimerMessage::addTimerCallback(5.f, (MMessage::MElapsedTimeFunction)OnInterval);