simplex-solver 3.1.0__39-abi3-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. simplex_solver-3.1.0.dist-info/METADATA +90 -0
  2. simplex_solver-3.1.0.dist-info/RECORD +79 -0
  3. simplex_solver-3.1.0.dist-info/WHEEL +5 -0
  4. simplexui/__init__.py +53 -0
  5. simplexui/_version.py +1 -0
  6. simplexui/channelBox.py +858 -0
  7. simplexui/comboCheckDialog.py +343 -0
  8. simplexui/commands/__init__.py +16 -0
  9. simplexui/commands/alembicCommon.py +991 -0
  10. simplexui/commands/applyCorrectives.py +451 -0
  11. simplexui/commands/correctiveInterface.py +261 -0
  12. simplexui/commands/expandedExport.py +436 -0
  13. simplexui/commands/hdf5Convert.py +60 -0
  14. simplexui/commands/mayaCorrectiveInterface.py +161 -0
  15. simplexui/commands/mayatonumpy.py +375 -0
  16. simplexui/commands/mesh.py +1081 -0
  17. simplexui/commands/numpytoimath.py +319 -0
  18. simplexui/commands/poseblendlib.py +166 -0
  19. simplexui/commands/reorderSimplexPoints.py +102 -0
  20. simplexui/commands/rigidAlign.py +99 -0
  21. simplexui/commands/smpxBlend.py +629 -0
  22. simplexui/commands/unsubdivide.py +1227 -0
  23. simplexui/commands/uvTransfer.py +977 -0
  24. simplexui/dragFilter.py +299 -0
  25. simplexui/falloffDialog.py +471 -0
  26. simplexui/img/ChefHead.png +0 -0
  27. simplexui/img/frozen.png +0 -0
  28. simplexui/interface/__init__.py +28 -0
  29. simplexui/interface/dummyInterface.py +1585 -0
  30. simplexui/interface/mayaInterface.py +3271 -0
  31. simplexui/interfaceModel.py +1053 -0
  32. simplexui/interfaceModelTrees.py +441 -0
  33. simplexui/items/__init__.py +42 -0
  34. simplexui/items/accessor.py +213 -0
  35. simplexui/items/combo.py +852 -0
  36. simplexui/items/falloff.py +778 -0
  37. simplexui/items/group.py +297 -0
  38. simplexui/items/progression.py +743 -0
  39. simplexui/items/shape.py +443 -0
  40. simplexui/items/simplex.py +1764 -0
  41. simplexui/items/slider.py +738 -0
  42. simplexui/items/stack.py +154 -0
  43. simplexui/items/traversal.py +966 -0
  44. simplexui/main.pyw +22 -0
  45. simplexui/menu/__init__.py +69 -0
  46. simplexui/menu/dummyPlugins/__init__.py +16 -0
  47. simplexui/menu/genericPlugins/__init__.py +16 -0
  48. simplexui/menu/genericPlugins/_builtins.py +268 -0
  49. simplexui/menu/genericPlugins/checkPossibleCombos.py +45 -0
  50. simplexui/menu/genericPlugins/exportSplit.py +59 -0
  51. simplexui/menu/genericPlugins/showFalloffs.py +24 -0
  52. simplexui/menu/genericPlugins/showTraversals.py +24 -0
  53. simplexui/menu/genericPlugins/simplexUvTransfer.py +107 -0
  54. simplexui/menu/genericPlugins/unsubdivide.py +70 -0
  55. simplexui/menu/mayaPlugins/__init__.py +16 -0
  56. simplexui/menu/mayaPlugins/exportOther.py +43 -0
  57. simplexui/menu/mayaPlugins/extractProgressives.py +65 -0
  58. simplexui/menu/mayaPlugins/freezeCombo.py +245 -0
  59. simplexui/menu/mayaPlugins/generateShapeIncrementals.py +97 -0
  60. simplexui/menu/mayaPlugins/importObjs.py +193 -0
  61. simplexui/menu/mayaPlugins/linearizeTraversal.py +48 -0
  62. simplexui/menu/mayaPlugins/makeShelfBtn.py +65 -0
  63. simplexui/menu/mayaPlugins/relaxToSelection.py +75 -0
  64. simplexui/menu/mayaPlugins/reloadDefinition.py +33 -0
  65. simplexui/menu/mayaPlugins/snapToNeutral.py +72 -0
  66. simplexui/menu/mayaPlugins/softSelectToCluster.py +200 -0
  67. simplexui/menu/mayaPlugins/tweakMix.py +134 -0
  68. simplexui/menu/mayaPlugins/updateRestShape.py +105 -0
  69. simplexui/pysimplex.dll.a +0 -0
  70. simplexui/pysimplex.pyd +0 -0
  71. simplexui/simplexDialog.py +1454 -0
  72. simplexui/travCheckDialog.py +397 -0
  73. simplexui/traversalDialog.py +271 -0
  74. simplexui/ui/comboCheckDialog.ui +475 -0
  75. simplexui/ui/falloffDialog.ui +243 -0
  76. simplexui/ui/simplexDialog.ui +1458 -0
  77. simplexui/ui/travCheckDialog.ui +488 -0
  78. simplexui/ui/traversalDialog.ui +532 -0
  79. simplexui/utils.py +320 -0
@@ -0,0 +1,3271 @@
1
+ # Copyright 2016, Blur Studio
2
+ #
3
+ # This file is part of Simplex.
4
+ #
5
+ # Simplex is free software: you can redistribute it and/or modify
6
+ # it under the terms of the GNU Lesser General Public License as published by
7
+ # the Free Software Foundation, either version 3 of the License, or
8
+ # (at your option) any later version.
9
+ #
10
+ # Simplex is distributed in the hope that it will be useful,
11
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ # GNU Lesser General Public License for more details.
14
+ #
15
+ # You should have received a copy of the GNU Lesser General Public License
16
+ # along with Simplex. If not, see <http://www.gnu.org/licenses/>.
17
+
18
+ # pylint: disable=invalid-name
19
+ from __future__ import annotations
20
+ import json
21
+ import re
22
+ from contextlib import contextmanager
23
+ from functools import wraps
24
+ from typing import TYPE_CHECKING
25
+
26
+ import maya.cmds as cmds
27
+ import maya.OpenMaya as om
28
+ from alembic.AbcGeom import GeometryScope, OPolyMeshSchemaSample, OV2fGeomParamSample
29
+ from imath import IntArray, UnsignedIntArray, V2fArray, V3fArray
30
+
31
+ from ..commands.alembicCommon import mkSampleVertexPoints, buildAbc
32
+ from Qt import QtCore
33
+ from Qt.QtCore import Signal
34
+ from Qt.QtWidgets import (
35
+ QApplication,
36
+ QDialog,
37
+ QMainWindow,
38
+ QMessageBox,
39
+ QSplashScreen,
40
+ )
41
+
42
+ if TYPE_CHECKING:
43
+ from ..items.simplex import Simplex
44
+
45
+ try:
46
+ import numpy as np
47
+ from ..commands.numpytoimath import numpyToImath
48
+ from ..commands.mayatonumpy import mayaToNumpy
49
+ except ImportError:
50
+ np = None
51
+ numpyToImath = None
52
+ mayaToNumpy = None
53
+
54
+
55
+ # UNDO STACK INTEGRATION
56
+ @contextmanager
57
+ def undoContext(inst=None):
58
+ """
59
+
60
+ Parameters
61
+ ----------
62
+ inst :
63
+ (Default value = None)
64
+
65
+ Returns
66
+ -------
67
+
68
+ """
69
+ if inst is None:
70
+ DCC.staticUndoOpen()
71
+ else:
72
+ inst.undoOpen()
73
+ try:
74
+ yield
75
+ finally:
76
+ if inst is None:
77
+ DCC.staticUndoClose()
78
+ else:
79
+ inst.undoClose()
80
+
81
+
82
+ def undoable(f):
83
+ """
84
+
85
+ Parameters
86
+ ----------
87
+ f :
88
+
89
+
90
+ Returns
91
+ -------
92
+
93
+ """
94
+
95
+ @wraps(f)
96
+ def stacker(*args, **kwargs):
97
+ """
98
+
99
+ Parameters
100
+ ----------
101
+ *args :
102
+
103
+ **kwargs :
104
+
105
+
106
+ Returns
107
+ -------
108
+
109
+ """
110
+ inst = None
111
+ if args and isinstance(args[0], DCC):
112
+ inst = args[0]
113
+ with undoContext(inst):
114
+ return f(*args, **kwargs)
115
+
116
+ return stacker
117
+
118
+
119
+ def doDisconnect(targets, testCnxType=("double", "float")):
120
+ """Temporarily disconnect inputs from a list of nodes and plugs
121
+
122
+ Parameters
123
+ ----------
124
+ targets :
125
+
126
+ testCnxType :
127
+ (Default value = ("double")
128
+ "float") :
129
+
130
+
131
+ Returns
132
+ -------
133
+
134
+ """
135
+ if not isinstance(targets, (list, tuple)):
136
+ targets = [targets]
137
+ targets = list(set(targets))
138
+ cnxs = {}
139
+ for target in targets:
140
+ tcnx = {}
141
+ cnxs[target] = tcnx
142
+
143
+ cnx = cmds.listConnections(
144
+ target, plugs=True, destination=False, source=True, connections=True
145
+ )
146
+ if cnx is None:
147
+ cnx = []
148
+
149
+ for i in range(0, len(cnx), 2):
150
+ cnxType = cmds.getAttr(cnx[i], type=True)
151
+ if cnxType not in testCnxType:
152
+ continue
153
+ tcnx[cnx[i + 1]] = cnx[i]
154
+ cmds.disconnectAttr(cnx[i + 1], cnx[i])
155
+ return cnxs
156
+
157
+
158
+ def doReconnect(cnxs):
159
+ """
160
+
161
+ Parameters
162
+ ----------
163
+ cnxs :
164
+
165
+
166
+ Returns
167
+ -------
168
+
169
+ """
170
+ for tdict in cnxs.values():
171
+ for s, d in tdict.items():
172
+ if not cmds.isConnected(s, d):
173
+ cmds.connectAttr(s, d, force=True)
174
+
175
+
176
+ @contextmanager
177
+ def disconnected(targets, testCnxType=("double", "float")):
178
+ """
179
+
180
+ Parameters
181
+ ----------
182
+ targets :
183
+
184
+ testCnxType :
185
+ (Default value = ("double")
186
+ "float") :
187
+
188
+
189
+ Returns
190
+ -------
191
+
192
+ """
193
+ cnxs = doDisconnect(targets, testCnxType=testCnxType)
194
+ try:
195
+ yield cnxs
196
+ finally:
197
+ doReconnect(cnxs)
198
+
199
+
200
+ def split_trailing_digits(s: str) -> tuple[str, str]:
201
+ """Split trailing digits from a string into (prefix, digits)."""
202
+ match = re.match(r"^(.*?)(\d+)?$", s)
203
+ if match:
204
+ return match.group(1), match.group(2) or ""
205
+ return s, ""
206
+
207
+
208
+ class DCC(object):
209
+ """ """
210
+
211
+ program = "maya"
212
+
213
+ def __init__(self, simplex, stack=None):
214
+ if not cmds.pluginInfo("simplex_maya", query=True, loaded=True):
215
+ cmds.loadPlugin("simplex_maya")
216
+ self.undoDepth: int = 0
217
+ self.name: str = "" # the name of the system
218
+ self.mesh: str = "" # the mesh object with the system
219
+ self.ctrl: str = "" # the object that has all the controllers on it
220
+ self.shapeNode: str = "" # the deformer object
221
+ self.hasPoseNode = False
222
+ self.poseNode: str = "" # the pose deformer object
223
+ self.op: str = "" # the simplex object
224
+ self.simplex: Simplex = simplex # the abstract representation of the setup
225
+ self._live: bool = True
226
+ self.sliderMul: float = self.simplex.sliderMul
227
+
228
+ # def __deepcopy__(self, memo):
229
+ # '''
230
+ # I don't actually need to define this here because I know that
231
+ # all of the maya "objects" store here are just strings
232
+ # But if they *weren't* (like in XSI) I would need to skip
233
+ # the maya objects when deepcopying, otherwise I might access
234
+ # a deleted scene node and crash everything
235
+ # And if we did skip things, I would also need to store a
236
+ # persistent accessor to use in case we get back to here
237
+ # through an undo
238
+ # '''
239
+ # pass
240
+
241
+ def _checkAllShapeValidity(self, shapeNames):
242
+ """Check shapes to see if they exist, and either gather the missing files, or
243
+ Load the proper data onto the shapes
244
+
245
+ Parameters
246
+ ----------
247
+ shapeNames :
248
+
249
+
250
+ Returns
251
+ -------
252
+
253
+ """
254
+ # Keep the set ordered, but make a set for quick checking
255
+ missingNameSet = set()
256
+ missingNames = []
257
+ seen = set()
258
+
259
+ # Get the blendshape weight names
260
+ try:
261
+ # GOOD GOD. This is because in maya 2016.5, if you delete a multi-instance
262
+ # then listAttr, *it lists the deleted ones, and skips the ones at the end*
263
+ # So I have to use aliasAttr and filter for the weights
264
+ aliases = cmds.aliasAttr(self.shapeNode, query=True) or []
265
+ attrs = [
266
+ aliases[i]
267
+ for i in range(0, len(aliases), 2)
268
+ if aliases[i + 1].startswith("weight[")
269
+ ]
270
+ attrs = set(attrs)
271
+
272
+ except ValueError:
273
+ attrs = set()
274
+
275
+ for shapeName in shapeNames:
276
+ if shapeName in seen:
277
+ continue
278
+ seen.add(shapeName)
279
+ if shapeName not in attrs:
280
+ if shapeName not in missingNameSet:
281
+ missingNameSet.add(shapeName)
282
+ missingNames.append(shapeName)
283
+ return missingNames, len(attrs)
284
+
285
+ @classmethod
286
+ def _removeExtraShapeNodes(cls, tfm):
287
+ shapeNodes = cmds.listRelatives(tfm, shapes=True, noIntermediate=True)
288
+ if len(shapeNodes) > 1:
289
+ keeper = None
290
+ todel = []
291
+ for sn in shapeNodes:
292
+ tfmChk = "".join(sn.rsplit("Shape", 1))
293
+ if tfmChk == tfm:
294
+ keeper = sn
295
+ else:
296
+ todel.append(sn)
297
+ if keeper is not None:
298
+ cmds.delete(todel)
299
+
300
+ def preLoad(self, simp, simpDict, create=True, pBar=None):
301
+ """
302
+
303
+ Parameters
304
+ ----------
305
+ simp :
306
+
307
+ simpDict :
308
+
309
+ create :
310
+ (Default value = True)
311
+ pBar :
312
+ (Default value = None)
313
+
314
+ Returns
315
+ -------
316
+
317
+ """
318
+ cmds.undoInfo(state=False)
319
+ try:
320
+ if pBar is not None:
321
+ pBar.setLabelText("Loading Connections")
322
+ QApplication.processEvents()
323
+ ev = simpDict["encodingVersion"]
324
+
325
+ shapeNames = simpDict.get("shapes")
326
+ if not shapeNames:
327
+ return
328
+
329
+ if ev > 1:
330
+ shapeNames = [i["name"] for i in shapeNames]
331
+
332
+ toMake, nextIndex = self._checkAllShapeValidity(shapeNames)
333
+
334
+ if not toMake:
335
+ return
336
+
337
+ if not create:
338
+ if pBar is not None:
339
+ msg = "Some shapes are Missing:\n{}\n\nCreate them?"
340
+ msg = msg.format(", ".join(toMake))
341
+ btns = (
342
+ QMessageBox.StandardButton.Yes
343
+ | QMessageBox.StandardButton.Cancel
344
+ )
345
+ bret = QMessageBox.question(pBar, "Missing Shapes", msg, btns)
346
+ if not bret & QMessageBox.StandardButton.Yes:
347
+ raise RuntimeError("Missing Shapes: {}".format(toMake))
348
+ else:
349
+ raise RuntimeError("Missing Shapes: {}".format(toMake))
350
+
351
+ if pBar is not None:
352
+ spacer = "_" * max(list(map(len, toMake)))
353
+ pBar.setMaximum(len(toMake))
354
+ pBar.setLabelText("Creating Empty Shape:\n{0}".format(spacer))
355
+ pBar.setValue(0)
356
+ QApplication.processEvents()
357
+
358
+ baseShape = cmds.duplicate(self.mesh)[0]
359
+ cmds.delete(baseShape, constructionHistory=True)
360
+ self._removeExtraShapeNodes(baseShape)
361
+
362
+ for i, shapeName in enumerate(toMake):
363
+ if pBar is not None:
364
+ pBar.setLabelText("Creating Empty Shape:\n{0}".format(shapeName))
365
+ pBar.setValue(i)
366
+ QApplication.processEvents()
367
+
368
+ baseShape = cmds.rename(baseShape, shapeName)
369
+
370
+ index = self._firstAvailableIndex()
371
+ cmds.blendShape(
372
+ self.shapeNode, edit=True, target=(self.mesh, index, baseShape, 1.0)
373
+ )
374
+ weightAttr = "{0}.weight[{1}]".format(self.shapeNode, index)
375
+ thing = cmds.ls(weightAttr)[0]
376
+
377
+ cmds.connectAttr("{0}.weights[{1}]".format(self.op, nextIndex), thing)
378
+ nextIndex += 1
379
+
380
+ cmds.delete(baseShape)
381
+ except Exception:
382
+ cmds.undoInfo(state=True)
383
+ raise
384
+
385
+ def postLoad(self, simp, preRet):
386
+ """
387
+
388
+ Parameters
389
+ ----------
390
+ simp :
391
+
392
+ preRet :
393
+
394
+ Returns
395
+ -------
396
+
397
+ """
398
+ cmds.undoInfo(state=True)
399
+
400
+ def checkForErrors(self, window):
401
+ """Check for any DCC specific errors
402
+
403
+ Parameters
404
+ ----------
405
+ window : QMainWindow
406
+ The simplex window
407
+ """
408
+ shapeNodes = cmds.listRelatives(self.mesh, shapes=True, noIntermediate=True)
409
+ if len(shapeNodes) > 1:
410
+ msg = (
411
+ "The current mesh has multiple shape nodes.",
412
+ "The UI will still mostly work, but extracting/connecting shapes"
413
+ "may fail in unexpected ways.",
414
+ )
415
+ QMessageBox.warning(window, "Multiple Shape Nodes", "\n".join(msg))
416
+
417
+ def _getOpNodes(self, thing: str):
418
+ hist: list[str] = cmds.listHistory(thing)
419
+ rawShapeNodes = cmds.ls(hist, type="blendShape")
420
+ rawPoseNodes = cmds.ls(hist, type="blendPose")
421
+
422
+ # Find any simplex ops connected to the history
423
+ # that have the given name
424
+ ops: list[str] = []
425
+ rawOps: list[str] = []
426
+ for sn in rawShapeNodes + rawPoseNodes:
427
+ op = (
428
+ cmds.listConnections(
429
+ "{0}.{1}".format(sn, "message"),
430
+ source=False,
431
+ destination=True,
432
+ type="simplex_maya",
433
+ )
434
+ or []
435
+ )
436
+ rawOps.extend(op)
437
+ rawOps = list(set(rawOps))
438
+
439
+ for op in rawOps:
440
+ js = cmds.getAttr(op + ".definition") or ""
441
+ sn = json.loads(js).get("systemName")
442
+ if sn == self.name:
443
+ ops.append(op)
444
+
445
+ if len(ops) > 1:
446
+ raise RuntimeError(
447
+ "Found too many Simplex systems with the same name on the same object"
448
+ )
449
+ return ops
450
+
451
+ def _getShapeNodes(self, ops):
452
+ shapeNodes = []
453
+ for op in ops:
454
+ try:
455
+ sn = cmds.listConnections(
456
+ "{0}.{1}".format(op, "shapeMsg"),
457
+ source=True,
458
+ destination=False,
459
+ type="blendShape",
460
+ )
461
+ except ValueError:
462
+ continue
463
+ if sn:
464
+ shapeNodes.append(sn[0])
465
+ return shapeNodes
466
+
467
+ def _getPoseNodes(self, ops):
468
+ poseNodes = []
469
+ for op in ops:
470
+ try:
471
+ sn = cmds.listConnections(
472
+ "{0}.{1}".format(op, "poseMsg"),
473
+ source=True,
474
+ destination=False,
475
+ type="blendPose",
476
+ )
477
+ except ValueError:
478
+ continue
479
+ if sn:
480
+ poseNodes.append(sn[0])
481
+ return poseNodes
482
+
483
+ def _getCtrlNodes(self, ops):
484
+ ctrlCnx = []
485
+ for op in ops:
486
+ ccnx = cmds.listConnections(
487
+ "{0}.{1}".format(op, "ctrlMsg"),
488
+ source=True,
489
+ destination=False,
490
+ )
491
+ if ccnx:
492
+ ctrlCnx.append(ccnx[0])
493
+ return ctrlCnx
494
+
495
+ def _createShapeNode(self, name, mesh) -> str:
496
+ intermediates = [
497
+ shp
498
+ for shp in cmds.listRelatives(mesh, shapes=True, path=True)
499
+ if cmds.getAttr(shp + ".intermediateObject")
500
+ ]
501
+ meshToFreeze = mesh if not intermediates else intermediates[0]
502
+ isIntermediate = cmds.getAttr(meshToFreeze + ".intermediateObject")
503
+
504
+ # Unlock the normals on the rest head because blendshapes don't work with locked normals
505
+ # and you can't really do this after the blendshape has been created
506
+ cmds.polyNormalPerVertex(meshToFreeze, unFreezeNormal=True)
507
+ cmds.polySoftEdge(meshToFreeze, angle=180, constructionHistory=True)
508
+ cmds.setAttr(meshToFreeze + ".intermediateObject", 0)
509
+ cmds.delete(meshToFreeze, constructionHistory=True)
510
+ cmds.setAttr(meshToFreeze + ".intermediateObject", isIntermediate)
511
+
512
+ name = "{}_BS".format(name)
513
+ return cmds.blendShape(mesh, name=name, frontOfChain=True)[0]
514
+
515
+ def _createPoseNode(self, name) -> str:
516
+ name = "{}_BP".format(name)
517
+ return cmds.createNode("blendPose", name=name)
518
+
519
+ def _createSimplexNode(self, name):
520
+ op = cmds.createNode("simplex_maya", name=name)
521
+ cmds.addAttr(op, longName="revision", attributeType="long")
522
+ cmds.addAttr(op, longName="shapeMsg", attributeType="message")
523
+ cmds.addAttr(op, longName="poseMsg", attributeType="message")
524
+ cmds.addAttr(op, longName="ctrlMsg", attributeType="message")
525
+ return op
526
+
527
+ def _createControlNode(self, name, op):
528
+ tfmAttrs = [".tx", ".ty", ".tz", ".rx", ".ry", ".rz", ".sx", ".sy", ".sz", ".v"]
529
+ ctrl = cmds.group(empty=True, name="{0}_CTRL".format(name))
530
+ for attr in tfmAttrs:
531
+ cmds.setAttr(ctrl + attr, keyable=False, channelBox=False)
532
+ cmds.addAttr(ctrl, longName="solver", attributeType="message")
533
+ cmds.connectAttr(
534
+ "{0}.{1}".format(ctrl, "solver"),
535
+ "{0}.{1}".format(op, "ctrlMsg"),
536
+ )
537
+ return ctrl
538
+
539
+ # System IO
540
+ @undoable
541
+ def loadNodes(self, simp, thing, create=True, pBar=None):
542
+ """Create a new system based on the simplex tree
543
+ Build any DCC objects that are missing if create=True
544
+ Raises a runtime error if missing objects are found and
545
+ create=False
546
+
547
+ Parameters
548
+ ----------
549
+ simp :
550
+
551
+ thing :
552
+
553
+ create :
554
+ (Default value = True)
555
+ pBar :
556
+ (Default value = None)
557
+
558
+ Returns
559
+ -------
560
+
561
+ """
562
+ self.name = simp.name
563
+ self.mesh = thing
564
+
565
+ ops = self._getOpNodes(thing)
566
+ sns = self._getShapeNodes(ops)
567
+ cc = self._getCtrlNodes(ops)
568
+
569
+ if not create and (not sns or not ops or not cc):
570
+ types = []
571
+ if not sns:
572
+ types.append("blendShape")
573
+ if not ops:
574
+ types.append("simplex_maya")
575
+ if not cc:
576
+ types.append("CTRL")
577
+
578
+ raise RuntimeError(
579
+ "Creation turned off and some objects are missing: {}".format(
580
+ ", ".join(types)
581
+ )
582
+ )
583
+
584
+ self.op = ops[0] if ops else self._createSimplexNode(self.name)
585
+ self.ctrl = cc[0] if cc else self._createControlNode(self.name, self.op)
586
+
587
+ self.shapeNode = sns[0] if sns else self._createShapeNode(self.name, self.mesh)
588
+ if not cmds.isConnected(f"{self.shapeNode}.message", f"{self.op}.shapeMsg"):
589
+ cmds.connectAttr(f"{self.shapeNode}.message", f"{self.op}.shapeMsg")
590
+
591
+ if self.hasPoseNode:
592
+ pns = self._getPoseNodes(ops)
593
+ self.poseNode = pns[0] if pns else self._createPoseNode(self.name)
594
+ if not cmds.isConnected(f"{self.poseNode}.message", f"{self.op}.poseMsg"):
595
+ cmds.connectAttr(f"{self.poseNode}.message", f"{self.op}.poseMsg")
596
+
597
+ def getShapeThing(self, shapeName):
598
+ """
599
+
600
+ Parameters
601
+ ----------
602
+ shapeName :
603
+
604
+
605
+ Returns
606
+ -------
607
+
608
+ """
609
+ s = cmds.ls("{0}.{1}".format(self.shapeNode, shapeName))
610
+ if not s:
611
+ return None
612
+ return s[0]
613
+
614
+ def getSliderThing(self, sliderName):
615
+ """
616
+
617
+ Parameters
618
+ ----------
619
+ sliderName :
620
+
621
+
622
+ Returns
623
+ -------
624
+
625
+ """
626
+ things = cmds.ls("{0}.{1}".format(self.ctrl, sliderName))
627
+ if not things:
628
+ return None
629
+ return things[0]
630
+
631
+ @classmethod
632
+ def buildDummyMesh(cls, name: str):
633
+ importHeadShape = cmds.createNode("mesh", name=name + "Shape")
634
+ badPar = cmds.listRelatives(importHeadShape, parent=True)[0]
635
+ importHead = cmds.rename(badPar, name)
636
+ return importHead, importHeadShape
637
+
638
+ @classmethod
639
+ @undoable
640
+ def buildRestAbc(cls, abcMesh, name):
641
+ """
642
+
643
+ Parameters
644
+ ----------
645
+ abcMesh :
646
+
647
+ name :
648
+
649
+
650
+ Returns
651
+ -------
652
+
653
+ """
654
+ if not cmds.pluginInfo("AbcImport", query=True, loaded=True):
655
+ cmds.loadPlugin("AbcImport")
656
+ if not cmds.pluginInfo("AbcImport", query=True, loaded=True):
657
+ raise RuntimeError("Unable to load the AbcImport plugin")
658
+
659
+ abcPath = str(abcMesh.getArchive())
660
+
661
+ abcNode = cmds.createNode("AlembicNode")
662
+ cmds.setAttr(abcNode + ".abc_File", abcPath, type="string")
663
+ cmds.setAttr(abcNode + ".speed", 24) # Is this needed anymore?
664
+ cmds.setAttr(abcNode + ".time", 0)
665
+
666
+ importHead, importHeadShape = cls.buildDummyMesh("{0}_SIMPLEX".format(name))
667
+
668
+ importHead = "{0}_SIMPLEX".format(name)
669
+ importHeadShape = cmds.createNode("mesh", name=importHead + "Shape")
670
+ badPar = cmds.listRelatives(importHeadShape, parent=True)[0]
671
+ importHead = cmds.rename(badPar, importHead)
672
+
673
+ cmds.connectAttr(abcNode + ".outPolyMesh[0]", importHeadShape + ".inMesh")
674
+ cmds.polyEvaluate(importHead, vertex=True) # Force a refresh
675
+ cmds.disconnectAttr(abcNode + ".outPolyMesh[0]", importHeadShape + ".inMesh")
676
+ cmds.sets(importHead, edit=True, forceElement="initialShadingGroup")
677
+ cmds.delete(abcNode)
678
+ return importHead
679
+
680
+ @classmethod
681
+ def vertCount(cls, mesh):
682
+ return cmds.polyEvaluate(mesh, vertex=True)
683
+
684
+ @undoable
685
+ def loadAbcPoses(self, abcMesh, js, pBar=None):
686
+ pass
687
+
688
+ @undoable
689
+ def loadAbc(self, abcMesh, js, pBar=None):
690
+ """
691
+
692
+ Parameters
693
+ ----------
694
+ abcMesh :
695
+
696
+ js :
697
+
698
+ pBar :
699
+ (Default value = None)
700
+
701
+ Returns
702
+ -------
703
+
704
+ """
705
+ # UGH, I *REALLY* hate that this is faster
706
+ # But if I want to be "pure" about it, I should just bite the bullet
707
+ # and do the direct alembic manipulation in C++
708
+
709
+ if not cmds.pluginInfo("AbcImport", query=True, loaded=True):
710
+ cmds.loadPlugin("AbcImport")
711
+ if not cmds.pluginInfo("AbcImport", query=True, loaded=True):
712
+ raise RuntimeError("Unable to load the AbcImport plugin")
713
+
714
+ abcPath = str(abcMesh.getArchive())
715
+
716
+ abcNode = cmds.createNode("AlembicNode")
717
+ cmds.setAttr(abcNode + ".abc_File", abcPath, type="string")
718
+
719
+ timeUnits = {
720
+ "game": 15,
721
+ "film": 24,
722
+ "pal": 25,
723
+ "ntsc": 30,
724
+ "show": 48,
725
+ "palf": 50,
726
+ "ntscf": 60,
727
+ }
728
+
729
+ fps = cmds.currentUnit(time=True, query=True)
730
+ if isinstance(fps, str):
731
+ if fps.endswith("fps"):
732
+ fps = fps[:-3]
733
+ if fps in timeUnits:
734
+ fps = timeUnits[fps]
735
+ fps = float(fps)
736
+
737
+ cmds.setAttr(abcNode + ".speed", fps)
738
+
739
+ shapes = js["shapes"]
740
+ shapeDict = {i.name: i for i in self.simplex.shapes}
741
+
742
+ if js["encodingVersion"] > 1:
743
+ shapes = [i["name"] for i in shapes]
744
+
745
+ importHead, importHeadShape = self.buildDummyMesh("importHead")
746
+
747
+ cmds.connectAttr(abcNode + ".outPolyMesh[0]", importHeadShape + ".inMesh")
748
+ cmds.polyEvaluate(importHead, vertex=True) # Force a refresh
749
+ cmds.disconnectAttr(abcNode + ".outPolyMesh[0]", importHeadShape + ".inMesh")
750
+
751
+ importRest = cmds.duplicate(self.mesh, name="importRest")[0]
752
+ cmds.delete(importRest, constructionHistory=True)
753
+ self._removeExtraShapeNodes(importRest)
754
+
755
+ importBS: str = cmds.blendShape(importRest, importHead)[0]
756
+ cmds.blendShape(importBS, edit=True, weight=[(0, 1.0)])
757
+ # Maybe get shapeNode from self.mesh??
758
+ importOrig = [
759
+ i for i in cmds.listRelatives(importHead, shapes=True) if i.endswith("Orig")
760
+ ][0]
761
+ cmds.connectAttr(abcNode + ".outPolyMesh[0]", importOrig + ".inMesh")
762
+ cmds.delete(importRest)
763
+
764
+ if pBar is not None:
765
+ pBar.show()
766
+ pBar.setMaximum(len(shapes))
767
+ longName = max(shapes, key=len)
768
+ pBar.setValue(1)
769
+ pBar.setLabelText("Loading:\n{0}".format("_" * len(longName)))
770
+
771
+ for i, shapeName in enumerate(shapes):
772
+ if pBar is not None:
773
+ pBar.setValue(i)
774
+ pBar.setLabelText("Loading:\n{0}".format(shapeName))
775
+ QApplication.processEvents()
776
+ if pBar.wasCanceled():
777
+ return
778
+ index = self.getShapeIndex(shapeDict[shapeName])
779
+ cmds.setAttr(abcNode + ".time", i)
780
+
781
+ outAttr = "{0}.worldMesh[0]".format(importHead)
782
+ tgn = "{0}.inputTarget[0].inputTargetGroup[{1}]".format(
783
+ self.shapeNode, index
784
+ )
785
+ inAttr = "{0}.inputTargetItem[6000].inputGeomTarget".format(tgn)
786
+
787
+ cmds.connectAttr(outAttr, inAttr, force=True)
788
+ cmds.disconnectAttr(outAttr, inAttr)
789
+ cmds.delete(abcNode)
790
+ cmds.delete(importHead)
791
+
792
+ def getAllShapeVertices(self, shapes, pBar=None):
793
+ """
794
+
795
+ Parameters
796
+ ----------
797
+ shapes :
798
+
799
+ pBar :
800
+ (Default value = None)
801
+
802
+ Returns
803
+ -------
804
+
805
+ """
806
+ sl = om.MSelectionList()
807
+ sl.add(self.mesh)
808
+ thing = om.MDagPath()
809
+ sl.getDagPath(0, thing)
810
+ meshFn = om.MFnMesh(thing)
811
+ _ptCount = meshFn.numVertices()
812
+ with disconnected(self.shapeNode) as cnx:
813
+ shapeCnx = cnx[self.shapeNode]
814
+ for v in shapeCnx.values():
815
+ cmds.setAttr(v, 0.0)
816
+
817
+ if pBar is not None:
818
+ # find the longest name for displaying stuff
819
+ sns = "_" * max(list(map(len, [s.name for s in shapes])))
820
+ pBar.setLabelText("Getting Shape:\n{0}".format(sns))
821
+ pBar.setMaximum(len(shapes))
822
+ QApplication.processEvents()
823
+
824
+ for i, shape in enumerate(shapes):
825
+ if pBar is not None:
826
+ pBar.setLabelText("Getting Shape:\n{0}".format(shape.name))
827
+ pBar.setValue(i)
828
+ QApplication.processEvents()
829
+
830
+ cmds.setAttr(shape.thing, 1.0)
831
+
832
+ if np is not None and mayaToNumpy is not None:
833
+ out = mayaToNumpy(meshFn.getRawPoints())
834
+ else:
835
+ flatverts = cmds.xform(
836
+ "{0}.vtx[*]".format(self.mesh),
837
+ translation=1,
838
+ query=1,
839
+ worldSpace=False,
840
+ )
841
+ args = [iter(flatverts)] * 3
842
+ out = list(zip(*args))
843
+
844
+ cmds.setAttr(shape.thing, 0.0)
845
+ shape.verts = out
846
+
847
+ def getShapeVertices(self, shape):
848
+ """
849
+
850
+ Parameters
851
+ ----------
852
+ shape :
853
+
854
+ Returns
855
+ -------
856
+
857
+ """
858
+ with disconnected(self.shapeNode) as cnx:
859
+ shapeCnx = cnx[self.shapeNode]
860
+ for v in shapeCnx.values():
861
+ cmds.setAttr(v, 0.0)
862
+ cmds.setAttr(shape.thing, 1.0)
863
+ if np is None:
864
+ flatverts = cmds.xform(
865
+ "{0}.vtx[*]".format(self.mesh),
866
+ translation=1,
867
+ query=1,
868
+ worldSpace=False,
869
+ )
870
+ args = [iter(flatverts)] * 3
871
+ out = list(zip(*args))
872
+ else:
873
+ out = self.getNumpyShape(self.mesh)
874
+ return out
875
+
876
+ def pushAllShapeVertices(self, shapes, pBar=None):
877
+ """
878
+
879
+ Parameters
880
+ ----------
881
+ shapes :
882
+
883
+ pBar :
884
+ (Default value = None)
885
+
886
+ Returns
887
+ -------
888
+
889
+ """
890
+ # take all the verts stored on the shapes
891
+ # and push them back to the DCC
892
+ for shape in shapes:
893
+ self.pushShapeVertices(shape)
894
+
895
+ def pushShapeVertices(self, shape):
896
+ """
897
+
898
+ Parameters
899
+ ----------
900
+ shape :
901
+
902
+
903
+ Returns
904
+ -------
905
+
906
+ """
907
+ # Push the vertices for a specific shape back to the DCC
908
+ pass
909
+
910
+ @classmethod
911
+ def getMeshTopology(cls, mesh, uvName=None):
912
+ """Get the topology of a mesh
913
+
914
+ Parameters
915
+ ----------
916
+ mesh : object
917
+ The DCC Mesh to read
918
+ uvName : str, optional
919
+ The name of the uv set to read
920
+
921
+ Returns
922
+ -------
923
+ np.array :
924
+ The vertex array
925
+ np.array :
926
+ The "faces" array
927
+ np.array :
928
+ The "counts" array
929
+ np.array :
930
+ The uv positions
931
+ np.array :
932
+ The "uvFaces" array
933
+ """
934
+ # Get the MDagPath from the name of the mesh
935
+ sl = om.MSelectionList()
936
+ sl.add(mesh)
937
+ thing = om.MDagPath()
938
+ sl.getDagPath(0, thing)
939
+ meshFn = om.MFnMesh(thing)
940
+
941
+ vts = om.MPointArray()
942
+ meshFn.getPoints(vts, om.MSpace.kObject)
943
+ verts = [(vts[i].x, vts[i].y, vts[i].z) for i in range(vts.length())]
944
+
945
+ faces = []
946
+ counts = []
947
+ rawUvFaces = []
948
+
949
+ vIdx = om.MIntArray()
950
+
951
+ util = om.MScriptUtil()
952
+ util.createFromInt(0)
953
+ uvIdxPtr = util.asIntPtr()
954
+ uArray = om.MFloatArray()
955
+ vArray = om.MFloatArray()
956
+ meshFn.getUVs(uArray, vArray)
957
+ hasUvs = uArray.length() > 0
958
+
959
+ for i in range(meshFn.numPolygons()):
960
+ meshFn.getPolygonVertices(i, vIdx)
961
+ face = []
962
+ for j in reversed(range(vIdx.length())):
963
+ face.append(vIdx[j])
964
+ if hasUvs:
965
+ meshFn.getPolygonUVid(i, j, uvIdxPtr)
966
+ uvIdx = util.getInt(uvIdxPtr)
967
+ if uvIdx >= uArray.length() or uvIdx < 0:
968
+ uvIdx = 0
969
+ rawUvFaces.append(uvIdx)
970
+
971
+ face = [vIdx[j] for j in reversed(range(vIdx.length()))]
972
+ faces.extend(face)
973
+ counts.append(vIdx.length())
974
+
975
+ if hasUvs:
976
+ uvs = [(uArray[i], vArray[i]) for i in range(len(vArray))]
977
+ uvFaces = rawUvFaces
978
+ else:
979
+ uvs = None
980
+ uvFaces = None
981
+
982
+ return verts, faces, counts, uvs, uvFaces
983
+
984
+ def loadMeshTopology(self):
985
+ """ """
986
+ self._faces, self._counts, self._uvs = self.getAbcFaces(self.mesh)
987
+
988
+ @classmethod
989
+ def getNumpyShape(cls, mesh, world=False):
990
+ """Get the np.array shape of the mesh connected to the smpx
991
+
992
+ Parameters
993
+ ----------
994
+ mesh : str
995
+ The name of the maya shape object
996
+ world : bool
997
+ Whether to get the points in worldspace, or local space
998
+
999
+ Returns
1000
+ -------
1001
+ : np.array
1002
+ The point positions of the mesh
1003
+
1004
+ """
1005
+ if np is None or mayaToNumpy is None:
1006
+ raise RuntimeError("Can't do numpy stuff if its not importable")
1007
+ vts = cls._getMeshVertices(mesh, world=world)
1008
+ ret = mayaToNumpy(vts)
1009
+ return ret[..., :3].copy()
1010
+
1011
+ @classmethod
1012
+ def _getMeshVertices(cls, mesh, world=False):
1013
+ """ """
1014
+ # Get the MDagPath from the name of the mesh
1015
+ sl = om.MSelectionList()
1016
+ sl.add(mesh)
1017
+ thing = om.MDagPath()
1018
+ sl.getDagPath(0, thing)
1019
+ meshFn = om.MFnMesh(thing)
1020
+ vts = om.MPointArray()
1021
+ if world:
1022
+ space = om.MSpace.kWorld
1023
+ else:
1024
+ space = om.MSpace.kObject
1025
+ meshFn.getPoints(vts, space)
1026
+ return vts
1027
+
1028
+ @classmethod
1029
+ def _exportAbcVertices(cls, mesh, world=False):
1030
+ """ """
1031
+ if np is None or numpyToImath is None:
1032
+ vts = cls._getMeshVertices(mesh, world=world)
1033
+ vertices = V3fArray(vts.length())
1034
+ for i in range(vts.length()):
1035
+ vertices[i] = (vts[i].x, vts[i].y, vts[i].z)
1036
+ else:
1037
+ vts = cls.getNumpyShape(mesh, world=world)
1038
+ vertices = mkSampleVertexPoints(vts)
1039
+ return vertices
1040
+
1041
+ @classmethod
1042
+ def getAbcFaces(cls, mesh):
1043
+ """ """
1044
+ # Get the MDagPath from the name of the mesh
1045
+ sl = om.MSelectionList()
1046
+ sl.add(mesh)
1047
+ thing = om.MDagPath()
1048
+ sl.getDagPath(0, thing)
1049
+ meshFn = om.MFnMesh(thing)
1050
+
1051
+ faces = []
1052
+ faceCounts = []
1053
+ # uvArray = []
1054
+ uvIdxArray = []
1055
+ vIdx = om.MIntArray()
1056
+
1057
+ util = om.MScriptUtil()
1058
+ util.createFromInt(0)
1059
+ uvIdxPtr = util.asIntPtr()
1060
+ uArray = om.MFloatArray()
1061
+ vArray = om.MFloatArray()
1062
+ meshFn.getUVs(uArray, vArray)
1063
+ hasUvs = uArray.length() > 0
1064
+
1065
+ for i in range(meshFn.numPolygons()):
1066
+ meshFn.getPolygonVertices(i, vIdx)
1067
+ face = []
1068
+ for j in reversed(range(vIdx.length())):
1069
+ face.append(vIdx[j])
1070
+ if hasUvs:
1071
+ meshFn.getPolygonUVid(i, j, uvIdxPtr)
1072
+ uvIdx = util.getInt(uvIdxPtr)
1073
+ if uvIdx >= uArray.length() or uvIdx < 0:
1074
+ uvIdx = 0
1075
+ uvIdxArray.append(uvIdx)
1076
+
1077
+ face = [vIdx[j] for j in reversed(range(vIdx.length()))]
1078
+ faces.extend(face)
1079
+ faceCounts.append(vIdx.length())
1080
+
1081
+ abcFaceIndices = IntArray(len(faces))
1082
+ for i in range(len(faces)):
1083
+ abcFaceIndices[i] = faces[i]
1084
+
1085
+ abcFaceCounts = IntArray(len(faceCounts))
1086
+ for i in range(len(faceCounts)):
1087
+ abcFaceCounts[i] = faceCounts[i]
1088
+
1089
+ if hasUvs:
1090
+ abcUVArray = V2fArray(len(uArray))
1091
+ for i in range(len(vArray)):
1092
+ abcUVArray[i] = (uArray[i], vArray[i])
1093
+ abcUVIdxArray = UnsignedIntArray(len(uvIdxArray))
1094
+ for i in range(len(uvIdxArray)):
1095
+ abcUVIdxArray[i] = uvIdxArray[i]
1096
+ uv = OV2fGeomParamSample(
1097
+ abcUVArray, abcUVIdxArray, GeometryScope.kFacevaryingScope
1098
+ )
1099
+ else:
1100
+ uv = None
1101
+
1102
+ return abcFaceIndices, abcFaceCounts, uv
1103
+
1104
+ def exportAbc(
1105
+ self, dccMesh, abcMesh, js, world=False, ensureCorrect=False, pBar=None
1106
+ ):
1107
+ """ """
1108
+ # export the data to alembic
1109
+ if dccMesh is None:
1110
+ dccMesh = self.mesh
1111
+
1112
+ shapeDict = {i.name: i for i in self.simplex.shapes}
1113
+
1114
+ shapeNames = js["shapes"]
1115
+ if js["encodingVersion"] > 1:
1116
+ shapeNames = [i["name"] for i in shapeNames]
1117
+ shapes = [shapeDict[i] for i in shapeNames]
1118
+
1119
+ faces, counts, uvs = self.getAbcFaces(dccMesh)
1120
+ schema = abcMesh.getSchema()
1121
+
1122
+ if pBar is not None:
1123
+ pBar.show()
1124
+ pBar.setMaximum(len(shapes))
1125
+ spacerName = "_" * max(list(map(len, shapeNames)))
1126
+ pBar.setLabelText("Exporting:\n{0}".format(spacerName))
1127
+ QApplication.processEvents()
1128
+
1129
+ if ensureCorrect:
1130
+ # Since this code is used to both export and exportOther
1131
+ # I only want to ensure that everything is correct only if
1132
+ # I'm doing a normal export
1133
+ envelope = cmds.getAttr(self.shapeNode + ".envelope")
1134
+ cmds.setAttr(self.shapeNode + ".envelope", 1.0)
1135
+
1136
+ with disconnected(self.shapeNode) as cnx:
1137
+ shapeCnx = cnx[self.shapeNode]
1138
+ for v in shapeCnx.values():
1139
+ cmds.setAttr(v, 0.0)
1140
+ for i, shape in enumerate(shapes):
1141
+ if pBar is not None:
1142
+ pBar.setLabelText("Exporting:\n{0}".format(shape.name))
1143
+ pBar.setValue(i)
1144
+ QApplication.processEvents()
1145
+ if pBar.wasCanceled():
1146
+ return
1147
+ cmds.setAttr(shape.thing, 1.0)
1148
+ verts = self._exportAbcVertices(dccMesh, world=world)
1149
+ if uvs is not None:
1150
+ abcSample = OPolyMeshSchemaSample(verts, faces, counts, uvs)
1151
+ else:
1152
+ abcSample = OPolyMeshSchemaSample(verts, faces, counts)
1153
+ schema.set(abcSample)
1154
+ cmds.setAttr(shape.thing, 0.0)
1155
+
1156
+ if ensureCorrect:
1157
+ cmds.setAttr(self.shapeNode + ".envelope", envelope)
1158
+
1159
+ def exportOtherAbc(self, dccMesh, abcMesh, js, world=False, pBar=None):
1160
+ """ """
1161
+ shapeNames = js["shapes"]
1162
+ if js["encodingVersion"] > 1:
1163
+ shapeNames = [i["name"] for i in shapeNames]
1164
+
1165
+ if pBar is not None:
1166
+ pBar.show()
1167
+ pBar.setMaximum(len(shapeNames))
1168
+ spacerName = "_" * max(list(map(len, shapeNames)))
1169
+ pBar.setLabelText("Exporting:\n{0}".format(spacerName))
1170
+ QApplication.processEvents()
1171
+
1172
+ # Get all the sliderVecs
1173
+ shapeNames, inVecs, keyIdxs = self.simplex.buildInputVectors()
1174
+ sliderVecs = [
1175
+ [0.0] * len(self.simplex.sliders) for i in range(len(self.simplex.shapes))
1176
+ ]
1177
+ for iv, idx in zip(inVecs, keyIdxs):
1178
+ sliderVecs[idx] = iv
1179
+
1180
+ # Get all the fully expanded shapes, and the activations per shape
1181
+ with disconnected(self.op) as allSliderCnx:
1182
+ sliderCnx = allSliderCnx[self.op]
1183
+ # zero all slider vals on the op to get the rest shape
1184
+ for a in sliderCnx.values():
1185
+ cmds.setAttr(a, 0.0)
1186
+ restVerts = self.getNumpyShape(dccMesh, world=world)
1187
+
1188
+ fullShapes = np.zeros((len(self.simplex.shapes), len(restVerts), 3))
1189
+ shpValArray = np.zeros((len(self.simplex.shapes), len(self.simplex.shapes)))
1190
+ for shpIdx, shape in enumerate(self.simplex.shapes):
1191
+ if pBar is not None:
1192
+ pBar.setLabelText("Reading Full Shapes:\n{0}".format(shape.name))
1193
+ pBar.setValue(shpIdx)
1194
+ QApplication.processEvents()
1195
+ if pBar.wasCanceled():
1196
+ raise RuntimeError("Cancelled!")
1197
+
1198
+ # Set the full vec for this shape
1199
+ inVec = sliderVecs[shpIdx]
1200
+ for vi, vv in enumerate(inVec):
1201
+ cmds.setAttr(sliderCnx[self.simplex.sliders[vi].thing], vv)
1202
+
1203
+ fullShapes[shpIdx] = self.getNumpyShape(dccMesh, world=world)
1204
+
1205
+ ary = np.array(cmds.getAttr(self.op + ".weights")[0])
1206
+ # Get rid of some floating point inaccuracies
1207
+ ary[np.isclose(ary, 1.0)] = 1.0
1208
+ ary[np.isclose(ary, 0.0)] = 0.0
1209
+ shpValArray[shpIdx] = ary
1210
+
1211
+ # Figure out what order to build the deltas
1212
+ # so that the deltas exist when I try to combine them
1213
+ ctrlOrder = self.simplex.controllersByDepth()
1214
+ shapeOrder = [pp.shape for ctrl in ctrlOrder for pp in ctrl.prog.pairs]
1215
+ shapeOrder = [i for i in shapeOrder if not i.isRest]
1216
+
1217
+ # Incrementally Build the numpy array of delta shapes
1218
+ # build deltaShapeArray as a 2d array because numpy is like 10x faster on 2d arrays
1219
+ indexByShape = {v: k for k, v in enumerate(self.simplex.shapes)}
1220
+ deltaShapeArray = np.zeros((len(self.simplex.shapes), len(restVerts) * 3))
1221
+ for shpOrderIdx, shape in enumerate(shapeOrder):
1222
+ if pBar is not None:
1223
+ pBar.setLabelText("Collapsing to Deltas:\n{0}".format(shape.name))
1224
+ pBar.setValue(shpOrderIdx)
1225
+ QApplication.processEvents()
1226
+ if pBar.wasCanceled():
1227
+ raise RuntimeError("Cancelled!")
1228
+
1229
+ shpIdx = indexByShape[shape]
1230
+ base = np.dot(shpValArray[shpIdx], deltaShapeArray)
1231
+ deltaShapeArray[shpIdx] = (
1232
+ fullShapes[shpIdx] - restVerts - base.reshape((-1, 3))
1233
+ ).flatten()
1234
+
1235
+ # And move that 2d array back into 3d
1236
+ deltaShapeArray = deltaShapeArray.reshape((len(self.simplex.shapes), -1, 3))
1237
+
1238
+ # Finally write the outputs
1239
+ faces, counts, uvs = self.getAbcFaces(dccMesh)
1240
+ schema = abcMesh.getSchema()
1241
+ for shpIdx, shape in enumerate(self.simplex.shapes):
1242
+ if pBar is not None:
1243
+ pBar.setLabelText("writing:\n{0}".format(shape.name))
1244
+ pBar.setValue(shpIdx)
1245
+ QApplication.processEvents()
1246
+ if pBar.wasCanceled():
1247
+ raise RuntimeError("Cancelled!")
1248
+ shpVerts = restVerts + deltaShapeArray[shpIdx]
1249
+ shpVerts = mkSampleVertexPoints(shpVerts)
1250
+ if uvs is not None:
1251
+ abcSample = OPolyMeshSchemaSample(shpVerts, faces, counts, uvs)
1252
+ else:
1253
+ abcSample = OPolyMeshSchemaSample(shpVerts, faces, counts)
1254
+ schema.set(abcSample)
1255
+
1256
+ def deleteObj(self, thing):
1257
+ """Delete the given object"""
1258
+ cmds.delete(thing)
1259
+
1260
+ def exportMesh(self, mesh, path):
1261
+ """Export a mesh to the given path"""
1262
+ faces, counts, uvs = self.getAbcFaces(mesh)
1263
+ shape = self.getNumpyShape(mesh)
1264
+ name = mesh.split('|')[-1]
1265
+ buildAbc(path, shape, faces, counts, uvs, name=name)
1266
+
1267
+ # Revision tracking
1268
+ def getRevision(self):
1269
+ """ """
1270
+ try:
1271
+ return cmds.getAttr("{0}.{1}".format(self.op, "revision"))
1272
+ except ValueError:
1273
+ # object does not exist
1274
+ return None
1275
+
1276
+ @undoable
1277
+ def incrementRevision(self):
1278
+ """ """
1279
+ value = self.getRevision()
1280
+ if value is None:
1281
+ return
1282
+ cmds.setAttr("{0}.{1}".format(self.op, "revision"), value + 1)
1283
+ jsString = self.simplex.dump()
1284
+ self.setSimplexString(self.op, jsString)
1285
+ return value + 1
1286
+
1287
+ @undoable
1288
+ def setRevision(self, val):
1289
+ """
1290
+
1291
+ Parameters
1292
+ ----------
1293
+ val :
1294
+
1295
+
1296
+ Returns
1297
+ -------
1298
+
1299
+ """
1300
+ cmds.setAttr("{0}.{1}".format(self.op, "revision"), val)
1301
+
1302
+ # System level
1303
+ @undoable
1304
+ def renameSystem(self, name):
1305
+ """
1306
+
1307
+ Parameters
1308
+ ----------
1309
+ name :
1310
+
1311
+
1312
+ Returns
1313
+ -------
1314
+
1315
+ """
1316
+ if (
1317
+ self.mesh is None
1318
+ or self.ctrl is None
1319
+ or self.shapeNode is None
1320
+ or self.op is None
1321
+ or self.simplex is None
1322
+ ):
1323
+ raise ValueError("System is not set up. Cannot rename")
1324
+
1325
+ nn = self.mesh.replace(self.name, name)
1326
+ self.mesh = cmds.rename(self.mesh, nn)
1327
+
1328
+ nn = self.ctrl.replace(self.name, name)
1329
+ self.ctrl = cmds.rename(self.ctrl, nn)
1330
+
1331
+ oldNodeName = self.shapeNode
1332
+ nn = self.shapeNode.replace(self.name, name)
1333
+ self.shapeNode = cmds.rename(self.shapeNode, nn)
1334
+
1335
+ nn = self.op.replace(self.name, name)
1336
+ self.op = cmds.rename(self.op, nn)
1337
+
1338
+ for shape in self.simplex.shapes:
1339
+ shape.thing = shape.thing.replace(oldNodeName, self.shapeNode)
1340
+
1341
+ self.name = name
1342
+
1343
+ @undoable
1344
+ def deleteSystem(self):
1345
+ """ """
1346
+ cmds.delete(self.ctrl)
1347
+ cmds.delete(self.shapeNode)
1348
+ cmds.delete(self.op)
1349
+ self.ctrl = None # the object that has all the controllers on it
1350
+ self.shapeNode = None # the deformer object
1351
+ self.op = None # the simplex object
1352
+ self.simplex = None
1353
+
1354
+ # Shapes
1355
+ @undoable
1356
+ def createShape(self, shape, live=False, offset=10):
1357
+ """
1358
+
1359
+ Parameters
1360
+ ----------
1361
+ shape :
1362
+
1363
+ live :
1364
+ (Default value = False)
1365
+ offset :
1366
+ (Default value = 10)
1367
+
1368
+ Returns
1369
+ -------
1370
+
1371
+ """
1372
+ with disconnected(self.shapeNode):
1373
+ try:
1374
+ attrs = cmds.listAttr("{0}.weight[*]".format(self.shapeNode))
1375
+ except ValueError:
1376
+ pass
1377
+ # Maya throws an error if there aren't any instead of
1378
+ # just returning an empty list
1379
+ else:
1380
+ for attr in attrs:
1381
+ cmds.setAttr("{0}.{1}".format(self.shapeNode, attr), 0.0)
1382
+ newShape = cmds.duplicate(self.mesh, name=shape.name)[0]
1383
+
1384
+ cmds.delete(newShape, constructionHistory=True)
1385
+ index = self._firstAvailableIndex()
1386
+ cmds.blendShape(
1387
+ self.shapeNode, edit=True, target=(self.mesh, index, newShape, 1.0)
1388
+ )
1389
+ weightAttr = "{0}.weight[{1}]".format(self.shapeNode, index)
1390
+ thing = cmds.ls(weightAttr)[0]
1391
+
1392
+ shapeIndex = len(shape.simplex.shapes) - 1
1393
+ cmds.connectAttr("{0}.weights[{1}]".format(self.op, shapeIndex), thing)
1394
+
1395
+ if live:
1396
+ cmds.xform(newShape, relative=True, translation=[offset, 0, 0])
1397
+ else:
1398
+ cmds.delete(newShape)
1399
+
1400
+ return thing
1401
+
1402
+ def _firstAvailableIndex(self):
1403
+ """ """
1404
+ aliases = cmds.aliasAttr(self.shapeNode, query=True)
1405
+ idxs = set()
1406
+ if not aliases:
1407
+ return 0
1408
+ for alias in aliases:
1409
+ match = re.search(r"\[\d+\]", alias)
1410
+ if not match:
1411
+ continue # No index found for the current shape
1412
+ idxs.add(int(match.group().strip("[]")))
1413
+
1414
+ for i in range(len(idxs) + 1):
1415
+ if i not in idxs:
1416
+ return i
1417
+ # there should be no way to get here, but just in case:
1418
+ return len(idxs) + 1
1419
+
1420
+ def getShapeIndex(self, shape):
1421
+ """
1422
+
1423
+ Parameters
1424
+ ----------
1425
+ shape :
1426
+
1427
+
1428
+ Returns
1429
+ -------
1430
+
1431
+ """
1432
+ aName = cmds.attributeName(shape.thing)
1433
+ aliases = cmds.aliasAttr(self.shapeNode, query=True)
1434
+ idx = aliases.index(aName)
1435
+ raw = aliases[idx + 1]
1436
+ matches = re.findall(r"\[\d+\]", raw)
1437
+ if not matches:
1438
+ raise IndexError("No index found for the current shape")
1439
+ return int(matches[-1].strip("[]"))
1440
+
1441
+ @undoable
1442
+ def extractWithDeltaShape(self, shape, live=True, offset=10.0):
1443
+ """Make a mesh representing a shape. Can be live or not.
1444
+ Also, make a shapenode that is the delta of the change being made
1445
+
1446
+ Parameters
1447
+ ----------
1448
+ shape :
1449
+
1450
+ live :
1451
+ (Default value = True)
1452
+ offset :
1453
+ (Default value = 10.0)
1454
+
1455
+ Returns
1456
+ -------
1457
+
1458
+ """
1459
+ with disconnected(self.shapeNode) as cnx:
1460
+ shapeCnx = cnx[self.shapeNode]
1461
+ for v in shapeCnx.values():
1462
+ cmds.setAttr(v, 0.0)
1463
+
1464
+ # store the delta shape
1465
+ delta = cmds.duplicate(self.mesh, name="{0}_Delta".format(shape.name))[0]
1466
+
1467
+ # Extract the shape
1468
+ cmds.setAttr(shape.thing, 1.0)
1469
+ extracted = cmds.duplicate(
1470
+ self.mesh, name="{0}_Extract".format(shape.name)
1471
+ )[0]
1472
+
1473
+ # Store the initial shape
1474
+ init = cmds.duplicate(extracted, name="{0}_Init".format(shape.name))[0]
1475
+
1476
+ # clear old orig objects
1477
+ for item in [delta, extracted, init]:
1478
+ self._clearShapes(item, doOrig=True)
1479
+
1480
+ # build the deltaObj system
1481
+ bs = cmds.blendShape(delta, name="{0}_DeltaBS".format(shape.name))[0]
1482
+
1483
+ cmds.blendShape(bs, edit=True, target=(delta, 0, init, 1.0))
1484
+ cmds.blendShape(bs, edit=True, target=(delta, 1, extracted, 1.0))
1485
+
1486
+ cmds.setAttr("{0}.{1}".format(bs, init), -1.0)
1487
+ cmds.setAttr("{0}.{1}".format(bs, extracted), 1.0)
1488
+
1489
+ # Cleanup
1490
+ nodeDict = {"Delta": delta, "Init": init}
1491
+ repDict = self._reparentDeltaShapes(extracted, nodeDict, bs)
1492
+
1493
+ # Shift the extracted shape to the side
1494
+ cmds.xform(extracted, relative=True, translation=(offset, 0, 0))
1495
+
1496
+ if live:
1497
+ self.connectShape(shape, extracted, live, delete=False)
1498
+
1499
+ return extracted, repDict["Delta"]
1500
+
1501
+ @undoable
1502
+ def extractWithDeltaConnection(self, shape, delta, value, live=True, offset=10.0):
1503
+ """Extract a shape with a live partial delta added in.
1504
+ Useful for updating progressive shapes
1505
+
1506
+ Parameters
1507
+ ----------
1508
+ shape :
1509
+
1510
+ delta :
1511
+
1512
+ value :
1513
+
1514
+ live :
1515
+ (Default value = True)
1516
+ offset :
1517
+ (Default value = 10.0)
1518
+
1519
+ Returns
1520
+ -------
1521
+
1522
+ """
1523
+ with disconnected(self.shapeNode):
1524
+ for attr in cmds.listAttr("{0}.weight[*]".format(self.shapeNode)):
1525
+ cmds.setAttr("{0}.{1}".format(self.shapeNode, attr), 0.0)
1526
+
1527
+ # Pull out the rest shape. we will blend this guy to the extraction
1528
+ extracted = cmds.duplicate(
1529
+ self.mesh, name="{0}_Extract".format(shape.name)
1530
+ )[0]
1531
+
1532
+ cmds.setAttr(shape.thing, 1.0)
1533
+ # Store the initial shape
1534
+ init = cmds.duplicate(self.mesh, name="{0}_Init".format(shape.name))[0]
1535
+
1536
+ # clear old orig objects
1537
+ for item in [init, extracted]:
1538
+ self._clearShapes(item, doOrig=True)
1539
+
1540
+ deltaPar = cmds.listRelatives(delta, parent=True)[0]
1541
+
1542
+ # build the restObj system
1543
+ cmds.select(clear=True) # 'cause maya
1544
+ bs = cmds.blendShape(extracted, name="{0}_DeltaBS".format(shape.name))[0]
1545
+ cmds.blendShape(bs, edit=True, target=(extracted, 0, init, 1.0))
1546
+ cmds.blendShape(bs, edit=True, target=(extracted, 1, deltaPar, 1.0))
1547
+
1548
+ cmds.setAttr("{0}.{1}".format(bs, init), 1.0)
1549
+ cmds.setAttr("{0}.{1}".format(bs, deltaPar), value)
1550
+
1551
+ outCnx = "{0}.worldMesh[0]".format(delta)
1552
+ inCnx = "{0}.inputTarget[0].inputTargetGroup[{1}].inputTargetItem[6000].inputGeomTarget".format(
1553
+ bs, 1
1554
+ )
1555
+ cmds.connectAttr(outCnx, inCnx, force=True)
1556
+ cmds.aliasAttr(delta, "{0}.{1}".format(bs, deltaPar))
1557
+
1558
+ # Cleanup
1559
+ nodeDict = {"Init": init}
1560
+ self._reparentDeltaShapes(extracted, nodeDict, bs)
1561
+
1562
+ # Remove the tweak node, otherwise editing the input progressives
1563
+ # *inverts* the shape
1564
+ exShape = cmds.listRelatives(extracted, noIntermediate=1, shapes=1)[0]
1565
+ tweak = cmds.listConnections(
1566
+ exShape + ".tweakLocation", source=1, destination=0
1567
+ )
1568
+ if tweak:
1569
+ cmds.delete(tweak)
1570
+
1571
+ # Shift the extracted shape to the side
1572
+ cmds.xform(extracted, relative=True, translation=(offset, 0, 0))
1573
+ self.connectShape(shape, extracted, live, delete=False)
1574
+
1575
+ return extracted
1576
+
1577
+ @undoable
1578
+ def extractShape(self, shape, live=True, offset=10.0):
1579
+ """Make a mesh representing a shape. Can be live or not.
1580
+ Can also store its starting shape and delta data
1581
+
1582
+ Parameters
1583
+ ----------
1584
+ shape :
1585
+
1586
+ live :
1587
+ (Default value = True)
1588
+ offset :
1589
+ (Default value = 10.0)
1590
+
1591
+ Returns
1592
+ -------
1593
+
1594
+ """
1595
+ with disconnected(self.shapeNode):
1596
+ for attr in cmds.listAttr("{0}.weight[*]".format(self.shapeNode)):
1597
+ cmds.setAttr("{0}.{1}".format(self.shapeNode, attr), 0.0)
1598
+
1599
+ cmds.setAttr(shape.thing, 1.0)
1600
+ extracted = cmds.duplicate(
1601
+ self.mesh, name="{0}_Extract".format(shape.name)
1602
+ )[0]
1603
+
1604
+ # Shift the extracted shape to the side
1605
+ cmds.xform(extracted, relative=True, translation=(offset, 0, 0))
1606
+ if live:
1607
+ self.connectShape(shape, extracted, live, delete=False)
1608
+ return extracted
1609
+
1610
+ @undoable
1611
+ def connectShape(self, shape, mesh=None, live=False, delete=False):
1612
+ """Force a shape to match a mesh
1613
+ The "connect shape" button is:
1614
+ mesh=None, delete=True
1615
+ The "match shape" button is:
1616
+ mesh=someMesh, delete=False
1617
+ There is a possibility of a "make live" button:
1618
+ live=True, delete=False
1619
+
1620
+ Parameters
1621
+ ----------
1622
+ shape :
1623
+
1624
+ mesh :
1625
+ (Default value = None)
1626
+ live :
1627
+ (Default value = False)
1628
+ delete :
1629
+ (Default value = False)
1630
+
1631
+ Returns
1632
+ -------
1633
+
1634
+ """
1635
+ if mesh is None:
1636
+ attrName = cmds.attributeName(shape.thing, long=True)
1637
+ mesh = "{0}_Extract".format(attrName)
1638
+
1639
+ chk = cmds.ls(mesh)
1640
+ if not chk:
1641
+ return
1642
+ if len(chk) > 1:
1643
+ msg = "Multiple objects with the same name found in file:\n"
1644
+ msg += '\n'.join(chk)
1645
+ raise ValueError(msg)
1646
+
1647
+ index = self.getShapeIndex(shape)
1648
+ tgn = "{0}.inputTarget[0].inputTargetGroup[{1}]".format(self.shapeNode, index)
1649
+ cnx = mesh + "Shape" if cmds.nodeType(mesh) == "transform" else mesh
1650
+
1651
+ outAttr = "{0}.worldMesh[0]".format(
1652
+ cnx
1653
+ ) # Make sure to check the right shape object
1654
+ inAttr = "{0}.inputTargetItem[6000].inputGeomTarget".format(tgn)
1655
+
1656
+ if not cmds.isConnected(outAttr, inAttr):
1657
+ cmds.connectAttr(outAttr, inAttr, force=True)
1658
+
1659
+ if not live:
1660
+ cmds.disconnectAttr(outAttr, inAttr)
1661
+
1662
+ if delete:
1663
+ cmds.delete(mesh)
1664
+
1665
+ @undoable
1666
+ def extractPosedShape(self, shape):
1667
+ """
1668
+
1669
+ Parameters
1670
+ ----------
1671
+ shape :
1672
+
1673
+
1674
+ Returns
1675
+ -------
1676
+
1677
+ """
1678
+ pass
1679
+
1680
+ @undoable
1681
+ def zeroShape(self, shape):
1682
+ """Set the shape to be completely zeroed
1683
+
1684
+ Parameters
1685
+ ----------
1686
+ shape :
1687
+
1688
+
1689
+ Returns
1690
+ -------
1691
+
1692
+ """
1693
+ index = self.getShapeIndex(shape)
1694
+ tgn = "{0}.inputTarget[0].inputTargetGroup[{1}]".format(self.shapeNode, index)
1695
+ shapeInput = "{0}.inputTargetItem[6000]".format(tgn)
1696
+ cmds.setAttr(
1697
+ "{0}.inputPointsTarget".format(shapeInput), 0, (), type="pointArray"
1698
+ )
1699
+ cmds.setAttr(
1700
+ "{0}.inputComponentsTarget".format(shapeInput), 0, "", type="componentList"
1701
+ )
1702
+
1703
+ @undoable
1704
+ def deleteShape(self, toDelShape):
1705
+ """Remove a shape from the system
1706
+
1707
+ Parameters
1708
+ ----------
1709
+ toDelShape :
1710
+
1711
+
1712
+ Returns
1713
+ -------
1714
+
1715
+ """
1716
+ index = self.getShapeIndex(toDelShape)
1717
+ tgn = "{0}.inputTarget[0].inputTargetGroup[{1}]".format(self.shapeNode, index)
1718
+ cmds.removeMultiInstance(toDelShape.thing, b=True)
1719
+ cmds.removeMultiInstance(tgn, b=True)
1720
+ cmds.aliasAttr(toDelShape.thing, remove=True)
1721
+ self._rebuildShapeConnections()
1722
+
1723
+ def _rebuildShapeConnections(self):
1724
+ """ """
1725
+ # Rebuild the shape connections in the proper order
1726
+ cnxs = (
1727
+ cmds.listConnections(
1728
+ self.op, plugs=True, source=False, destination=True, connections=True
1729
+ )
1730
+ or []
1731
+ )
1732
+ for i, cnx in enumerate(cnxs):
1733
+ if i % 2 == 0 and cnx.startswith("{0}.weights[".format(self.op)):
1734
+ cmds.disconnectAttr(cnxs[i], cnxs[i + 1])
1735
+
1736
+ for i, shape in enumerate(self.simplex.shapes):
1737
+ cmds.connectAttr(
1738
+ "{0}.weights[{1}]".format(self.op, i), shape.thing, force=True
1739
+ )
1740
+
1741
+ @undoable
1742
+ def forceRebuildShapeConnections(self):
1743
+ """ """
1744
+ self._rebuildShapeConnections()
1745
+
1746
+ @undoable
1747
+ def renameShape(self, shape, name):
1748
+ """Change the name of the shape
1749
+
1750
+ Parameters
1751
+ ----------
1752
+ shape :
1753
+
1754
+ name :
1755
+
1756
+
1757
+ Returns
1758
+ -------
1759
+
1760
+ """
1761
+ cmds.aliasAttr(name, shape.thing)
1762
+ shape.thing = "{0}.{1}".format(self.shapeNode, name)
1763
+
1764
+ @undoable
1765
+ def convertShapeToCorrective(self, shape):
1766
+ """
1767
+
1768
+ Parameters
1769
+ ----------
1770
+ shape :
1771
+
1772
+
1773
+ Returns
1774
+ -------
1775
+
1776
+ """
1777
+ pass
1778
+
1779
+ # Falloffs
1780
+ def createFalloff(self, name):
1781
+ """
1782
+
1783
+ Parameters
1784
+ ----------
1785
+ name :
1786
+
1787
+
1788
+ Returns
1789
+ -------
1790
+
1791
+ """
1792
+ pass # for eventual live splits
1793
+
1794
+ def duplicateFalloff(self, falloff, newFalloff, newName):
1795
+ """
1796
+
1797
+ Parameters
1798
+ ----------
1799
+ falloff :
1800
+
1801
+ newFalloff :
1802
+
1803
+ newName :
1804
+
1805
+
1806
+ Returns
1807
+ -------
1808
+
1809
+ """
1810
+ pass # for eventual live splits
1811
+
1812
+ def deleteFalloff(self, falloff):
1813
+ """
1814
+
1815
+ Parameters
1816
+ ----------
1817
+ falloff :
1818
+
1819
+
1820
+ Returns
1821
+ -------
1822
+
1823
+ """
1824
+ pass # for eventual live splits
1825
+
1826
+ def setFalloffData(
1827
+ self, falloff, splitType, axis, minVal, minHandle, maxHandle, maxVal, mapName
1828
+ ):
1829
+ """
1830
+
1831
+ Parameters
1832
+ ----------
1833
+ falloff :
1834
+
1835
+ splitType :
1836
+
1837
+ axis :
1838
+
1839
+ minVal :
1840
+
1841
+ minHandle :
1842
+
1843
+ maxHandle :
1844
+
1845
+ maxVal :
1846
+
1847
+ mapName :
1848
+
1849
+
1850
+ Returns
1851
+ -------
1852
+
1853
+ """
1854
+ pass # for eventual live splits
1855
+
1856
+ def getFalloffThing(self, falloff):
1857
+ """
1858
+
1859
+ Parameters
1860
+ ----------
1861
+ falloff :
1862
+
1863
+
1864
+ Returns
1865
+ -------
1866
+
1867
+ """
1868
+ shape = cmds.listRelatives(self.mesh, shapes=True)[0]
1869
+ return shape + "." + falloff.name
1870
+
1871
+ # Sliders
1872
+ @undoable
1873
+ def createSlider(self, slider):
1874
+ """
1875
+
1876
+ Parameters
1877
+ ----------
1878
+ slider :
1879
+
1880
+
1881
+ Returns
1882
+ -------
1883
+
1884
+ """
1885
+ index = slider.simplex.sliders.index(slider)
1886
+ cmds.addAttr(
1887
+ self.ctrl,
1888
+ longName=slider.name,
1889
+ attributeType="double",
1890
+ keyable=True,
1891
+ min=slider.minValue * self.sliderMul,
1892
+ max=slider.maxValue * self.sliderMul,
1893
+ )
1894
+ thing = "{0}.{1}".format(self.ctrl, slider.name)
1895
+ cmds.connectAttr(thing, "{0}.sliders[{1}]".format(self.op, index))
1896
+ return thing
1897
+
1898
+ @undoable
1899
+ def renameSlider(self, slider, name):
1900
+ """Set the name of a slider
1901
+
1902
+ Parameters
1903
+ ----------
1904
+ slider :
1905
+
1906
+ name :
1907
+
1908
+
1909
+ Returns
1910
+ -------
1911
+
1912
+ """
1913
+ vals = [v.value for v in slider.prog.pairs]
1914
+ cnx = cmds.listConnections(
1915
+ slider.thing, plugs=True, source=False, destination=True
1916
+ )
1917
+ cmds.deleteAttr(slider.thing)
1918
+ cmds.addAttr(
1919
+ self.ctrl,
1920
+ longName=name,
1921
+ attributeType="double",
1922
+ keyable=True,
1923
+ min=self.sliderMul * min(vals),
1924
+ max=self.sliderMul * max(vals),
1925
+ )
1926
+ newThing = "{0}.{1}".format(self.ctrl, name)
1927
+ slider.thing = newThing
1928
+ for c in cnx:
1929
+ cmds.connectAttr(newThing, c)
1930
+
1931
+ @undoable
1932
+ def setSliderRange(self, slider):
1933
+ """Set the range of a slider
1934
+
1935
+ Parameters
1936
+ ----------
1937
+ slider :
1938
+
1939
+
1940
+ Returns
1941
+ -------
1942
+
1943
+ """
1944
+ vals = [v.value for v in slider.prog.pairs]
1945
+ attrName = "{0}.{1}".format(self.ctrl, slider.name)
1946
+ cmds.addAttr(
1947
+ attrName,
1948
+ edit=True,
1949
+ min=self.sliderMul * min(vals),
1950
+ max=self.sliderMul * max(vals),
1951
+ )
1952
+
1953
+ @undoable
1954
+ def deleteSlider(self, toDelSlider):
1955
+ """
1956
+
1957
+ Parameters
1958
+ ----------
1959
+ toDelSlider :
1960
+
1961
+
1962
+ Returns
1963
+ -------
1964
+
1965
+ """
1966
+ cmds.deleteAttr(toDelSlider.thing)
1967
+
1968
+ # Rebuild the slider connections in the proper order
1969
+ # Get the sliders connections
1970
+ cnxs = cmds.listConnections(
1971
+ self.op, plugs=True, source=True, destination=False, connections=True
1972
+ )
1973
+ for i, cnx in enumerate(cnxs):
1974
+ if cnx.startswith("{0}.sliders".format(self.op)):
1975
+ cmds.disconnectAttr(cnxs[i + 1], cnxs[i])
1976
+
1977
+ for i, slider in enumerate(self.simplex.sliders):
1978
+ cmds.connectAttr(slider.thing, "{0}.sliders[{1}]".format(self.op, i))
1979
+
1980
+ @undoable
1981
+ def addProgFalloff(self, prog, falloff):
1982
+ """
1983
+
1984
+ Parameters
1985
+ ----------
1986
+ prog :
1987
+
1988
+ falloff :
1989
+
1990
+
1991
+ Returns
1992
+ -------
1993
+
1994
+ """
1995
+ pass # for eventual live splits
1996
+
1997
+ @undoable
1998
+ def removeProgFalloff(self, prog, falloff):
1999
+ """
2000
+
2001
+ Parameters
2002
+ ----------
2003
+ prog :
2004
+
2005
+ falloff :
2006
+
2007
+
2008
+ Returns
2009
+ -------
2010
+
2011
+ """
2012
+ pass # for eventual live splits
2013
+
2014
+ @undoable
2015
+ def setSlidersWeights(self, sliders, weights):
2016
+ """Set the weight of a slider. This does not change the definition
2017
+
2018
+ Parameters
2019
+ ----------
2020
+ sliders :
2021
+
2022
+ weights :
2023
+
2024
+
2025
+ Returns
2026
+ -------
2027
+
2028
+ """
2029
+ for slider, weight in zip(sliders, weights):
2030
+ try:
2031
+ cmds.setAttr(slider.thing, weight)
2032
+ except RuntimeError:
2033
+ # Probably locked or connected. Just skip it
2034
+ pass
2035
+
2036
+ @undoable
2037
+ def setSliderWeight(self, slider, weight):
2038
+ """
2039
+
2040
+ Parameters
2041
+ ----------
2042
+ slider :
2043
+
2044
+ weight :
2045
+
2046
+
2047
+ Returns
2048
+ -------
2049
+
2050
+ """
2051
+ try:
2052
+ cmds.setAttr(slider.thing, weight)
2053
+ except RuntimeError:
2054
+ # Probably locked or connected. Just skip it
2055
+ pass
2056
+
2057
+ @undoable
2058
+ def updateSlidersRange(self, sliders):
2059
+ """
2060
+
2061
+ Parameters
2062
+ ----------
2063
+ sliders :
2064
+
2065
+
2066
+ Returns
2067
+ -------
2068
+
2069
+ """
2070
+ for slider in sliders:
2071
+ vals = [v.value for v in slider.prog.pairs]
2072
+ cmds.addAttr(
2073
+ slider.thing,
2074
+ edit=True,
2075
+ min=min(vals) * self.sliderMul,
2076
+ max=max(vals) * self.sliderMul,
2077
+ )
2078
+
2079
+ def _doesDeltaExist(self, combo, target):
2080
+ """
2081
+
2082
+ Parameters
2083
+ ----------
2084
+ combo :
2085
+
2086
+ target :
2087
+
2088
+
2089
+ Returns
2090
+ -------
2091
+
2092
+ """
2093
+ dshape = "{0}_DeltaShape".format(combo.name)
2094
+ if not cmds.ls(dshape):
2095
+ return None
2096
+ par = cmds.listRelatives(dshape, allParents=1)
2097
+ if not par:
2098
+ # there is apparently a transform object with the name
2099
+ return None
2100
+
2101
+ par = cmds.ls(par[0], absoluteName=1)
2102
+ tar = cmds.ls(target, absoluteName=1)
2103
+
2104
+ if par != tar:
2105
+ # the shape exists under a different transform ... ugh
2106
+ return None
2107
+ return par + "|" + dshape
2108
+
2109
+ def _clearShapes(self, item, doOrig=False):
2110
+ """
2111
+
2112
+ Parameters
2113
+ ----------
2114
+ item :
2115
+
2116
+ doOrig :
2117
+ (Default value = False)
2118
+
2119
+ Returns
2120
+ -------
2121
+
2122
+ """
2123
+ aname = cmds.ls(item, long=1)[0]
2124
+ shapes = cmds.ls(cmds.listRelatives(item, shapes=1), long=1)
2125
+ baseName = aname.split("|")[-1]
2126
+ baseName, digits = split_trailing_digits(baseName)
2127
+
2128
+ primary = "{0}|{1}Shape{2}".format(aname, baseName, digits)
2129
+
2130
+ origs = []
2131
+ others = []
2132
+ for shape in shapes:
2133
+ base, digits = split_trailing_digits(shape)
2134
+ if base.endswith('Orig'):
2135
+ origs.append(shape)
2136
+ else:
2137
+ others.append(shape)
2138
+
2139
+ for shape in others:
2140
+ if shape == primary:
2141
+ continue
2142
+ cmds.delete(shape)
2143
+
2144
+ if doOrig:
2145
+ cmds.delete(origs)
2146
+ else:
2147
+ # Don't delete the first orig
2148
+ if len(origs) > 1:
2149
+ origs = sorted(origs)
2150
+ cmds.delete(origs[1:])
2151
+
2152
+ @undoable
2153
+ def forceRebuildSliderConnections(self):
2154
+ """ """
2155
+ self._rebuildSliderConnections()
2156
+
2157
+ def _rebuildSliderConnections(self):
2158
+ # disconnect all outputs from the ctrl
2159
+ rcnx = cmds.listConnections(
2160
+ self.ctrl, source=False, plugs=True, connections=True
2161
+ )
2162
+ for i in range(0, len(rcnx), 2):
2163
+ src, dst = rcnx[i], rcnx[i + 1]
2164
+ if cmds.getAttr(src, type=True) != "double":
2165
+ # only disconnect doubles
2166
+ continue
2167
+ cmds.disconnectAttr(src, dst)
2168
+
2169
+ # Reconnect by name
2170
+ for i, sli in enumerate(self.simplex.sliders):
2171
+ thing = self.getSliderThing(sli.name)
2172
+ cmds.connectAttr(thing, self.op + ".sliders[{0}]".format(i))
2173
+
2174
+ # Combos
2175
+ def _reparentDeltaShapes(self, par, nodeDict, bsNode, toDelete=None):
2176
+ """Reparent and clean up a single-transform delta system
2177
+
2178
+ Put all the relevant shape nodes from the nodeDict under the par,
2179
+ and rename the shapes to maya's convention. Then build a callback
2180
+ to ensure the blendshape node isn't left floating
2181
+
2182
+ par: The parent transform node
2183
+ nodeDict: A {simpleName: node} dictionary.
2184
+ bsNode: The blendshape node.
2185
+ toDelete: Any extra nodes to delte after all the node twiddling
2186
+
2187
+ Parameters
2188
+ ----------
2189
+ par :
2190
+
2191
+ nodeDict :
2192
+
2193
+ bsNode :
2194
+
2195
+ toDelete :
2196
+ (Default value = None)
2197
+
2198
+ Returns
2199
+ -------
2200
+
2201
+ """
2202
+ # Get the shapes and origs
2203
+ shapeDict = {}
2204
+ origDict = {}
2205
+
2206
+ for name, node in nodeDict.items():
2207
+ shape = cmds.listRelatives(node, noIntermediate=1, shapes=1)[0]
2208
+ shape = cmds.ls(shape, absoluteName=1)[0]
2209
+ if shape:
2210
+ shapeDict[name] = shape
2211
+
2212
+ orig = shape + "Orig"
2213
+ orig = cmds.ls(orig)
2214
+ if orig:
2215
+ origDict[name] = orig
2216
+
2217
+ for name in nodeDict:
2218
+ for d, fmt in [(shapeDict, "{0}Shape{1}"), (origDict, "{0}Shape{1}Orig")]:
2219
+ shape = d.get(name)
2220
+ if shape is None:
2221
+ continue
2222
+ shapeUUID = cmds.ls(shape, uuid=1)[0]
2223
+ cmds.parent(shape, par, shape=True, relative=True)
2224
+ newShape = cmds.rename(cmds.ls(shapeUUID)[0], fmt.format(par, name))
2225
+ d[name] = newShape
2226
+ cmds.setAttr(newShape + ".intermediateObject", 1)
2227
+ cmds.hide(newShape)
2228
+
2229
+ cmds.delete(nodeDict[name])
2230
+
2231
+ if toDelete:
2232
+ cmds.delete(toDelete)
2233
+
2234
+ # Use the simplexDelete message attribute to keep track of what nodes
2235
+ # will need to be delete-linked when the file is reopened
2236
+ sdNode = par + ".simplexDelete"
2237
+ if not cmds.ls(sdNode):
2238
+ cmds.addAttr(par, longName="simplexDelete", attributeType="message")
2239
+ cmds.connectAttr(bsNode + ".message", sdNode)
2240
+
2241
+ # build the callback setup so the blendshape is deleted with the delta setup
2242
+ # along with a persistent scriptjob
2243
+ buildDeleterCallback(par, bsNode)
2244
+ buildDeleterScriptJob()
2245
+
2246
+ return shapeDict
2247
+
2248
+ def _createTravDelta(self, trav, target, tVal, doReparent=True):
2249
+ """Part of the traversal extraction process.
2250
+ Very similar to the combo extraction
2251
+
2252
+ Parameters
2253
+ ----------
2254
+ trav :
2255
+
2256
+ target :
2257
+
2258
+ tVal :
2259
+
2260
+
2261
+ Returns
2262
+ -------
2263
+
2264
+ """
2265
+ exists = self._doesDeltaExist(trav, target)
2266
+ if exists is not None:
2267
+ return exists
2268
+
2269
+ # Traversals *MAY* depend on floaters, but that's complicated
2270
+ # I'm just gonna ignore them for now
2271
+ floatShapes = [i.thing for i in self.simplex.getFloatingShapes()]
2272
+
2273
+ # Get all traversal shapes
2274
+ tShapes = []
2275
+ for oTrav in self.simplex.traversals:
2276
+ tShapes.extend([i.thing for i in oTrav.prog.getShapes()])
2277
+
2278
+ with disconnected(self.op) as cnx:
2279
+ sliderCnx = cnx[self.op]
2280
+
2281
+ # zero all slider vals on the op
2282
+ for a in sliderCnx.values():
2283
+ cmds.setAttr(a, 0.0)
2284
+
2285
+ with disconnected(floatShapes + tShapes):
2286
+ # pull out the rest shape
2287
+ rest = cmds.duplicate(self.mesh, name="{0}_Rest".format(trav.name))[0]
2288
+
2289
+ sliDict = {}
2290
+ for pair in trav.startPoint.pairs:
2291
+ sliDict[pair.slider] = [pair.value]
2292
+ for pair in trav.endPoint.pairs:
2293
+ sliDict[pair.slider].append(pair.value)
2294
+
2295
+ for slider, (start, end) in sliDict.items():
2296
+ vv = start + tVal * (end - start)
2297
+ cmds.setAttr(sliderCnx[slider.thing], vv)
2298
+
2299
+ deltaObj = cmds.duplicate(
2300
+ self.mesh, name="{0}_Delta".format(trav.name)
2301
+ )[0]
2302
+ base = cmds.duplicate(deltaObj, name="{0}_Base".format(trav.name))[0]
2303
+
2304
+ # clear out all non-primary shapes so we don't have those 'Orig1' things floating around
2305
+ for item in [rest, deltaObj, base]:
2306
+ self._clearShapes(item, doOrig=True)
2307
+
2308
+ # Build the delta blendshape setup
2309
+ bs = cmds.blendShape(deltaObj, name="{0}_DeltaBS".format(trav.name))[0]
2310
+ cmds.blendShape(bs, edit=True, target=(deltaObj, 0, target, 1.0))
2311
+ cmds.blendShape(bs, edit=True, target=(deltaObj, 1, base, 1.0))
2312
+ cmds.blendShape(bs, edit=True, target=(deltaObj, 2, rest, 1.0))
2313
+ cmds.setAttr("{0}.{1}".format(bs, target), 1.0)
2314
+ cmds.setAttr("{0}.{1}".format(bs, base), 1.0)
2315
+ cmds.setAttr("{0}.{1}".format(bs, rest), 1.0)
2316
+
2317
+ # Cleanup
2318
+ if doReparent:
2319
+ nodeDict = {"Delta": deltaObj}
2320
+ repDict = self._reparentDeltaShapes(target, nodeDict, bs, [rest, base])
2321
+ return repDict["Delta"]
2322
+ return deltaObj
2323
+
2324
+ @undoable
2325
+ def extractTraversalShape(self, trav, shape, live=True, offset=10.0):
2326
+ """Extract a shape from a Traversal progression
2327
+
2328
+ Parameters
2329
+ ----------
2330
+ trav :
2331
+ shape :
2332
+ live :
2333
+ (Default value = True)
2334
+ offset :
2335
+ (Default value = 10.0)
2336
+
2337
+ Returns
2338
+ -------
2339
+
2340
+ """
2341
+ floatShapes = self.simplex.getFloatingShapes()
2342
+ floatShapes = [i.thing for i in floatShapes]
2343
+
2344
+ shapeIdx = trav.prog.getShapeIndex(shape)
2345
+ val = trav.prog.pairs[shapeIdx].value
2346
+
2347
+ # TODO: Do traversals interact? Should I turn off any other traversals?
2348
+ # For now, no, but it may be a thing
2349
+ # tShapes = []
2350
+ # for oTrav in self.simplex.traversals:
2351
+ # if oTrav is trav: continue
2352
+ # tShapes.extend([i.thing for i in oTrav.prog.getShapes()])
2353
+
2354
+ with disconnected(self.op) as cnx:
2355
+ sliderCnx = cnx[self.op]
2356
+ # zero all slider vals on the op
2357
+ for a in sliderCnx.values():
2358
+ cmds.setAttr(a, 0.0)
2359
+
2360
+ with disconnected(floatShapes): # tShapes
2361
+ sliDict = {}
2362
+ for pair in trav.startPoint.pairs:
2363
+ sliDict[pair.slider] = [pair.value]
2364
+ for pair in trav.endPoint.pairs:
2365
+ sliDict[pair.slider].append(pair.value)
2366
+
2367
+ for slider, (start, end) in sliDict.items():
2368
+ vv = start + val * (end - start)
2369
+ cmds.setAttr(sliderCnx[slider.thing], vv)
2370
+
2371
+ extracted = cmds.duplicate(
2372
+ self.mesh, name="{0}_Extract".format(shape.name)
2373
+ )
2374
+ extracted = extracted[0]
2375
+ self._clearShapes(extracted)
2376
+ cmds.xform(extracted, relative=True, translation=(offset, 0, 0))
2377
+ if live:
2378
+ self.connectTraversalShape(trav, shape, extracted, live=live, delete=False)
2379
+ cmds.select(extracted)
2380
+ return extracted
2381
+
2382
+ @undoable
2383
+ def connectTraversalShape(self, trav, shape, mesh=None, live=True, delete=False):
2384
+ """Connect a shape into a Traversal progression
2385
+
2386
+ Parameters
2387
+ ----------
2388
+ trav :
2389
+
2390
+ shape :
2391
+
2392
+ mesh :
2393
+ (Default value = None)
2394
+ live :
2395
+ (Default value = True)
2396
+ delete :
2397
+ (Default value = False)
2398
+
2399
+ Returns
2400
+ -------
2401
+
2402
+ """
2403
+ if mesh is None:
2404
+ attrName = cmds.attributeName(shape.thing, long=True)
2405
+ mesh = "{0}_Extract".format(attrName)
2406
+
2407
+ chk = cmds.ls(mesh)
2408
+ if not chk:
2409
+ return
2410
+ if len(chk) > 1:
2411
+ msg = "Multiple objects with the same name found in file:\n"
2412
+ msg += '\n'.join(chk)
2413
+ raise ValueError(msg)
2414
+
2415
+ shapeIdx = trav.prog.getShapeIndex(shape)
2416
+ tVal = trav.prog.pairs[shapeIdx].value
2417
+ delta = self._createTravDelta(trav, mesh, tVal)
2418
+
2419
+ if live:
2420
+ self.connectShape(shape, delta, live, delete)
2421
+
2422
+ if delete:
2423
+ cmds.delete(mesh)
2424
+
2425
+ def _createComboDelta(self, combo, target, tVal, doReparent=True):
2426
+ """Part of the combo extraction process.
2427
+ Combo shapes are fixit shapes added on top of any sliders.
2428
+ This means that the actual combo-shape by itself will not look good by itself,
2429
+ and that's bad for artist interaction.
2430
+ So we must create a setup to take the final sculpted shape, and subtract
2431
+ the any direct slider deformations to get the actual "combo shape" as a delta
2432
+ It is this delta shape that is then plugged into the system
2433
+
2434
+ Parameters
2435
+ ----------
2436
+ combo :
2437
+
2438
+ target :
2439
+
2440
+ tVal :
2441
+
2442
+
2443
+ Returns
2444
+ -------
2445
+
2446
+ """
2447
+ exists = self._doesDeltaExist(combo, target)
2448
+ if exists is not None:
2449
+ return exists
2450
+
2451
+ # get floaters
2452
+ # As floaters can appear anywhere along any combo, they must
2453
+ # always be evaluated in isolation. For this reason, we will
2454
+ # always disconnect all floaters
2455
+ floatShapes = [i.thing for i in self.simplex.getFloatingShapes()]
2456
+
2457
+ # get my shapes
2458
+ myShapes = [i.thing for i in combo.prog.getShapes()]
2459
+
2460
+ with disconnected([self.op] + floatShapes + myShapes) as cnx:
2461
+ sliderCnx = cnx[self.op]
2462
+
2463
+ # zero all slider vals on the op
2464
+ for a in sliderCnx.values():
2465
+ cmds.setAttr(a, 0.0)
2466
+
2467
+ # pull out the rest shape
2468
+ rest = cmds.duplicate(self.mesh, name="{0}_Rest".format(combo.name))[0]
2469
+
2470
+ # set the combo values
2471
+ for pair in combo.pairs:
2472
+ cmds.setAttr(sliderCnx[pair.slider.thing], pair.value * tVal)
2473
+
2474
+ # Get the resulting slider values for later
2475
+ # weightPairs = []
2476
+ # self.shapeNode = None # the deformer object
2477
+
2478
+ deltaObj = cmds.duplicate(self.mesh, name="{0}_Delta".format(combo.name))[0]
2479
+ base = cmds.duplicate(deltaObj, name="{0}_Base".format(combo.name))[0]
2480
+
2481
+ # clear out all non-primary shapes so we don't have those 'Orig1' things floating around
2482
+ for item in [rest, deltaObj, base]:
2483
+ self._clearShapes(item, doOrig=True)
2484
+
2485
+ # Build the delta blendshape setup
2486
+ bs = cmds.blendShape(deltaObj, name="{0}_DeltaBS".format(combo.name))[0]
2487
+ cmds.blendShape(bs, edit=True, target=(deltaObj, 0, target, 1.0))
2488
+ cmds.blendShape(bs, edit=True, target=(deltaObj, 1, base, 1.0))
2489
+ cmds.blendShape(bs, edit=True, target=(deltaObj, 2, rest, 1.0))
2490
+ cmds.setAttr("{0}.{1}".format(bs, target), 1.0)
2491
+ cmds.setAttr("{0}.{1}".format(bs, base), 1.0)
2492
+ cmds.setAttr("{0}.{1}".format(bs, rest), 1.0)
2493
+
2494
+ # Cleanup
2495
+ if doReparent:
2496
+ nodeDict = {"Delta": deltaObj}
2497
+ repDict = self._reparentDeltaShapes(target, nodeDict, bs, [rest, base])
2498
+ return repDict["Delta"]
2499
+ return deltaObj
2500
+
2501
+ @undoable
2502
+ def extractComboShape(self, combo, shape, live=True, offset=10.0):
2503
+ """Extract a shape from a combo progression
2504
+
2505
+ Parameters
2506
+ ----------
2507
+ combo :
2508
+
2509
+ shape :
2510
+
2511
+ live :
2512
+ (Default value = True)
2513
+ offset :
2514
+ (Default value = 10.0)
2515
+
2516
+ Returns
2517
+ -------
2518
+
2519
+ """
2520
+ floatShapes = self.simplex.getFloatingShapes()
2521
+ floatShapes = [i.thing for i in floatShapes]
2522
+
2523
+ shapeIdx = combo.prog.getShapeIndex(shape)
2524
+ tVal = combo.prog.pairs[shapeIdx].value
2525
+
2526
+ with disconnected(self.op) as cnx:
2527
+ sliderCnx = cnx[self.op]
2528
+ # zero all slider vals on the op
2529
+ for a in sliderCnx.values():
2530
+ cmds.setAttr(a, 0.0)
2531
+
2532
+ with disconnected(floatShapes):
2533
+ # set the combo values
2534
+ for pair in combo.pairs:
2535
+ cmds.setAttr(sliderCnx[pair.slider.thing], pair.value * tVal)
2536
+
2537
+ extracted = cmds.duplicate(
2538
+ self.mesh, name="{0}_Extract".format(shape.name)
2539
+ )[0]
2540
+
2541
+ self._clearShapes(extracted)
2542
+ cmds.xform(extracted, relative=True, translation=(offset, 0, 0))
2543
+
2544
+ if live:
2545
+ self.connectComboShape(combo, shape, extracted, live=live, delete=False)
2546
+
2547
+ cmds.select(extracted)
2548
+ return extracted
2549
+
2550
+ @undoable
2551
+ def connectComboShape(self, combo, shape, mesh=None, live=True, delete=False):
2552
+ """Connect a shape into a combo progression
2553
+
2554
+ Parameters
2555
+ ----------
2556
+ combo :
2557
+
2558
+ shape :
2559
+
2560
+ mesh :
2561
+ (Default value = None)
2562
+ live :
2563
+ (Default value = True)
2564
+ delete :
2565
+ (Default value = False)
2566
+
2567
+ Returns
2568
+ -------
2569
+
2570
+ """
2571
+ if mesh is None:
2572
+ attrName = cmds.attributeName(shape.thing, long=True)
2573
+ mesh = "{0}_Extract".format(attrName)
2574
+
2575
+ chk = cmds.ls(mesh)
2576
+ if not chk:
2577
+ return
2578
+ if len(chk) > 1:
2579
+ msg = "Multiple objects with the same name found in file:\n"
2580
+ msg += '\n'.join(chk)
2581
+ raise ValueError(msg)
2582
+ mesh = chk[0]
2583
+
2584
+ progShapeIdx = combo.prog.getShapeIndex(shape)
2585
+ tVal = combo.prog.pairs[progShapeIdx].value
2586
+
2587
+ delta = self._createComboDelta(combo, mesh, tVal)
2588
+ if live:
2589
+ self.connectShape(shape, delta, live, delete)
2590
+
2591
+ if delete:
2592
+ cmds.delete(mesh)
2593
+
2594
+ @classmethod
2595
+ def setDisabled(cls, op):
2596
+ """
2597
+
2598
+ Parameters
2599
+ ----------
2600
+ op :
2601
+
2602
+
2603
+ Returns
2604
+ -------
2605
+
2606
+ """
2607
+ bss = list(set(cmds.listConnections(op, type="blendShape")))
2608
+ helpers = []
2609
+ for bs in bss:
2610
+ prop = "{0}.envelope".format(bs)
2611
+ val = cmds.getAttr(prop)
2612
+ cmds.setAttr(prop, 0.0)
2613
+ if val != 0.0:
2614
+ helpers.append((prop, val))
2615
+ return helpers
2616
+
2617
+ @classmethod
2618
+ def reEnable(cls, helpers):
2619
+ """
2620
+
2621
+ Parameters
2622
+ ----------
2623
+ helpers :
2624
+
2625
+
2626
+ Returns
2627
+ -------
2628
+
2629
+ """
2630
+ for prop, val in helpers:
2631
+ cmds.setAttr(prop, val)
2632
+
2633
+ @undoable
2634
+ def renameCombo(self, combo, name):
2635
+ """Set the name of a Combo
2636
+
2637
+ Parameters
2638
+ ----------
2639
+ combo :
2640
+
2641
+ name :
2642
+
2643
+
2644
+ Returns
2645
+ -------
2646
+
2647
+ """
2648
+ pass
2649
+
2650
+ # Data Access
2651
+ @classmethod
2652
+ def getSimplexOperators(cls):
2653
+ """ """
2654
+ return cmds.ls(type="simplex_maya")
2655
+
2656
+ @classmethod
2657
+ def getSimplexOperatorsByName(cls, name):
2658
+ """
2659
+
2660
+ Parameters
2661
+ ----------
2662
+ name :
2663
+
2664
+
2665
+ Returns
2666
+ -------
2667
+ type
2668
+
2669
+
2670
+ """
2671
+ return cmds.ls(name, type="simplex_maya")
2672
+
2673
+ @classmethod
2674
+ def getSimplexOperatorsOnObject(cls, thing):
2675
+ """
2676
+
2677
+ Parameters
2678
+ ----------
2679
+ thing :
2680
+
2681
+
2682
+ Returns
2683
+ -------
2684
+ type
2685
+
2686
+
2687
+ """
2688
+ ops = cmds.ls(type="simplex_maya")
2689
+ out = []
2690
+ for op in ops:
2691
+ shapeNode = cmds.listConnections(
2692
+ "{0}.{1}".format(op, "shapeMsg"), source=True, destination=False
2693
+ )
2694
+ if not shapeNode:
2695
+ continue
2696
+
2697
+ # Now that I've got the connected blendshape node, I can check the deformer history
2698
+ # to see if I find it. Eventually, I should probably set this up to deal with
2699
+ # multi-objects, or branched hierarchies. But for now, it works
2700
+ if shapeNode[0] in (cmds.listHistory(thing, pruneDagObjects=True) or []):
2701
+ out.append(op)
2702
+ return out
2703
+
2704
+ @classmethod
2705
+ def getSimplexString(cls, op):
2706
+ """
2707
+
2708
+ Parameters
2709
+ ----------
2710
+ op :
2711
+
2712
+
2713
+ Returns
2714
+ -------
2715
+ type
2716
+
2717
+
2718
+ """
2719
+ return cmds.getAttr(op + ".definition")
2720
+
2721
+ @classmethod
2722
+ def getSimplexStringOnThing(cls, thing, systemName):
2723
+ """
2724
+
2725
+ Parameters
2726
+ ----------
2727
+ thing :
2728
+
2729
+ systemName :
2730
+
2731
+
2732
+ Returns
2733
+ -------
2734
+ type
2735
+
2736
+
2737
+ """
2738
+ ops = DCC.getSimplexOperatorsOnObject(thing)
2739
+ for op in ops:
2740
+ js = DCC.getSimplexString(op)
2741
+ jdict = json.loads(js)
2742
+ if jdict["systemName"] == systemName:
2743
+ return js
2744
+ return None
2745
+
2746
+ @classmethod
2747
+ def setSimplexString(cls, op, val):
2748
+ """
2749
+
2750
+ Parameters
2751
+ ----------
2752
+ op :
2753
+
2754
+ val :
2755
+
2756
+
2757
+ Returns
2758
+ -------
2759
+ type
2760
+
2761
+
2762
+ """
2763
+ return cmds.setAttr(op + ".definition", val, type="string")
2764
+
2765
+ @classmethod
2766
+ def selectObject(cls, thing):
2767
+ """Select an object in the DCC
2768
+
2769
+ Parameters
2770
+ ----------
2771
+ thing :
2772
+
2773
+
2774
+ Returns
2775
+ -------
2776
+
2777
+ """
2778
+ cmds.select([thing])
2779
+
2780
+ def selectCtrl(self):
2781
+ """Select the system's control object"""
2782
+ if self.ctrl:
2783
+ self.selectObject(self.ctrl)
2784
+
2785
+ @classmethod
2786
+ def getObjectByName(cls, name):
2787
+ """
2788
+
2789
+ Parameters
2790
+ ----------
2791
+ name :
2792
+
2793
+
2794
+ Returns
2795
+ -------
2796
+ type
2797
+
2798
+
2799
+ """
2800
+ objs = cmds.ls(name)
2801
+ if not objs:
2802
+ return None
2803
+ if len(objs) > 1:
2804
+ raise ValueError("Multiple objects with the same name found")
2805
+ return objs[0]
2806
+
2807
+ @classmethod
2808
+ def getObjectName(cls, thing):
2809
+ """
2810
+
2811
+ Parameters
2812
+ ----------
2813
+ thing :
2814
+
2815
+
2816
+ Returns
2817
+ -------
2818
+ type
2819
+
2820
+
2821
+ """
2822
+ return thing
2823
+
2824
+ @classmethod
2825
+ def staticUndoOpen(cls):
2826
+ """ """
2827
+ cmds.undoInfo(chunkName="SimplexOperation", openChunk=True)
2828
+
2829
+ @classmethod
2830
+ def staticUndoClose(cls):
2831
+ """ """
2832
+ cmds.undoInfo(closeChunk=True)
2833
+
2834
+ def undoOpen(self):
2835
+ """ """
2836
+ if self.undoDepth == 0:
2837
+ self.staticUndoOpen()
2838
+ self.undoDepth += 1
2839
+
2840
+ def undoClose(self):
2841
+ """ """
2842
+ self.undoDepth -= 1
2843
+ if self.undoDepth == 0:
2844
+ self.staticUndoClose()
2845
+
2846
+ @classmethod
2847
+ def getPersistentFalloff(cls, thing):
2848
+ """
2849
+
2850
+ Parameters
2851
+ ----------
2852
+ thing :
2853
+
2854
+
2855
+ Returns
2856
+ -------
2857
+
2858
+ """
2859
+ return cls.getObjectName(thing)
2860
+
2861
+ @classmethod
2862
+ def loadPersistentFalloff(cls, thing):
2863
+ """
2864
+
2865
+ Parameters
2866
+ ----------
2867
+ thing :
2868
+
2869
+
2870
+ Returns
2871
+ -------
2872
+
2873
+ """
2874
+ return cls.getObjectByName(thing)
2875
+
2876
+ @classmethod
2877
+ def getPersistentShape(cls, thing):
2878
+ """
2879
+
2880
+ Parameters
2881
+ ----------
2882
+ thing :
2883
+
2884
+
2885
+ Returns
2886
+ -------
2887
+
2888
+ """
2889
+ return cls.getObjectName(thing)
2890
+
2891
+ @classmethod
2892
+ def loadPersistentShape(cls, thing):
2893
+ """
2894
+
2895
+ Parameters
2896
+ ----------
2897
+ thing :
2898
+
2899
+
2900
+ Returns
2901
+ -------
2902
+
2903
+ """
2904
+ return cls.getObjectByName(thing)
2905
+
2906
+ @classmethod
2907
+ def getPersistentSlider(cls, thing):
2908
+ """
2909
+
2910
+ Parameters
2911
+ ----------
2912
+ thing :
2913
+
2914
+
2915
+ Returns
2916
+ -------
2917
+
2918
+ """
2919
+ return cls.getObjectName(thing)
2920
+
2921
+ @classmethod
2922
+ def loadPersistentSlider(cls, thing):
2923
+ """
2924
+
2925
+ Parameters
2926
+ ----------
2927
+ thing :
2928
+
2929
+
2930
+ Returns
2931
+ -------
2932
+
2933
+ """
2934
+ return cls.getObjectByName(thing)
2935
+
2936
+ @classmethod
2937
+ def getSelectedObjects(cls):
2938
+ """ """
2939
+ # For maya, only return transform nodes
2940
+ return cmds.ls(sl=True, transforms=True)
2941
+
2942
+ @undoable
2943
+ def importObj(self, path):
2944
+ """
2945
+
2946
+ Parameters
2947
+ ----------
2948
+ path :
2949
+
2950
+
2951
+ Returns
2952
+ -------
2953
+
2954
+ """
2955
+ current = set(cmds.ls(transforms=True))
2956
+ cmds.file(path, i=True, type="OBJ", ignoreVersion=True)
2957
+ new = set(cmds.ls(transforms=True))
2958
+ shapes = set(cmds.ls(shapes=True))
2959
+ new = new - current - shapes
2960
+ imp = new.pop()
2961
+ return imp
2962
+
2963
+ @classmethod
2964
+ def _getDeformerChain(cls, chkObj):
2965
+ # Get a deformer chain
2966
+ memo = []
2967
+ while chkObj and chkObj not in memo:
2968
+ memo.append(chkObj)
2969
+
2970
+ typ = cmds.nodeType(chkObj)
2971
+ if typ == "mesh":
2972
+ cnx = cmds.listConnections(chkObj + ".inMesh") or [None]
2973
+ chkObj = cnx[0]
2974
+ elif typ == "groupParts":
2975
+ cnx = cmds.listConnections(
2976
+ chkObj + ".inputGeometry", destination=False, shapes=True
2977
+ ) or [None]
2978
+ chkObj = cnx[0]
2979
+ else:
2980
+ cnx = cmds.ls(chkObj, type="geometryFilter") or [None]
2981
+ chkObj = cnx[0]
2982
+ if chkObj: # we have a deformer
2983
+ cnx = cmds.listConnections(chkObj + ".input[0].inputGeometry") or [
2984
+ None
2985
+ ]
2986
+ chkObj = cnx[0]
2987
+ return memo
2988
+
2989
+ # Freezing stuff
2990
+ def primeShapes(self, combo):
2991
+ """Make sure the upstream shapes of this combo are primed and ready.
2992
+ Priming here means the deltas are stored and available on the blendshape node
2993
+ """
2994
+ # Maya doesn't populate the delta plugs on the blendshape node unless
2995
+ # you have a mesh connection while the value for that shape is turned to 1
2996
+ upstreams = []
2997
+ comboUps = self.simplex.getComboUpstreams(combo)
2998
+ for u in comboUps:
2999
+ upstreams.append(u.prog.getShapeAtValue(1.0))
3000
+ for pair in combo.pairs:
3001
+ sli, val = pair.slider, pair.value
3002
+ upstreams.append(sli.prog.getShapeAtValue(val))
3003
+
3004
+ with disconnected(self.shapeNode) as cnx:
3005
+ shapeCnx = cnx[self.shapeNode]
3006
+ for v in shapeCnx.values():
3007
+ cmds.setAttr(v, 0.0)
3008
+
3009
+ for shape in upstreams:
3010
+ cmds.setAttr(shape.thing, 1.0)
3011
+ try:
3012
+ # Make sure to check for any already incoming connections
3013
+ index = self.getShapeIndex(shape)
3014
+ tgn = "{0}.inputTarget[0].inputTargetGroup[{1}]".format(
3015
+ self.shapeNode, index
3016
+ )
3017
+ isConnected = cmds.listConnections(
3018
+ tgn, source=True, destination=False
3019
+ )
3020
+
3021
+ if not isConnected:
3022
+ shapeGeo = cmds.duplicate(self.mesh, name=shape.name)[0]
3023
+ shape.connectShape(mesh=shapeGeo, live=False, delete=True)
3024
+
3025
+ finally:
3026
+ cmds.setAttr(shape.thing, 0.0)
3027
+
3028
+ def getFreezeThing(self, combo):
3029
+ # If the blendshape shape has an incoming connection whose shape name
3030
+ # ends with 'FreezeShape' and the shape's parent is the ctrl
3031
+ ret = []
3032
+ shapes = combo.prog.getShapes()
3033
+ shapes = [i for i in shapes if not i.isRest]
3034
+
3035
+ shapePlugFmt = (
3036
+ ".inputTarget[{meshIdx}].inputTargetGroup[{shapeIdx}].inputTargetItem[6000]"
3037
+ )
3038
+
3039
+ for shape in shapes:
3040
+ shpIdx = self.getShapeIndex(shape)
3041
+ shpPlug = (
3042
+ self.shapeNode
3043
+ + shapePlugFmt.format(meshIdx=0, shapeIdx=shpIdx)
3044
+ + ".inputGeomTarget"
3045
+ )
3046
+
3047
+ cnx = cmds.listConnections(shpPlug, shapes=True, destination=False) or []
3048
+ for cc in cnx:
3049
+ if not cc.endswith("FreezeShape"):
3050
+ continue
3051
+ par = cmds.listRelatives(cc, parent=True)
3052
+ if par and par[0] == self.ctrl:
3053
+ # Can't use list history to get the chain because it's a pseudo-cycle
3054
+ ret.extend(self._getDeformerChain(cc))
3055
+
3056
+ if ret:
3057
+ self.primeShapes(combo)
3058
+
3059
+ return ret
3060
+
3061
+
3062
+ class SliderDispatch(QtCore.QObject):
3063
+ valueChanged = Signal()
3064
+
3065
+ def __init__(self, node, parent=None):
3066
+ super(SliderDispatch, self).__init__(parent)
3067
+ mObject = getMObject(node)
3068
+ self.callbackID = om.MNodeMessage.addAttributeChangedCallback(
3069
+ mObject, self.emitValueChanged
3070
+ )
3071
+
3072
+ def emitValueChanged(self, *args, **kwargs):
3073
+ self.valueChanged.emit()
3074
+
3075
+ def disconnectCallbacks(self):
3076
+ om.MMessage.removeCallback(self.callbackID)
3077
+ self.callbackID = None
3078
+
3079
+ def __del__(self):
3080
+ self.disconnectCallbacks()
3081
+
3082
+
3083
+ class Dispatch(QtCore.QObject):
3084
+ beforeNew = Signal()
3085
+ afterNew = Signal()
3086
+ beforeOpen = Signal()
3087
+ afterOpen = Signal()
3088
+ undo = Signal()
3089
+ redo = Signal()
3090
+
3091
+ def __init__(self, parent=None):
3092
+ super(Dispatch, self).__init__(parent)
3093
+ self.callbackIDs = []
3094
+ self.connectCallbacks()
3095
+
3096
+ def connectCallbacks(self):
3097
+ if self.callbackIDs:
3098
+ self.disconnectCallbacks()
3099
+
3100
+ self.callbackIDs.append(
3101
+ om.MSceneMessage.addCallback(
3102
+ om.MSceneMessage.kBeforeNew, self.emitBeforeNew
3103
+ )
3104
+ )
3105
+ self.callbackIDs.append(
3106
+ om.MSceneMessage.addCallback(om.MSceneMessage.kAfterNew, self.emitAfterNew)
3107
+ )
3108
+ self.callbackIDs.append(
3109
+ om.MSceneMessage.addCallback(
3110
+ om.MSceneMessage.kBeforeOpen, self.emitBeforeOpen
3111
+ )
3112
+ )
3113
+ self.callbackIDs.append(
3114
+ om.MSceneMessage.addCallback(
3115
+ om.MSceneMessage.kAfterOpen, self.emitAfterOpen
3116
+ )
3117
+ )
3118
+ self.callbackIDs.append(
3119
+ om.MEventMessage.addEventCallback("Undo", self.emitUndo)
3120
+ )
3121
+ self.callbackIDs.append(
3122
+ om.MEventMessage.addEventCallback("Redo", self.emitRedo)
3123
+ )
3124
+
3125
+ def disconnectCallbacks(self):
3126
+ for i in self.callbackIDs:
3127
+ om.MMessage.removeCallback(i)
3128
+ self.callbackIDs = []
3129
+
3130
+ def emitBeforeNew(self, *args, **kwargs):
3131
+ self.beforeNew.emit()
3132
+
3133
+ def emitAfterNew(self, *args, **kwargs):
3134
+ self.afterNew.emit()
3135
+
3136
+ def emitBeforeOpen(self, *args, **kwargs):
3137
+ self.beforeOpen.emit()
3138
+
3139
+ def emitAfterOpen(self, *args, **kwargs):
3140
+ self.afterOpen.emit()
3141
+
3142
+ def emitUndo(self, *args, **kwargs):
3143
+ self.undo.emit()
3144
+
3145
+ def emitRedo(self, *args, **kwargs):
3146
+ self.redo.emit()
3147
+
3148
+ def __del__(self):
3149
+ self.disconnectCallbacks()
3150
+
3151
+
3152
+ DISPATCH = Dispatch()
3153
+
3154
+
3155
+ def rootWindow():
3156
+ """Returns the currently active QT main window
3157
+ Only works for QT UI's like Maya
3158
+ """
3159
+ # for MFC apps there should be no root window
3160
+ window = None
3161
+ if QApplication.instance():
3162
+ inst = QApplication.instance()
3163
+ window = inst.activeWindow()
3164
+ # Ignore QSplashScreen's, they should never be considered the root window.
3165
+ if isinstance(window, QSplashScreen):
3166
+ return None
3167
+ # If the application does not have focus try to find A top level widget
3168
+ # that doesn't have a parent and is a QMainWindow or QDialog
3169
+ if window is None:
3170
+ windows = []
3171
+ dialogs = []
3172
+ for w in QApplication.instance().topLevelWidgets():
3173
+ if w.parent() is None:
3174
+ if isinstance(w, QMainWindow):
3175
+ windows.append(w)
3176
+ elif isinstance(w, QDialog):
3177
+ dialogs.append(w)
3178
+ if windows:
3179
+ window = windows[0]
3180
+ elif dialogs:
3181
+ window = dialogs[0]
3182
+
3183
+ # grab the root window
3184
+ if window:
3185
+ while True:
3186
+ parent = window.parent()
3187
+ if not parent:
3188
+ break
3189
+ if isinstance(parent, QSplashScreen):
3190
+ break
3191
+ window = parent
3192
+
3193
+ return window
3194
+
3195
+
3196
+ SIMPLEX_RESET_SCRIPTJOB = """
3197
+ import maya.cmds as cmds
3198
+ import maya.OpenMaya as om
3199
+
3200
+ def simplexDelCB(node, dgMod, clientData):
3201
+ xNode, dName = clientData
3202
+ dNode = getMObject(dName)
3203
+ if dNode and not dNode.isNull():
3204
+ dgMod.deleteNode(dNode)
3205
+
3206
+ def getMObject(name):
3207
+ selected = om.MSelectionList()
3208
+ try:
3209
+ selected.add(name, True)
3210
+ except RuntimeError:
3211
+ return None
3212
+ if selected.isEmpty():
3213
+ return None
3214
+ thing = om.MObject()
3215
+ selected.getDependNode(0, thing)
3216
+ return thing
3217
+
3218
+ # get all .simplexDelete message attributes
3219
+ delAttrs = cmds.ls("*.simplexDelete")
3220
+ if delAttrs:
3221
+ # get all their connections
3222
+ cnx = cmds.listConnections(delAttrs, plugs=True, connections=True, destination=False)
3223
+
3224
+ # Set up the deletion callback
3225
+ mmIds = []
3226
+ for i in range(0, len(cnx), 2):
3227
+ parName, delName = cmds.ls(cnx[i:i+2], long=True, objectsOnly=True)
3228
+ pNode = getMObject(parName)
3229
+ dNode = getMObject(delName)
3230
+ om.MNodeMessage.addNodeAboutToDeleteCallback(pNode, simplexDelCB, (dNode, delName))
3231
+ """
3232
+
3233
+
3234
+ def buildDeleterScriptJob():
3235
+ dcbName = "SimplexDeleterCallback"
3236
+ if not cmds.ls(dcbName):
3237
+ cmds.scriptNode(
3238
+ scriptType=1,
3239
+ beforeScript=SIMPLEX_RESET_SCRIPTJOB,
3240
+ name=dcbName,
3241
+ sourceType="python",
3242
+ )
3243
+
3244
+
3245
+ def simplexDelCB(_node, dgMod, clientData):
3246
+ _xNode, dName = clientData
3247
+ dNode = getMObject(dName)
3248
+ if dNode and not dNode.isNull():
3249
+ dgMod.deleteNode(dNode)
3250
+
3251
+
3252
+ def getMObject(name):
3253
+ selected = om.MSelectionList()
3254
+ try:
3255
+ selected.add(name, True)
3256
+ except RuntimeError:
3257
+ return None
3258
+ if selected.isEmpty():
3259
+ return None
3260
+ thing = om.MObject()
3261
+ selected.getDependNode(0, thing)
3262
+ return thing
3263
+
3264
+
3265
+ def buildDeleterCallback(parName, delName):
3266
+ pNode = getMObject(parName)
3267
+ dNode = getMObject(delName)
3268
+ idNum = om.MNodeMessage.addNodeAboutToDeleteCallback(
3269
+ pNode, simplexDelCB, (dNode, delName)
3270
+ )
3271
+ return idNum