forked from code-google-com/stretchmesh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stretchMeshCmd.cpp
2318 lines (2018 loc) · 94.9 KB
/
stretchMeshCmd.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
// File: stretchMeshCmd.cpp
//
// Description:
// This defines a command that will create a stretch mesh node, and initialize
// all of the relevant attributes for that node (pyramid coordinates etc.). The
// deformer itself is defined in another project (stretchMesh.cpp)
//
#define KS_DOUBLE_EQ(x,v) (((v - 0.00000001) < x) && (x <( v + 0.00000001)))
#include "stretchMeshCmd.h"
#include <math.h>
#include <vector>
#include <algorithm>
#include <maya/MItSelectionList.h>
#include <maya/MString.h>
#include <maya/MArgList.h>
#include <maya/MItMeshVertex.h>
#include <maya/MPointArray.h>
#include <maya/MFnCamera.h>
#include <maya/MGlobal.h>
#include <maya/M3dView.h>
#include <maya/MDagPath.h>
#include <maya/MPlug.h>
#include <maya/MPlugArray.h>
#include <maya/MCommandResult.h>
#include <maya/MFnNurbsCurve.h>
#include <maya/MSyntax.h>
#include <maya/MArgParser.h>
#include <maya/MArgDatabase.h>
#include <maya/MCursor.h>
#include <maya/MMatrix.h>
#include "ksUtils.h"
#include "IncludeMFnPluginClass.h"
using namespace std;
// Custom struct for holding the polar coordinates of connected verts. PolarAngle and polarDistance
// represent the polar coordinates for the connected vert relative to the current vert. We are using the
// vector from the current vert to the 1st connected vert (as returned by getConnectedVertices() ) as the
// xAxis/polarAxis of the polar coordinate system. The wedgeAngle represents the angle between the
// two adjacent connected verts
struct polarCoords {
int vertID;
double polarAngle;
double polarDistance;
double wedgeAngle;
};
// Function for sorting an array of objects of type <polarCoords>
bool polarCoordsCompare (polarCoords i, polarCoords j) {
return (i.polarAngle < j.polarAngle);
}
bool stretchMeshCmd::Registered = false;
stretchMeshCmd::~stretchMeshCmd() {}
void* stretchMeshCmd::creator()
{
return new stretchMeshCmd();
}
MSyntax stretchMeshCmd::newSyntax()
{
MSyntax syntax;
syntax.enableEdit(true);
syntax.addFlag(kCollisionStepFlag, kCollisionStepFlagLong, MSyntax::kDouble);
syntax.addFlag(kIterationFlag, kIterationFlagLong, MSyntax::kDouble);
syntax.addFlag(kStiffnessFlag, kStiffnessFlagLong, MSyntax::kDouble);
syntax.addFlag(kCollisionFlag, kCollisionFlagLong, MSyntax::kBoolean);
syntax.addFlag(kAddColliderFlag, kAddColliderFlagLong, MSyntax::kString);
syntax.addFlag(kAddCurveColliderFlag, kAddCurveColliderFlagLong, MSyntax::kString);
syntax.addFlag(kAddSphereColliderFlag, kAddSphereColliderFlagLong, MSyntax::kString);
syntax.addFlag(kAddAttractorFlag, kAddAttractorFlagLong, MSyntax::kString);
syntax.addFlag(kAddCurveAttractorFlag, kAddCurveAttractorFlagLong, MSyntax::kString);
syntax.addFlag(kScaleSafeFlag, kScaleSafeFlagLong, MSyntax::kBoolean);
syntax.addFlag(kExtendConnectedVertsFlag, kExtendConnectedVertsFlagLong, MSyntax::kBoolean);
syntax.useSelectionAsDefault( true );
syntax.setObjectType( MSyntax::kSelectionList );
return syntax;
}
MStatus stretchMeshCmd::doIt( const MArgList& args )
//
// Description
// Gets the currently selected object, and stores it in the local class data.
// Then calls redoit to actually execute the command.
//
// Note
// The doit method should collect whatever information is
// required to do the task, and store it in local class data.
// It should finally call redoIt to make the command happen.
//
{
MStatus status;
status = parseArgs(args);
if (MS::kSuccess != status)
return status;
return redoIt();
}
MStatus stretchMeshCmd::parseArgs(const MArgList &args)
{
MStatus status;
MArgDatabase argData(syntax(), args);
MSelectionList argObjects;
// Initialize the <attribute>FlagSet variables to false so we can tell later on if they
// were set from the command line.
collisionStepFlagSet = false;
iterationFlagSet = false;
collisionFlagSet = false;
addColliderFlagSet = false;
addAttractorFlagSet = false;
addCurveAttractorFlagSet = false;
stiffnessFlagSet = false;
isEditMode = false;
addCurveColliderFlagSet = false;
addSphereColliderFlagSet = false;
scaleSafeFlagSet = false;
extendConnectedVertsFlagSet = false;
if (argData.isEdit()) { isEditMode = true; }
if (argData.isFlagSet(kCollisionStepFlag)) {
int tmp;
status = argData.getFlagArgument(kCollisionStepFlag, 0, tmp);
if (!status) {
status.perror("collision step flag parsing failed");
return status;
}
collisionStepFlag = tmp;
collisionStepFlagSet = true;
}else{ collisionStepFlag = COLLISION_STEP_DFLT; }
if (argData.isFlagSet(kIterationFlag)) {
int tmp;
status = argData.getFlagArgument(kIterationFlag, 0, tmp);
if (!status) {
status.perror("iteration flag parsing failed");
return status;
}
iterationFlag = tmp;
iterationFlagSet = true;
}else{ iterationFlag = ITERATIONS_DFLT; }
if (argData.isFlagSet(kStiffnessFlag)) {
double tmp;
status = argData.getFlagArgument(kStiffnessFlag, 0, tmp);
if (!status) {
status.perror("stiffness flag parsing failed");
return status;
}
stiffnessFlag = tmp;
stiffnessFlagSet = true;
}else{ stiffnessFlag = STIFFNESS_DFLT; }
if (argData.isFlagSet(kCollisionFlag)) {
bool tmp;
status = argData.getFlagArgument(kCollisionFlag, 0, tmp);
if (!status) {
status.perror("collision flag parsing failed");
return status;
}
collisionFlag = tmp;
collisionFlagSet = true;
}else{ collisionFlag = COLLISION_DFLT; }
if (argData.isFlagSet(kAddColliderFlag)) {
MString tmp;
status = argData.getFlagArgument(kAddColliderFlag, 0, tmp);
if (!status) {
status.perror("Add collider flag parsing failed");
return status;
}
addColliderFlag = tmp;
addColliderFlagSet = true;
}
if (argData.isFlagSet(kAddCurveColliderFlag)) {
MString tmp;
status = argData.getFlagArgument(kAddCurveColliderFlag, 0, tmp);
if (!status) {
status.perror("Add curve collider flag parsing failed");
return status;
}
addCurveColliderFlag = tmp;
addCurveColliderFlagSet = true;
}
if (argData.isFlagSet(kAddSphereColliderFlag)) {
MString tmp;
status = argData.getFlagArgument(kAddSphereColliderFlag, 0, tmp);
if (!status) {
status.perror("Add sphere collider flag parsing failed");
return status;
}
addSphereColliderFlag = tmp;
addSphereColliderFlagSet = true;
}
if (argData.isFlagSet(kAddAttractorFlag)) {
MString tmp;
status = argData.getFlagArgument(kAddAttractorFlag, 0, tmp);
if (!status) {
status.perror("Add attractor flag parsing failed");
return status;
}
addAttractorFlag = tmp;
addAttractorFlagSet = true;
}
if (argData.isFlagSet(kAddCurveAttractorFlag)) {
MString tmp;
status = argData.getFlagArgument(kAddCurveAttractorFlag, 0, tmp);
if (!status) {
status.perror("Add attractor flag parsing failed");
return status;
}
addCurveAttractorFlag = tmp;
addCurveAttractorFlagSet = true;
}
if (argData.isFlagSet(kScaleSafeFlag)) {
bool tmp;
status = argData.getFlagArgument(kScaleSafeFlag, 0, tmp);
if (!status) {
status.perror("scale safe flag parsing failed");
return status;
}
scaleSafeFlag = tmp;
scaleSafeFlagSet = true;
}else{ scaleSafeFlag = SCALE_SAFE_DFLT; }
if (argData.isFlagSet(kExtendConnectedVertsFlag)) {
bool tmp;
status = argData.getFlagArgument(kExtendConnectedVertsFlag, 0, tmp);
if (!status) {
status.perror("Extend connected vert flag parsing failed");
return status;
}
extendConnectedVertsFlag = tmp;
extendConnectedVertsFlagSet = true;
}else{ extendConnectedVertsFlag = EXTEND_CONN_VRTS_DFLT; }
argData.getObjects(argObjects);
if(argObjects.length() == 0){
MGlobal::displayError( "No deformable objects selected." );
}
// if there were objects passed in on the command line, use those. Else use the selected objects
selected = argObjects;
return MS::kSuccess;
}
MStatus stretchMeshCmd::redoIt()
//
// Description
// Creates/modifies a StretchMesh node
//
// Note
// The redoIt method should do the actual work, based on the
// internal data only.
//
{
MStatus status;
// We only want the polygonal meshes from the selection list
MItSelectionList iter(selected, MFn::kMesh, &status );
if (MS::kSuccess != status) {
cerr << "redoIt: could not create selection list iterator\n";
return status;
}
MString currSelected;
MSelectionList selectionList;
MPlug deformerPlug;
unsigned int numShapes;
int prevIndex;
MVector nrml;
MPoint currVrtPt;
MVector currVrtPos;
MPointArray inputPts;
MPoint connVrtPt;
MVector connVrtPos;
MVector currVrtProj;
MVector connVrtProj;
MVector projected;
double d;
MDoubleArray mvWeights;
MPoint conn1Pt;
MVector conn1Pos;
MVector conn1Proj;
MVector vec1;
MPoint conn2Pt;
MVector conn2Pos;
MVector conn2Proj;
MVector vec2;
MVector vec;
MStringArray melResult;
MIntArray connVerts;
MIntArray connVertsReverse;
MIntArray degenerateVertIds;
MPlug polarCoordsPlug;
MPlug nrmlOrderPlug;
MPlug connVrtIdPlug;
MPlug connVrtIdNrmlOrderPlug;
MPlug connVrtIdPlugArray;
MPlug connVrtIdNrmlOrderPlugArray;
MSelectionList degenerateVertList;
degenerateVertList.clear();
clearResult();
// First, we must determine if we're in edit mode
if (isEditMode){
if(selected.length() != 1){
MGlobal::displayError("A single deformer should be specified in edit/query mode.");
return MStatus::kFailure;
}
// Find the StretchMesh node from the selected object
MObject argObj;
MObject stretchMeshObj;
selected.getDependNode(0, argObj);
MFnDependencyNode argFn;
argFn.setObject(argObj);
// First, we check to see if argObj is the StretchMesh node.
if(argFn.typeName() == "stretchMesh"){
deformerFnDepNode.setObject(argObj);
}else{
// If we've gotten here, the argument to the command was not the stretchMesh, so we
// have to search for it in the input to this mesh's inMesh attr.
MDagPath argDagPath;
selected.getDagPath(0, argDagPath);
argDagPath.extendToShapeDirectlyBelow(0);
argFn.setObject(argDagPath.node());
MPlug inMeshPlug;
inMeshPlug = argFn.findPlug("inMesh");
if(!inMeshPlug.isConnected()){
MStringArray selectionStrings;
selected.getSelectionStrings(selectionStrings);
MGlobal::displayError("Expected a stretchMesh deformer or a deformed shape. Found '" + selectionStrings[0] + "' instead.");
return MStatus::kFailure;
}
// get the plug connected to the inMesh, this should be a StretchMesh, if not, print error and exit.
MPlugArray connectedPlugs;
MPlug connectedPlug;
inMeshPlug.connectedTo(connectedPlugs, true, false);
argFn.setObject(connectedPlugs[0].node());
if(argFn.typeName() == "stretchMesh"){
deformerFnDepNode.setObject(connectedPlugs[0].node());
}else{
MGlobal::displayError("Expected a stretchMesh deformer or a deformed shape.");
return MStatus::kFailure;
}
}
// If we've made it here, deformerFnDepNode contains the stretchMesh node.
// Set the attributes to be edited. Only the attributes that were specified to the
// command should be set, we can determine this from the <attribute>FlagSet boolean
// member attributes.
MPlug stretchMeshPlug;
// get the plug for nodeState, disable the stretchMesh deformer so it's not evaluating as we go.
stretchMeshPlug = deformerFnDepNode.findPlug("nodeState");
int nodeState;
stretchMeshPlug.getValue(nodeState);
stretchMeshPlug.setValue( 1 );
if(collisionStepFlagSet){
// Store the attribute values before making any changes for undo purposes.
stretchMeshPlug = deformerFnDepNode.findPlug("collisionStep");
stretchMeshPlug.getValue(collisionStepOrig);
stretchMeshPlug.setValue( collisionStepFlag );
}
if(iterationFlagSet){
// Store the attribute values before making any changes for undo purposes.
stretchMeshPlug = deformerFnDepNode.findPlug("iterations");
stretchMeshPlug.getValue(iterationOrig);
stretchMeshPlug.setValue( iterationFlag );
}
if(stiffnessFlagSet){
// Store the attribute values before making any changes for undo purposes.
stretchMeshPlug = deformerFnDepNode.findPlug("stiffnessList");
stretchMeshPlug = stretchMeshPlug.elementByLogicalIndex(0);
stretchMeshPlug = stretchMeshPlug.child(0);
stiffnessOrigArray.clear();
stiffnessOrigArray.setLength(stretchMeshPlug.numElements());
for(int itr = 0; itr < stiffnessOrigArray.length(); itr++){
stretchMeshPlug = deformerFnDepNode.findPlug("stiffnessList");
stretchMeshPlug = stretchMeshPlug.elementByLogicalIndex(0);
stretchMeshPlug = stretchMeshPlug.child(0);
stretchMeshPlug = stretchMeshPlug.elementByLogicalIndex(itr);
stretchMeshPlug.getValue(stiffnessOrigArray[itr]);
}
// set the stiffness values
for(int itr = 0; itr < stiffnessOrigArray.length(); itr++){
stretchMeshPlug = deformerFnDepNode.findPlug("stiffnessList");
stretchMeshPlug = stretchMeshPlug.elementByLogicalIndex(0);
stretchMeshPlug = stretchMeshPlug.child(0);
stretchMeshPlug = stretchMeshPlug.elementByLogicalIndex(itr);
stretchMeshPlug.setValue( stiffnessFlag );
}
}
if(scaleSafeFlagSet){
// Store the attribute values before making any changes for undo purposes.
stretchMeshPlug = deformerFnDepNode.findPlug("enableScaleSafe");
stretchMeshPlug.getValue(scaleSafeOrig);
stretchMeshPlug.setValue( scaleSafeFlag );
}
if(addColliderFlagSet){
addCollider();
}
if(addCurveColliderFlagSet){
addCurveCollider();
}
if(addSphereColliderFlagSet){
addSphereCollider();
}
if(addAttractorFlagSet){
addAttractor();
}
if(addCurveAttractorFlagSet){
addCurveAttractor();
}
// turn nodeState back to what is was before we started
stretchMeshPlug = deformerFnDepNode.findPlug("nodeState");
stretchMeshPlug.setValue( nodeState );
melResult.append(deformerFnDepNode.name());
/////////////////////////////////////////////////////////////////////////////
// END EDIT MODE ////////
/////////////////////////////////////////////////////////////////////////////
}else{
// We're not in edit mode, so just iterate through the selection list and apply a
// stretchMesh to any selected poly mesh
for(iter.reset(); !iter.isDone(); iter.next() )
{
MDagPath selectedItem;
iter.getDagPath(selectedItem);
if(selectedItem.apiType() != MFn::kMesh){
MGlobal::displayError("StretchMesh must be applied to a polygonal mesh");
continue;
}
// First off... create the stretchMesh deformer
MStringArray deformerResult;
MGlobal::executeCommand( "deformer -type stretchMesh " + selectedItem.fullPathName(), deformerResult );
melResult.append(deformerResult[0]);
// Add the deformer string to the member list so it can be removed during undo.
stretchMeshesCreated.append(deformerResult[0]);
selectionList.clear();
selectionList.add( deformerResult[0] );
MObject deformerObj;
selectionList.getDependNode(0, deformerObj);
deformerFnDepNode.setObject(deformerObj);
// set the version of stretchMesh that was used to create this node
deformerPlug = deformerFnDepNode.findPlug("stretchMeshVersion");
deformerPlug.setValue( SM_VERSION );
// get the plug for nodeState, disable the stretchMesh deformer so it's not evaluating as we go.
deformerPlug = deformerFnDepNode.findPlug("nodeState");
deformerPlug.setValue( 1 );
// Populate an array with the input point positions
MItMeshVertex vertIter( selectedItem );
int vertCount = vertIter.count();
inputPts.clear();
inputPts.setLength(vertCount);
for(vertIter.reset(); !vertIter.isDone(); vertIter.next() ){
inputPts[vertIter.index()] = vertIter.position( MSpace::kWorld );
}
connVrtIdPlugArray = deformerFnDepNode.findPlug("connVrtIdList");
connVrtIdPlugArray.setNumElements(vertCount);
connVrtIdNrmlOrderPlugArray = deformerFnDepNode.findPlug("connVrtIdNrmlOrderList");
connVrtIdNrmlOrderPlugArray.setNumElements(vertCount);
// iterate through each vertex, and set the corresponding pyramid coords on the deformer
for(int vertId = 0; vertId < vertCount; vertId++){
MItMeshVertex pyramidCoordsIter( selectedItem );
pyramidCoordsIter.setIndex(vertId, prevIndex);
connVerts.clear();
if(extendConnectedVertsFlag){
getConnectedVerts(pyramidCoordsIter, connVerts, vertId);
}else{
pyramidCoordsIter.getConnectedVertices( connVerts );
}
// // The paper calls for the connected verts to be in counter clockwise order, but getConnectedVertices returns
// // them in clockwise order. I'm reversing them here to be consistent with the paper...
// int connVertsItr = connVertsReverse.length();
// connVertsItr = connVertsItr - 1;
// connVerts.clear();
// for( ; connVertsItr >= 0; connVertsItr--){
// connVerts.append( connVertsReverse[connVertsItr] );
// }
nrml = getCurrNormal(inputPts, connVerts);
// Determine the d term of the projection plane equation
currVrtPt = inputPts[vertId];
currVrtPos.x = currVrtPt.x; currVrtPos.y = currVrtPt.y; currVrtPos.z = currVrtPt.z;
d = 0.0;
for(int j = 0; j < connVerts.length(); j++){
connVrtPt = inputPts[connVerts[j]];
connVrtPos.x = connVrtPt.x; connVrtPos.y = connVrtPt.y; connVrtPos.z = connVrtPt.z;
d = d + nrml*connVrtPos;
}
d = -(d/connVerts.length());
// project the current vertex and each neighboring vertex onto the projection plane, we'll call these v' and vi'
// respectively
currVrtProj = projectVrtToPlane(currVrtPos, nrml, d);
// NOTE: I'm not sure if this is necessary... connVrtProj isn't used anywhere else in the python version of this
// script... which is what I'm porting from.
connVrtProj.x = 0; connVrtProj.y = 0; connVrtProj.z = 0;
// Here, we're converting all connected points to polar coordinates. This is a bug fix for vertices that were degenerate.
// Converting to polar coordinates ensures that the total of all angles between adjacent connected verts and
// the current vert equals 360. First we need to define 2d cartesian coordinates based on the planed defined by
// "nrml". Here, we define the x and y axes of the 2d cartesian coordinate system:
MPoint xAxisPt = inputPts[connVerts[0]];
MVector xAxis;
xAxis.x = xAxisPt.x; xAxis.y = xAxisPt.y; xAxis.z = xAxisPt.z;
xAxis = projectVrtToPlane(xAxis, nrml, d);
xAxis = xAxis - currVrtProj;
xAxis.normalize();
MVector yAxis;
yAxis = nrml^xAxis;
yAxis.normalize();
// now convert all the connected verts to polar coordinates with respect to the plane defined by "nrml":
vector<polarCoords> polarCoordsArray;
polarCoordsArray.clear();
for(int connVrtItr = 0; connVrtItr < connVerts.length(); connVrtItr++){
double xCoord, yCoord;
MPoint connPt = inputPts[connVerts[connVrtItr]];
MVector connVec;
connVec.x = connPt.x; connVec.y = connPt.y; connVec.z = connPt.z;
connVec = projectVrtToPlane(connVec, nrml, d);
connVec = connVec - currVrtProj;
xCoord = connVec*xAxis;
yCoord = connVec*yAxis;
polarCoords currPolarCoords;
currPolarCoords.vertID = connVerts[connVrtItr];
currPolarCoords.polarDistance = sqrt((xCoord*xCoord) + (yCoord*yCoord));
// Using the polar coordinate coversion descirbed on wikipedia
if(xCoord > 0 && (yCoord > 0 || KS_DOUBLE_EQ(yCoord, 0.0))){
currPolarCoords.polarAngle = atan(yCoord/xCoord);
}else if(xCoord > 0 && yCoord < 0){
currPolarCoords.polarAngle = atan(yCoord/xCoord) + (2.0 * PI);
}else if(xCoord < 0){
currPolarCoords.polarAngle = atan(yCoord/xCoord) + PI;
}else if(KS_DOUBLE_EQ(xCoord, 0.0) && yCoord > 0){
currPolarCoords.polarAngle = PI/2.0;
}else if(KS_DOUBLE_EQ(xCoord, 0.0) && yCoord < 0){
currPolarCoords.polarAngle = (3.0 * PI)/2.0;
}else if(KS_DOUBLE_EQ(xCoord, 0.0) && KS_DOUBLE_EQ(yCoord, 0.0)){ // Handling the case of colocated verts
currPolarCoords.polarAngle = 0.0;
}
// fill the polarCoords struct
polarCoordsArray.push_back(currPolarCoords);
}
// sort the polar coords array according to the polar angle:
sort(polarCoordsArray.begin(), polarCoordsArray.end(), polarCoordsCompare );
// We have the polar angles, but now we need to calculate the wedgeAngles which actually
// represent the angles we're interested in (see description in polarCoords struct definition above)
for(int i = 0; i < polarCoordsArray.size(); i++){
if(i==0){
polarCoordsArray[i].wedgeAngle = polarCoordsArray[i].polarAngle;
}else{
polarCoordsArray[i].wedgeAngle = polarCoordsArray[i].polarAngle - polarCoordsArray[i-1].polarAngle;
}
}
// The first wedgeAngle is incorrectly set to zero, fixing that here:
polarCoordsArray[0].wedgeAngle = (2.0*PI) - polarCoordsArray.back().polarAngle;
// set the attributes representing the connected verts.
connVrtIdPlug = connVrtIdPlugArray.elementByLogicalIndex(vertId);
connVrtIdPlug = connVrtIdPlug.child(0);
connVrtIdPlug.setNumElements(connVerts.length());
connVrtIdNrmlOrderPlug = connVrtIdNrmlOrderPlugArray.elementByLogicalIndex( vertId );
connVrtIdNrmlOrderPlug = connVrtIdNrmlOrderPlug.child(0);
connVrtIdNrmlOrderPlug.setNumElements(connVerts.length());
for(int j = 0; j < connVerts.length(); j++ ){
// We have to store connected vertices in two ways (for backward compatibility),
// one in an order consistent with the way the normal is calculated, and one in
// a way that is consistent with the way the polar angles are stored. Polar
// angle order here:
polarCoordsPlug = connVrtIdPlug.elementByLogicalIndex(j);
polarCoordsPlug.setValue(polarCoordsArray[j].vertID);
// ... and normal order here:
nrmlOrderPlug = connVrtIdNrmlOrderPlug.elementByLogicalIndex(j);
nrmlOrderPlug.setValue(connVerts[j]);
}
// Determine the mean-value weights:
//
mvWeights.clear();
double weightsSum = 0.0;
for(int j = 0; j < connVerts.length(); j++){
if(connVerts.length() > MAX_NUM_CONN_VRTS){
MGlobal::executeCommand( "error \"stretchMesh currently only supports meshes with 32 or fewer connected vertices per vertex\"" );
return MStatus::kFailure;
}
double alpha1 = polarCoordsArray[j].wedgeAngle;
double alpha2 = polarCoordsArray[(j+1)%connVerts.length()].wedgeAngle;
weightsSum = weightsSum + (tan(alpha1/2) + tan(alpha2/2))/polarCoordsArray[j].polarDistance;
mvWeights.append((tan(alpha1/2) + tan(alpha2/2))/polarCoordsArray[j].polarDistance);
}
int weightItr = 0;
for(int j = 0; j < mvWeights.length(); j++){
mvWeights[j] = mvWeights[j]/weightsSum;
deformerPlug = deformerFnDepNode.findPlug("meanWeightsList");
deformerPlug = deformerPlug.elementByLogicalIndex( vertId );
deformerPlug = deformerPlug.child(0);
deformerPlug = deformerPlug.elementByLogicalIndex( j );
deformerPlug.setValue( mvWeights[j] );
weightItr = weightItr + 1;
}
// Determine the normal component of the pyramid coords (the "b" term in the paper)
vec = currVrtPos - currVrtProj;
double b = vec.length();
if ( vec*nrml < 0 ){
b = -b;
}
deformerPlug = deformerFnDepNode.findPlug("b");
deformerPlug = deformerPlug.elementByLogicalIndex(vertId);
deformerPlug.setValue( b );
// This is an alternate method for determining "b". This method produces better
// results when scaling the mesh.
for(int j = 0; j < polarCoordsArray.size(); j++){
if(polarCoordsArray.size() > MAX_NUM_CONN_VRTS){
MGlobal::executeCommand( "error \"stretchMesh currently only supports meshes with 32 or fewer connected vertices per vertex\"" );
return MStatus::kFailure;
}
// To represent the normal component of vi with respect to the local frame, we
// calculate the signed cosine of the angle between each edge incident to vi and the
// normal
connVrtPt = inputPts[polarCoordsArray[j].vertID];
MVector connPtToCurrPt;
connPtToCurrPt = (currVrtPos - connVrtPt);
double cos = (connPtToCurrPt * nrml)/connPtToCurrPt.length();
double bScales = (cos)/(sqrt(1 - (cos*cos)));
deformerPlug = deformerFnDepNode.findPlug("bScalableList");
deformerPlug = deformerPlug.elementByLogicalIndex( vertId );
deformerPlug = deformerPlug.child(0);
deformerPlug = deformerPlug.elementByLogicalIndex( j );
deformerPlug.setValue( bScales );
}
deformerPlug = deformerFnDepNode.findPlug("stiffnessList");
// "stiffnessList" is a compound attribute that has children that correspond to the
// individual vert stiffness values. It must be a compound attribute in order to support
// weight painting.
deformerPlug = deformerPlug.elementByLogicalIndex(0);
deformerPlug = deformerPlug.child(0);
// Now get the actual stiffness plug
deformerPlug = deformerPlug.elementByLogicalIndex(vertId);
deformerPlug.setValue( stiffnessFlag );
}
//
// Set iterations to 1, and compare the vertex positions to input mesh points. This will determine which verts are
// degenerate and should have stiffness values of 1.0
MObject degenerateVert;
bool stiffnessWarning = false;
deformerPlug = deformerFnDepNode.findPlug("iterations");
deformerPlug.setValue( 1 );
deformerPlug = deformerFnDepNode.findPlug("nodeState");
deformerPlug.setValue( 0 );
deformerPlug = deformerFnDepNode.findPlug("enableScaleSafe");
deformerPlug.setValue( false );
degenerateVertIds.clear();
for(vertIter.reset( selectedItem ); !vertIter.isDone(); vertIter.next() ){
int currVrtId = vertIter.index();
if(!vertIter.position(MSpace::kWorld).isEquivalent( inputPts[currVrtId], .00001)){
degenerateVert = vertIter.currentItem();
degenerateVertList.add(selectedItem, degenerateVert);
stiffnessWarning = true;
degenerateVertIds.append(currVrtId);
}
}
// iterate through one more time to find degenerate verts... this time with scale safe on
// to find degenerate scale safe verts
deformerPlug = deformerFnDepNode.findPlug("enableScaleSafe");
deformerPlug.setValue( true );
for(vertIter.reset( selectedItem ); !vertIter.isDone(); vertIter.next() ){
int currVrtId = vertIter.index();
if(!vertIter.position(MSpace::kWorld).isEquivalent( inputPts[currVrtId], .00001)){
degenerateVert = vertIter.currentItem();
degenerateVertList.add(selectedItem, degenerateVert);
stiffnessWarning = true;
degenerateVertIds.append(currVrtId);
}
}
//Turn off the deformer again while we modify the actual stiffness values: optimization
deformerPlug = deformerFnDepNode.findPlug("nodeState");
deformerPlug.setValue( 1 );
for(int degenItr = 0; degenItr < degenerateVertIds.length(); degenItr++){
deformerPlug = deformerFnDepNode.findPlug("stiffnessList");
deformerPlug = deformerPlug.elementByLogicalIndex(0);
deformerPlug = deformerPlug.child(0);
// Now get the actual stiffness plug
deformerPlug = deformerPlug.elementByLogicalIndex(degenerateVertIds[degenItr]);
deformerPlug.setValue( 1.0 );
}
if(stiffnessWarning){
MGlobal::displayWarning("Warning: StretchMesh stiffness has been set to 1.0 for one or more vertices. See documentation for details.");
MGlobal::setActiveSelectionList(degenerateVertList);
}
// Last thing we need to do: set the iterations step to something reasonable. It defaults to zero so the deformer
// isn't trying to evaluate itself during the initialization procedure above:
deformerPlug = deformerFnDepNode.findPlug("iterations");
deformerPlug.setValue( iterationFlag );
deformerPlug = deformerFnDepNode.findPlug("collisionStep");
deformerPlug.setValue( collisionStepFlag );
deformerPlug = deformerFnDepNode.findPlug("collisions");
deformerPlug.setValue( collisionFlag );
deformerPlug = deformerFnDepNode.findPlug("enableScaleSafe");
deformerPlug.setValue( scaleSafeFlag );
// add collisions if there are any
if(addColliderFlagSet){
addCollider();
}
// add attractors
if(addAttractorFlagSet){
addAttractor();
}
deformerPlug = deformerFnDepNode.findPlug("nodeState");
deformerPlug.setValue( 0 );
}
}
dgModifier.doIt();
setResult( melResult );
return MS::kSuccess;
}
MStatus stretchMeshCmd::undoIt()
//
// Description
// the undo routine
//
{
if(isEditMode){
MPlug stretchMeshPlug;
// If we're in edit mode, undo anything done in edit mode
if(collisionStepFlagSet){
stretchMeshPlug = deformerFnDepNode.findPlug("collisionStep");
stretchMeshPlug.setValue( collisionStepOrig );
}
if(iterationFlagSet){
stretchMeshPlug = deformerFnDepNode.findPlug("iterations");
stretchMeshPlug.setValue( iterationOrig );
}
if(stiffnessFlagSet){
// set the stiffness values to original values
for(int itr = 0; itr < stiffnessOrigArray.length(); itr++){
stretchMeshPlug = deformerFnDepNode.findPlug("stiffnessList");
stretchMeshPlug = stretchMeshPlug.elementByLogicalIndex(0);
stretchMeshPlug = stretchMeshPlug.child(0);
stretchMeshPlug = stretchMeshPlug.elementByLogicalIndex(itr);
stretchMeshPlug.setValue( stiffnessOrigArray[itr] );
}
}
if(collisionFlagSet){
stretchMeshPlug = deformerFnDepNode.findPlug("collisions");
stretchMeshPlug.setValue( collisionsOrig );
}
if(addColliderFlagSet){
dgModifier.undoIt();
}
if(addAttractorFlagSet){
dgModifier.undoIt();
}
if(scaleSafeFlagSet){
stretchMeshPlug = deformerFnDepNode.findPlug("enableScaleSafe");
stretchMeshPlug.setValue( scaleSafeOrig );
}
}else{
// ...otherwise, delete any stretchMesh nodes that were created.
for(int i = 0; i < stretchMeshesCreated.length(); i++){
MGlobal::executeCommand("delete " + stretchMeshesCreated[i]);
}
}
return MS::kSuccess;
}
bool stretchMeshCmd::isUndoable() const
//
// Description
// Make the command eligable for undo.
//
{
return true;
}
bool stretchMeshCmd::getConnectedVerts(MItMeshVertex& meshIter, MIntArray& connVerts, int currVertIndex)
{
meshIter.getConnectedVertices(connVerts);
MIntArray scndDegreeConnVerts;
MIntArray connVertsDup = connVerts;
// for each connected vertex, find the connected vertices and add them to the connVerts
// array
for(int connVertsIter = 0; connVertsIter < connVertsDup.length(); connVertsIter++){
int prevIndex;
meshIter.setIndex(connVertsDup[connVertsIter], prevIndex);
meshIter.getConnectedVertices(scndDegreeConnVerts);
for(int vertIter = 0; vertIter < scndDegreeConnVerts.length(); vertIter++){
// MGlobal::displayInfo(MString("Hello!"));
//first, check that this vert isn't already in the connVertsArray
bool vertIdIsDuplicate = false;
for(int i = 0; i < connVerts.length(); i++){
if(connVerts[i] == scndDegreeConnVerts[vertIter]){
vertIdIsDuplicate=true;
}
}
if(scndDegreeConnVerts[vertIter] != currVertIndex && !vertIdIsDuplicate){
connVerts.append(scndDegreeConnVerts[vertIter]);
}
}
}
/* // iterate through the connected verts array and only add non-duplicate verts
connVertsDup = connVerts;
MIntArray connVertsResult = connVerts;
MIntArray vertIDsToRemove;
for(int i = 0; i < connVerts.length(); i++){
for(int j = 0 ; j < connVerts.length(); j++){
// MGlobal::displayInfo(MString("Greetings!"));
if(connVerts[i] == connVerts[j]){
vertIDsToRemove.append(i);
}
}
}
//bubble sort the verIDsToRemove array
bubbleSort(vertIDsToRemove);
// bubbleSort(connVertsResult);
for(int i=0; i<vertIDsToRemove.length(); i++){
MGlobal::displayInfo(MString("\tvert id to remove") + (vertIDsToRemove[i]-i));
connVertsResult.remove(vertIDsToRemove[i]-i);
}
connVerts = connVertsResult;
*/
return true;
}
bool stretchMeshCmd::bubbleSort(MIntArray& vertsToRemove)
{
bool swapped;
do
{
swapped=false;
for(int i=0; i < (vertsToRemove.length()-1); i++){
if(vertsToRemove[i] > vertsToRemove[i+1]){
int swap1 = vertsToRemove[i];
int swap2 = vertsToRemove[i+1];
vertsToRemove[i] = swap2;
vertsToRemove[i+1] = swap1;
swapped = true;
}
}
}while(swapped);
return true;
}
/*procedure bubbleSort( A : list of sortable items ) defined as:
do
swapped := false
for each i in 0 to length(A) - 2 inclusive do:
if A[i] > A[i+1] then
swap( A[i], A[i+1] )
swapped := true
end if
end for
while swapped
end procedure
*/
MVector stretchMeshCmd::getCurrNormal(MPointArray& inputPts, MIntArray& connVerts)
{
// Compute the average position of all the connected verts (the "l" term in the paper)
MVector vrtAvg(0.0, 0.0, 0.0);
MVector crossSum(0.0, 0.0, 0.0);
MVector vec_1;
MVector vec_2;
MVector cross(0.0, 0.0, 0.0);
MVector cross_sum(0.0, 0.0, 0.0);
MPoint pt;
MPoint pt_1;
MPoint pt_2;
for(unsigned int i = 0; i < connVerts.length(); i++){
pt = inputPts[connVerts[i]];
vrtAvg.x = vrtAvg.x + pt.x;
vrtAvg.y = vrtAvg.y + pt.y;
vrtAvg.z = vrtAvg.z + pt.z;
}
vrtAvg.x = vrtAvg.x/connVerts.length();
vrtAvg.y = vrtAvg.y/connVerts.length();
vrtAvg.z = vrtAvg.z/connVerts.length();
// next, we need to sum the cross products between adjacent verts and the vrt_avg
for(unsigned int i = 0; i < connVerts.length(); i++){
pt_1 = inputPts[connVerts[(i+1)%connVerts.length()]];
vec_1.x = pt_1.x; vec_1.y = pt_1.y; vec_1.z = pt_1.z;
pt_2 = inputPts[connVerts[i]];
vec_2.x = pt_2.x; vec_2.y = pt_2.y; vec_2.z = pt_2.z;
cross = vec_1^vec_2;
cross_sum = cross_sum + cross;
}
cross_sum.normalize();
return cross_sum;
}
MVector stretchMeshCmd::projectVrtToPlane(MVector vrt, MVector nrml, double d)
{
// Using the algorithm described in the paper...
double x;
MVector vrtProj;
x = d + (vrt*nrml);
vrtProj = x*nrml;
vrtProj = vrt - vrtProj;
return vrtProj;
}
bool stretchMeshCmd::addCollider()
{