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,1764 @@
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=missing-docstring,unused-argument,no-self-use
19
+ import copy
20
+ import itertools
21
+ import json
22
+
23
+ try:
24
+ import numpy as np
25
+ except ImportError:
26
+ np = None
27
+
28
+ from ..commands.alembicCommon import (
29
+ buildAlembicArchiveData,
30
+ getPointCount,
31
+ getSmpxArchiveData,
32
+ readFalloffData,
33
+ )
34
+ from ..interface import DCC, undoContext
35
+ from ..interface.dummyInterface import DCC as DummyDCC
36
+ from Qt.QtGui import QColor
37
+ from Qt.QtWidgets import QApplication
38
+ from ..utils import nested
39
+ from .combo import Combo, ComboPair
40
+ from .falloff import Falloff
41
+ from .group import Group
42
+ from .progression import ProgPair, Progression
43
+ from .shape import Shape
44
+ from .slider import Slider
45
+ from .stack import Stack, stackable
46
+ from .traversal import Traversal, TravPair
47
+
48
+
49
+ class Simplex(object):
50
+ """The main Top-level abstract object that controls an entire setup
51
+
52
+ Simplex objects contain and manage the entire hierarchy. They have methods
53
+ to import from and export to disk. Simplex objects also mange the connections
54
+ to the DCC and the UI, setting up connections with the undo stack, the dispatcher,
55
+ and all of the ui TreeModels.
56
+
57
+ Finally Simplex systems handle splitting, which will be covered more in depth
58
+ in the documentation for the split method.
59
+
60
+ """
61
+
62
+ classDepth = 0
63
+
64
+ def __init__(
65
+ self, name="", models=None, falloffModels=None, forceDummy=False, sliderMul=1.0
66
+ ):
67
+ """Constructor
68
+
69
+ Parameters
70
+ ----------
71
+ name : str, optional
72
+ The name of the new system. Defaults to ""
73
+ models : [QAbstractItemModel, ....], optional
74
+ The ui models that read this system. Defaults to []
75
+ falloffModels : [QAbstractItemModel, ....], optional
76
+ The ui models for managing Falloffs.
77
+ Defaults to []
78
+ forceDummy : bool, optional
79
+ When loading, don't make a connection to the actual DCC. Instead use the
80
+ "dummy" DCC. Defaults False
81
+ sliderMul : float, optional
82
+ A multiplier for the range of sliders. Simplex will only define values
83
+ between -1 and 1. This multiplier will let the attribute range in the DCC be larger so
84
+ animators can push the extremes
85
+
86
+ Returns
87
+ -------
88
+ """
89
+ self._name = name # The name of the system
90
+ self.sliders = [] # List of contained sliders
91
+ self.combos = [] # List of contained combos
92
+ self.traversals = [] # list of contained traversals
93
+ self.sliderGroups = [] # List of groups containing sliders
94
+ self.comboGroups = [] # List of groups containing combos
95
+ self.traversalGroups = [] # List of groups containing traversals
96
+ self.falloffs = [] # List of contained falloff objects
97
+ self.shapes = [] # List of contained shape objects
98
+ self.models = models or [] # connected Qt Item Models
99
+ self.falloffModels = falloffModels or [] # connected Qt Falloff Models
100
+ self.restShape = None # Name of the rest shape
101
+ self.clusterName = "Shape" # Name of the cluster (XSI use only)
102
+ self.expanded = {} # Am I expanded by model
103
+ self.comboExpanded = False # Am I expanded in the combo tree
104
+ self.sliderExpanded = False # Am I expanded in the slider tree
105
+ self.sliderMul = sliderMul
106
+ self.DCC = DummyDCC(self) if forceDummy else DCC(self) # Interface to the DCC
107
+ self.stack = Stack() # Reference to the Undo stack
108
+ self._extras = {} # Any extra key data to store in the output json
109
+ self._legacy = False # whether to write the legacy types
110
+
111
+ def __deepcopy__(self, memo):
112
+ """Gotta be really picky about what gets deepcopied.
113
+ Especially since I pretty much abuse the deepcopy mechanism to do splitting
114
+ Deep-copied systems have no reference to a UI, or a DCC
115
+ """
116
+ cls = self.__class__
117
+ result = cls.__new__(cls)
118
+ memo[id(self)] = result
119
+ for k, v in self.__dict__.items():
120
+ if k == "models":
121
+ # do not make a copy of the connected models
122
+ # a deepcopied simplex won't be connected to a UI
123
+ setattr(result, k, [])
124
+ elif k == "falloffModels":
125
+ # do not make a copy of the connected models
126
+ # a deepcopied simplex won't be connected to a UI
127
+ setattr(result, k, [])
128
+ elif k == "stack":
129
+ # Make a disabled stack for new simplex
130
+ s = Stack()
131
+ s.enabled = False
132
+ setattr(result, k, s)
133
+ elif k == "DCC":
134
+ # do not connect the deepcopied simplex to the DCC
135
+ # we will want to change it without affecting the current scene
136
+ # Requires the name be copied already
137
+ setattr(result, "_name", copy.deepcopy(self._name, memo)) # noqa: B010
138
+ if v.program == "dummy":
139
+ # If it's already a dummy, go ahead and just deepcopy
140
+ setattr(result, k, copy.deepcopy(v, memo))
141
+ else:
142
+ setattr(result, k, DummyDCC(result))
143
+ elif k == "expanded":
144
+ # do not make a copy of the expansion
145
+ # because it's keyed off the un-copied models
146
+ setattr(result, k, {})
147
+ else:
148
+ setattr(result, k, copy.deepcopy(v, memo))
149
+ return result
150
+
151
+ def _initValues(self):
152
+ """Re-initialize the variables to that of an empy system"""
153
+ self._name = "" # The name of the system
154
+ self.sliders = [] # List of contained sliders
155
+ self.combos = [] # List of contained combos
156
+ self.sliderGroups = [] # List of groups containing sliders
157
+ self.comboGroups = [] # List of groups containing combos
158
+ self.traversalGroups = [] # List of groups containing combos
159
+ self.falloffs = [] # List of contained falloff objects
160
+ self.shapes = [] # List of contained shape objects
161
+ self.restShape = None # Name of the rest shape
162
+ self.clusterName = "Shape" # Name of the cluster (XSI use only)
163
+ self.expanded = {} # Am I expanded? (Keep around for consistent interface)
164
+ self.color = QColor(128, 128, 128)
165
+ self.comboExpanded = False # Am I expanded in the combo tree
166
+ self.sliderExpanded = False # Am I expanded in the slider tree
167
+
168
+ # Alternate Constructors
169
+ @classmethod
170
+ def buildBaseObject(cls, smpxPath, name=None, forceDummy=False):
171
+ """Build the rest object from a .smpx file
172
+
173
+ Parameters
174
+ ----------
175
+ smpxPath : str
176
+ The path to the .smpx file
177
+ name : str, optional
178
+ The Name of the object to create. Defaults to the name of the simplex system
179
+
180
+ Returns
181
+ -------
182
+ : object
183
+ A reference to the DCC mesh
184
+
185
+ """
186
+ iarch, abcMesh, jsString = getSmpxArchiveData(smpxPath)
187
+ try:
188
+ if name is None:
189
+ js = json.loads(jsString)
190
+ name = js["systemName"]
191
+ if forceDummy:
192
+ return DummyDCC.buildRestAbc(abcMesh, name)
193
+ else:
194
+ return DCC.buildRestAbc(abcMesh, name)
195
+ finally:
196
+ del iarch
197
+
198
+ @classmethod
199
+ def buildEmptySystem(cls, thing, name, sliderMul=1.0, forceDummy=False):
200
+ """Create a new, empty system on a given mesh
201
+
202
+ Parameters
203
+ ----------
204
+ thing : object
205
+ The DCC mesh to build the system on
206
+ name : str
207
+ The name of the new Simplex system
208
+ sliderMul : float, optional
209
+ A multiplier for the range of sliders. Simplex will only define values
210
+ between -1 and 1. This multiplier will let the attribute range in the DCC be larger so
211
+ animators can push the extremes (Default value = 1.0)
212
+ forceDummy : bool, optional
213
+ When loading, don't make a connection to the actual DCC. Instead use the
214
+ "dummy" DCC. Defaults False
215
+
216
+ Returns
217
+ -------
218
+ : Simplex
219
+ A newly created Simplex system
220
+
221
+ """
222
+ self = cls(name, forceDummy=forceDummy, sliderMul=sliderMul)
223
+ self.DCC.loadNodes(self, thing, create=True)
224
+ self.restShape = Shape.buildRest(self)
225
+ return self
226
+
227
+ @classmethod
228
+ def buildSystemFromJsonString(
229
+ cls, jsString, thing=None, name=None, forceDummy=False, sliderMul=1.0, pBar=None
230
+ ):
231
+ """Build a system from a json encoded string
232
+
233
+ Parameters
234
+ ----------
235
+ jsString : str
236
+ The json encoded simplex definition
237
+ thing : object
238
+ The DCC mesh to build the system on (Default value = None)
239
+ name : str
240
+ The name of the new Simplex system (Default value = None)
241
+ forceDummy : bool
242
+ When loading, don't make a connection to the actual DCC. Instead use the
243
+ "dummy" DCC. Defaults False
244
+ sliderMul : float
245
+ A multiplier for the range of sliders. Simplex will only define values
246
+ between -1 and 1. This multiplier will let the attribute range in the DCC be larger so
247
+ animators can push the extremes (Default value = 1.0)
248
+ pBar : QProgressDialog, optional
249
+ If provided, display progress in this dialog
250
+
251
+ Returns
252
+ -------
253
+ : Simplex
254
+ A newly created Simplex system
255
+
256
+ """
257
+ js = json.loads(jsString)
258
+ if name is None:
259
+ name = js["systemName"]
260
+ return cls.buildSystemFromDict(
261
+ js, thing, name=name, forceDummy=forceDummy, sliderMul=sliderMul, pBar=pBar
262
+ )
263
+
264
+ @classmethod
265
+ def buildSystemFromJson(
266
+ cls, jsPath, thing=None, name=None, forceDummy=False, sliderMul=1.0, pBar=None
267
+ ):
268
+ """Build a system from .json file
269
+
270
+ Parameters
271
+ ----------
272
+ jsPath : str
273
+ The .json file to load
274
+ thing : object
275
+ The DCC mesh to build the system on (Default value = None)
276
+ name : str
277
+ The name of the new Simplex system (Default value = None)
278
+ forceDummy : bool
279
+ When loading, don't make a connection to the actual DCC. Instead use the
280
+ "dummy" DCC. Defaults False
281
+ sliderMul : float
282
+ A multiplier for the range of sliders. Simplex will only define values
283
+ between -1 and 1. This multiplier will let the attribute range in the DCC be larger so
284
+ animators can push the extremes (Default value = 1.0)
285
+ pBar : QProgressDialog, optional
286
+ If provided, display progress in this dialog
287
+
288
+ Returns
289
+ -------
290
+ : Simplex
291
+ A newly created Simplex system
292
+
293
+ """
294
+ with open(jsPath, "r") as f:
295
+ jsString = f.read()
296
+ return cls.buildSystemFromJsonString(
297
+ jsString,
298
+ thing,
299
+ name=name,
300
+ forceDummy=forceDummy,
301
+ sliderMul=sliderMul,
302
+ pBar=pBar,
303
+ )
304
+
305
+ @classmethod
306
+ def buildSystemFromSmpx(
307
+ cls, smpxPath, thing=None, name=None, forceDummy=False, sliderMul=1.0, pBar=None
308
+ ):
309
+ """Build a system from a .smpx file
310
+ SMPX files are (under-the-hood) alembic caches with each shape delta stored as a frame of animation,
311
+ and the json string stored in a property on the mesh.
312
+
313
+ Parameters
314
+ ----------
315
+ smxpPath : str
316
+ The .smpx file to load
317
+ thing : object
318
+ The DCC mesh to build the system on (Default value = None)
319
+ name : str
320
+ The name of the new Simplex system (Default value = None)
321
+ forceDummy : bool
322
+ When loading, don't make a connection to the actual DCC. Instead use the
323
+ "dummy" DCC. Defaults False
324
+ sliderMul : float
325
+ A multiplier for the range of sliders. Simplex will only define values
326
+ between -1 and 1. This multiplier will let the attribute range in the DCC be larger so
327
+ animators can push the extremes (Default value = 1.0)
328
+ pBar : QProgressDialog, optional
329
+ If provided, display progress in this dialog
330
+
331
+ Returns
332
+ -------
333
+ : Simplex
334
+ A newly created Simplex system
335
+
336
+ """
337
+ if thing is None:
338
+ thing = cls.buildBaseObject(smpxPath, forceDummy=forceDummy)
339
+ iarch, abcMesh, jsString = getSmpxArchiveData(smpxPath)
340
+ js = json.loads(jsString)
341
+
342
+ if not forceDummy:
343
+ smpxCount = getPointCount(abcMesh)
344
+ dccCount = DCC.vertCount(thing)
345
+ if smpxCount != dccCount:
346
+ raise RuntimeError(
347
+ "Point Count Mismatch. Smpx File:{0} DCC:{1}".format(
348
+ smpxCount, dccCount
349
+ )
350
+ )
351
+
352
+ del iarch, abcMesh # release the files
353
+ if name is None:
354
+ name = js["systemName"]
355
+ self = cls.buildSystemFromDict(
356
+ js, thing, name=name, forceDummy=forceDummy, sliderMul=sliderMul, pBar=pBar
357
+ )
358
+ self.loadSmpxShapes(smpxPath, pBar=pBar)
359
+ self.loadSmpxFalloffs(smpxPath, pBar=pBar)
360
+ return self
361
+
362
+ @classmethod
363
+ def buildSystemFromFile(
364
+ cls, path, thing=None, name=None, forceDummy=False, sliderMul=1.0, pBar=None
365
+ ):
366
+ """Build a system from a file
367
+
368
+ Parameters
369
+ ----------
370
+ path : str
371
+ The file to load. Either .json or .smpx
372
+ thing : object
373
+ The DCC mesh to build the system on (Default value = None)
374
+ name : str
375
+ The name of the new Simplex system (Default value = None)
376
+ forceDummy : bool
377
+ When loading, don't make a connection to the actual DCC. Instead use the
378
+ "dummy" DCC. Defaults False
379
+ sliderMul : float
380
+ A multiplier for the range of sliders. Simplex will only define values
381
+ between -1 and 1. This multiplier will let the attribute range in the DCC be larger so
382
+ animators can push the extremes (Default value = 1.0)
383
+ pBar : QProgressDialog, optional
384
+ If provided, display progress in this dialog
385
+
386
+ Returns
387
+ -------
388
+ : Simplex
389
+ A newly created Simplex system
390
+
391
+ """
392
+ if path.endswith(".json"):
393
+ return cls.buildSystemFromJson(
394
+ path,
395
+ thing=thing,
396
+ name=name,
397
+ forceDummy=forceDummy,
398
+ sliderMul=sliderMul,
399
+ pBar=pBar,
400
+ )
401
+ elif path.endswith(".smpx"):
402
+ return cls.buildSystemFromSmpx(
403
+ path,
404
+ thing=thing,
405
+ name=name,
406
+ forceDummy=forceDummy,
407
+ sliderMul=sliderMul,
408
+ pBar=pBar,
409
+ )
410
+ else:
411
+ raise ValueError(
412
+ "The filepath provided is not a .json or .smpx: {0}".format(path)
413
+ )
414
+
415
+ @classmethod
416
+ def buildSystemFromMesh(
417
+ cls, thing, name, forceDummy=False, sliderMul=1.0, pBar=None
418
+ ):
419
+ """Build a system from the data already built in the DCC
420
+
421
+ Parameters
422
+ ----------
423
+ thing : object
424
+ The DCC mesh to load the system from
425
+ name : str
426
+ The name of the new Simplex system
427
+ forceDummy : bool
428
+ When loading, don't make a connection to the actual DCC. Instead use the
429
+ "dummy" DCC. Defaults False
430
+ sliderMul : float
431
+ A multiplier for the range of sliders. Simplex will only define values
432
+ between -1 and 1. This multiplier will let the attribute range in the DCC be larger so
433
+ animators can push the extremes (Default value = 1.0)
434
+ pBar : QProgressDialog, optional
435
+ If provided, display progress in this dialog
436
+
437
+ Returns
438
+ -------
439
+ : Simplex
440
+ A newly created Simplex system
441
+
442
+ """
443
+ jsDict = json.loads(DCC.getSimplexStringOnThing(thing, name))
444
+ return cls.buildSystemFromDict(
445
+ jsDict,
446
+ thing,
447
+ name=name,
448
+ create=False,
449
+ forceDummy=forceDummy,
450
+ sliderMul=sliderMul,
451
+ pBar=pBar,
452
+ )
453
+
454
+ @classmethod
455
+ def buildSystemFromDict(
456
+ cls,
457
+ jsDict,
458
+ thing,
459
+ name=None,
460
+ create=True,
461
+ forceDummy=False,
462
+ sliderMul=1.0,
463
+ pBar=None,
464
+ ):
465
+ """Utility for building a cleared system from a dictionary
466
+
467
+ Parameters
468
+ ----------
469
+ jsDict : dict
470
+ The definition dictonary (parsed from a json string)
471
+ thing : object
472
+ The DCC mesh to load the system on
473
+ name : str, optional
474
+ The name of the new Simplex system. If None, default to the system name
475
+ create : bool, optional
476
+ Create any missing blendshapes as the system is loaded. If False, error on missing.
477
+ Defaults to True
478
+ forceDummy : bool, optional
479
+ When loading, don't make a connection to the actual DCC. Instead use the
480
+ "dummy" DCC. Defaults to False
481
+ sliderMul : float, optional
482
+ A multiplier for the range of sliders. Simplex will only define values
483
+ between -1 and 1. This multiplier will let the attribute range in the DCC be larger so
484
+ animators can push the extremes (Default value = 1.0)
485
+ pBar : QProgressDialog, optional
486
+ If provided, display progress in this dialog
487
+
488
+ Returns
489
+ -------
490
+ : Simplex
491
+ A newly created Simplex system
492
+
493
+ """
494
+ if name is None:
495
+ name = jsDict["systemName"]
496
+ self = cls(name, forceDummy=forceDummy, sliderMul=sliderMul)
497
+ self.DCC.loadNodes(self, thing, create=create)
498
+ self.loadDefinition(jsDict, create=create, pBar=pBar)
499
+ return self
500
+
501
+ def loadSmpxShapes(self, smpxPath, pBar=None):
502
+ """Load the Shapes from a .smpx file onto an already loaded system
503
+ This is the "We got updated shapes from the modelers" method
504
+
505
+ Parameters
506
+ ----------
507
+ smpxPath : str
508
+ The path to the .smpx file
509
+ pBar : QProgressDialog, optional
510
+ If provided, display progress in this dialog
511
+
512
+ Returns
513
+ -------
514
+
515
+ """
516
+ iarch, abcMesh, jsString = getSmpxArchiveData(smpxPath)
517
+ js = json.loads(jsString)
518
+
519
+ try:
520
+ self.DCC.loadAbc(abcMesh, js, pBar=pBar)
521
+ finally:
522
+ del abcMesh, iarch
523
+
524
+ def loadSmpxPoses(self, smpxPath, pBar=None):
525
+ """Load the Poses from a .smpx file onto an already loaded system
526
+ This is the "Update the joints and skin" method
527
+
528
+ Parameters
529
+ ----------
530
+ smpxPath : str
531
+ The path to the .smpx file
532
+ pBar : QProgressDialog, optional
533
+ If provided, display progress in this dialog
534
+
535
+ Returns
536
+ -------
537
+
538
+ """
539
+ iarch, abcMesh, jsString = getSmpxArchiveData(smpxPath)
540
+ js = json.loads(jsString)
541
+
542
+ try:
543
+ self.DCC.loadAbcPoses(abcMesh, js, pBar=pBar)
544
+ finally:
545
+ del abcMesh, iarch
546
+
547
+ def loadSmpxFalloffs(self, abcPath, pBar=None):
548
+ """Load the relevant data from a simplex alembic
549
+
550
+ Parameters
551
+ ----------
552
+ abcPath : str
553
+ Path to the .smpx file
554
+ pBar : QProgressDialog, optional
555
+ If provided, display progress in this dialog
556
+
557
+ Returns
558
+ -------
559
+
560
+ """
561
+ foDict = readFalloffData(abcPath)
562
+
563
+ for fo in self.falloffs:
564
+ foData = foDict.get(fo.name, None)
565
+ if foData is not None:
566
+ fo.weights = foData
567
+
568
+ # Properties
569
+ @property
570
+ def name(self):
571
+ """Get the system name"""
572
+ return self._name
573
+
574
+ @name.setter
575
+ @stackable
576
+ def name(self, value):
577
+ """Set the system name"""
578
+ if value == self._name:
579
+ return
580
+
581
+ self._name = value
582
+ self.DCC.renameSystem(value) # ??? probably needs work
583
+ if self.restShape is not None:
584
+ self.restShape.name = self.getRestName()
585
+
586
+ for model in self.models:
587
+ model.itemDataChanged(self)
588
+
589
+ @property
590
+ def progs(self):
591
+ """Get all Progressions defined in the system"""
592
+ out = []
593
+ for slider in self.sliders:
594
+ out.append(slider.prog)
595
+ for combo in self.combos:
596
+ out.append(combo.prog)
597
+ for trav in self.traversals:
598
+ out.append(trav.prog)
599
+ return out
600
+
601
+ @property
602
+ def groups(self):
603
+ """Get all Groups defined in the system"""
604
+ return self.sliderGroups + self.comboGroups + self.traversalGroups
605
+
606
+ def treeChild(self, row):
607
+ """ """
608
+ return self.groups[row]
609
+
610
+ def treeRow(self):
611
+ """ """
612
+ return 0
613
+
614
+ def treeParent(self):
615
+ """ """
616
+ return None
617
+
618
+ def treeChildCount(self):
619
+ """ """
620
+ return len(self.groups)
621
+
622
+ def treeData(self, column):
623
+ """ """
624
+ if column == 0:
625
+ return self.name
626
+ return None
627
+
628
+ def treeChecked(self):
629
+ """ """
630
+ return None
631
+
632
+ def icon(self):
633
+ return None
634
+
635
+ # HELPER
636
+ def comboExists(self, sliders, values):
637
+ """Check if a combo exists with these specific sliders and values
638
+ Because combo names aren't necessarily always in the same order
639
+
640
+ Parameters
641
+ ----------
642
+ sliders : [Slider, ....]
643
+ The sliders to check
644
+ values : [float, ....]
645
+ The values to check
646
+
647
+ Returns
648
+ -------
649
+ : Combo or None
650
+ The Combo with those sliders and values, or None if none found
651
+
652
+ """
653
+ checkSet = {(s.name, v) for s, v in zip(sliders, values)}
654
+ for cmb in self.combos:
655
+ cmbSet = {(p.slider.name, p.value) for p in cmb.pairs}
656
+ if checkSet == cmbSet:
657
+ return cmb
658
+ return None
659
+
660
+ # DESTRUCTOR
661
+ def deleteSystem(self):
662
+ """Delete an existing system from the DCC"""
663
+ # Store the models as temp so the model doesn't go crazy with the signals
664
+ models, self.models = self.models, None
665
+ mgrs = [model.resetModelManager() for model in models]
666
+ with nested(*mgrs):
667
+ self.DCC.deleteSystem()
668
+ self._initValues()
669
+ self.DCC = DCC(self)
670
+ self.models = models
671
+
672
+ def getComboUpstreams(self, combo):
673
+ """Get a list of only combos that are upstream to the given combo
674
+ In this case, "upstream" means that when the given combo is active,
675
+ then any returned combos are also active.
676
+
677
+ I am currently ignoring floating combos in this function
678
+ The upstream sliders are available trivially through combo.pairs
679
+
680
+ Parameters
681
+ ----------
682
+ combo : Combo
683
+ The given combo
684
+
685
+ Returns
686
+ -------
687
+ : [Combo, ....]
688
+ The list of upstream combos
689
+
690
+ """
691
+ pairDict = {p.slider: p.value for p in combo.pairs}
692
+
693
+ upstreams = []
694
+ for c in self.combos:
695
+ if c.isFloating():
696
+ continue
697
+
698
+ if len(c.pairs) >= len(pairDict):
699
+ continue
700
+
701
+ if not all(p.slider in pairDict for p in c.pairs):
702
+ continue
703
+
704
+ fail = False
705
+ for p in c.pairs:
706
+ if p.slider not in pairDict:
707
+ fail = True
708
+ break
709
+ if pairDict[p.slider] * p.value < 0.0:
710
+ # opposite Signs
711
+ fail = True
712
+ break
713
+
714
+ if not fail:
715
+ upstreams.append(c)
716
+
717
+ return upstreams
718
+
719
+ def getDownstreamTraversals(self, slider):
720
+ """Get a list of any traversals that depend on the given slider
721
+
722
+ Parameters
723
+ ----------
724
+ slider : Slider
725
+ The system slider to check
726
+
727
+ Returns
728
+ -------
729
+ : [Traversal, ....]
730
+ The list of dependent Traversals
731
+
732
+ """
733
+ downstream = []
734
+ for t in self.traversals:
735
+ for pair in t.startPoint.pairs + t.endPoint.pairs:
736
+ if slider == pair.slider:
737
+ downstream.append(t)
738
+ break
739
+ downstream = list(set(downstream))
740
+ return downstream
741
+
742
+ def getDownstreamCombos(self, slider):
743
+ """Get a list of any Combos that depend on the given slider
744
+
745
+ Parameters
746
+ ----------
747
+ slider : Slider
748
+ The Slider item to check
749
+
750
+ Returns
751
+ -------
752
+ : [Combo, ....]
753
+ The list of dependent Combos
754
+
755
+ """
756
+ downstream = []
757
+ if not isinstance(slider, Slider):
758
+ return downstream
759
+ for c in self.combos:
760
+ for pair in c.pairs:
761
+ if pair.slider == slider:
762
+ downstream.append(c)
763
+ break
764
+ downstream = list(set(downstream))
765
+ return downstream
766
+
767
+ def deleteDownstream(self, item):
768
+ """Delete all items from the system that depend on the given item
769
+
770
+ Parameters
771
+ ----------
772
+ item : object
773
+ The system item to check
774
+
775
+ Returns
776
+ -------
777
+
778
+ """
779
+ todel = []
780
+ todel.extend(self.getDownstreamCombos(item))
781
+ todel.extend(self.getDownstreamTraversals(item))
782
+ for c in todel:
783
+ c.delete()
784
+
785
+ # USER METHODS
786
+ def setLegacy(self, legacy):
787
+ """Set whether to use the legacy .json format
788
+
789
+ Parameters
790
+ ----------
791
+ legacy : bool
792
+ Whether to use the legacy .json format
793
+
794
+ Returns
795
+ -------
796
+
797
+ """
798
+ self._legacy = legacy
799
+
800
+ def getFloatingShapes(self):
801
+ """Find Combos with values other than -1 and 1
802
+
803
+ Parameters
804
+ ----------
805
+
806
+ Returns
807
+ -------
808
+ : [Combo, ....]
809
+ Combos that don't have fully extreme activations
810
+
811
+ """
812
+ floaters = [c for c in self.combos if c.isFloating()]
813
+ floatShapes = []
814
+ for f in floaters:
815
+ floatShapes.extend(f.prog.getShapes())
816
+ return floatShapes
817
+
818
+ def buildDefinition(self):
819
+ """Create a simplex definition dictionary
820
+ Loop through all the objects managed by this simplex system, and build a dictionary that defines it
821
+
822
+ Parameters
823
+ ----------
824
+
825
+ Returns
826
+ -------
827
+ : dict
828
+ The simplex definition dictionary
829
+
830
+ """
831
+ things = [
832
+ self.shapes,
833
+ self.sliders,
834
+ self.combos,
835
+ self.traversals,
836
+ self.groups,
837
+ self.falloffs,
838
+ ]
839
+ for thing in things:
840
+ for i in thing:
841
+ i.clearBuildIndex()
842
+
843
+ # Make sure we start with the extras in
844
+ # case we're overwriting with new data
845
+ d = copy.deepcopy(self._extras)
846
+
847
+ # Then set all the top-level system keys
848
+ d["encodingVersion"] = 1 if self._legacy else 3
849
+ d["systemName"] = self.name
850
+ d["clusterName"] = self.clusterName
851
+ d.setdefault("falloffs", [])
852
+ d.setdefault("combos", [])
853
+ d.setdefault("shapes", [])
854
+ d.setdefault("sliders", [])
855
+ d.setdefault("groups", [])
856
+ d.setdefault("progressions", [])
857
+ d.setdefault("traversals", [])
858
+
859
+ # rest shape should *ALWAYS* be index 0
860
+ for shape in self.shapes:
861
+ shape.buildDefinition(d, self._legacy)
862
+
863
+ for group in self.groups:
864
+ group.buildDefinition(d, self._legacy)
865
+
866
+ for falloff in self.falloffs:
867
+ falloff.buildDefinition(d, self._legacy)
868
+
869
+ for slider in self.sliders:
870
+ slider.buildDefinition(d, self._legacy)
871
+
872
+ for combo in self.combos:
873
+ combo.buildDefinition(d, self._legacy)
874
+
875
+ for trav in self.traversals:
876
+ trav.buildDefinition(d, self._legacy)
877
+
878
+ return d
879
+
880
+ @stackable
881
+ def loadDefinition(self, simpDict, create=True, pBar=None):
882
+ """Build the structure of objects in this system
883
+ based on a provided dictionary
884
+
885
+ Parameters
886
+ ----------
887
+ simpDict : dict
888
+ The dictionary to load
889
+ create : bool, optional
890
+ Create any missing blendshapes as the system is loaded. If False, error on missing.
891
+ Defaults to True
892
+ pBar : QProgressDialog, optional
893
+ If provided, display progress in this dialog
894
+
895
+ Returns
896
+ -------
897
+
898
+ """
899
+
900
+ self.name = simpDict["systemName"]
901
+ self.clusterName = simpDict["clusterName"] # for XSI
902
+ if simpDict["encodingVersion"] == 1:
903
+ self.loadV1(simpDict, create=create, pBar=pBar)
904
+ elif simpDict["encodingVersion"] == 2:
905
+ self.loadV2(simpDict, create=create, pBar=pBar)
906
+ elif simpDict["encodingVersion"] == 3:
907
+ self.loadV3(simpDict, create=create, pBar=pBar)
908
+ self.storeExtras(simpDict)
909
+
910
+ def _incPBar(self, pBar, txt, inc=1):
911
+ """Increment the progress bar and return False if the user cancelled
912
+
913
+ Parameters
914
+ ----------
915
+ pBar :
916
+
917
+ txt :
918
+
919
+ inc :
920
+ (Default value = 1)
921
+
922
+ Returns
923
+ -------
924
+
925
+ """
926
+ if pBar is not None:
927
+ pBar.setValue(pBar.value() + inc)
928
+ pBar.setLabelText("Building:\n" + txt)
929
+ QApplication.processEvents()
930
+ return not pBar.wasCanceled()
931
+ return True
932
+
933
+ def loadV3(self, simpDict, create=True, pBar=None):
934
+ """Load the version 3 simplex definition
935
+ V3 is just the same as V2, except for an update Traversal definition
936
+
937
+ Parameters
938
+ ----------
939
+ simpDict : dict
940
+ The simplex definition dictionary
941
+ create : bool, optional
942
+ Create any missing blendshapes as the system is loaded. If False, error on missing.
943
+ Defaults to True
944
+ pBar : QProgressDialog, optional
945
+ If provided, display progress in this dialog
946
+
947
+ Returns
948
+ -------
949
+
950
+ """
951
+ preRet = self.DCC.preLoad(self, simpDict, create=create, pBar=pBar)
952
+ try:
953
+ fos = simpDict.get("falloffs", [])
954
+ gs = simpDict.get("groups", [])
955
+ for f in fos:
956
+ Falloff.loadV2(self, f)
957
+ if gs:
958
+ for g in gs:
959
+ Group.loadV2(self, g)
960
+ else:
961
+ Group("Group_0", self, Slider)
962
+ Group("Group_1", self, Combo)
963
+ Group("Group_2", self, Traversal)
964
+
965
+ if pBar is not None:
966
+ maxLen = max(len(i["name"]) for i in simpDict["shapes"])
967
+ pBar.setLabelText("_" * maxLen)
968
+ pBar.setValue(0)
969
+ pBar.setMaximum(len(simpDict["shapes"]) + 1)
970
+ self.shapes = []
971
+ for s in simpDict["shapes"]:
972
+ if not self._incPBar(pBar, s["name"]):
973
+ return
974
+ Shape.loadV2(self, s, create)
975
+
976
+ self.restShape = self.shapes[0]
977
+ self.restShape.isRest = True
978
+
979
+ progs = [Progression.loadV2(self, p) for p in simpDict["progressions"]]
980
+
981
+ for s in simpDict["sliders"]:
982
+ Slider.loadV2(self, progs, s, create)
983
+ for c in simpDict["combos"]:
984
+ Combo.loadV2(self, progs, c)
985
+ for t in simpDict["traversals"]:
986
+ Traversal.loadV3(self, progs, t)
987
+
988
+ for x in itertools.chain(self.sliders, self.combos, self.traversals):
989
+ x.prog.name = x.name
990
+ finally:
991
+ self.DCC.postLoad(self, preRet)
992
+
993
+ def loadV2(self, simpDict, create=True, pBar=None):
994
+ """Load the version 2 simplex definition
995
+
996
+ Parameters
997
+ ----------
998
+ simpDict : dict
999
+ The simplex definition dictionary
1000
+ create : bool, optional
1001
+ Create any missing blendshapes as the system is loaded. If False, error on missing.
1002
+ Defaults to True
1003
+ pBar : QProgressDialog, optional
1004
+ If provided, display progress in this dialog
1005
+
1006
+ Returns
1007
+ -------
1008
+
1009
+ """
1010
+ preRet = self.DCC.preLoad(self, simpDict, create=create, pBar=pBar)
1011
+ try:
1012
+ fos = simpDict.get("falloffs", [])
1013
+ gs = simpDict.get("groups", [])
1014
+ for f in fos:
1015
+ Falloff.loadV2(self, f)
1016
+ if gs:
1017
+ for g in gs:
1018
+ Group.loadV2(self, g)
1019
+ else:
1020
+ Group("Group_0", self, Slider)
1021
+ Group("Group_1", self, Combo)
1022
+ Group("Group_2", self, Traversal)
1023
+
1024
+ if pBar is not None:
1025
+ maxLen = max(len(i["name"]) for i in simpDict["shapes"])
1026
+ pBar.setLabelText("_" * maxLen)
1027
+ pBar.setValue(0)
1028
+ pBar.setMaximum(len(simpDict["shapes"]) + 1)
1029
+ self.shapes = []
1030
+ for s in simpDict["shapes"]:
1031
+ if not self._incPBar(pBar, s["name"]):
1032
+ return
1033
+ Shape.loadV2(self, s, create)
1034
+
1035
+ self.restShape = self.shapes[0]
1036
+ self.restShape.isRest = True
1037
+
1038
+ progs = [Progression.loadV2(self, p) for p in simpDict["progressions"]]
1039
+
1040
+ for s in simpDict["sliders"]:
1041
+ Slider.loadV2(self, progs, s, create)
1042
+ for c in simpDict["combos"]:
1043
+ Combo.loadV2(self, progs, c)
1044
+ for t in simpDict["traversals"]:
1045
+ Traversal.loadV2(self, progs, t)
1046
+
1047
+ for x in itertools.chain(self.sliders, self.combos, self.traversals):
1048
+ x.prog.name = x.name
1049
+ finally:
1050
+ self.DCC.postLoad(self, preRet)
1051
+
1052
+ def loadV1(self, simpDict, create=True, pBar=None):
1053
+ """Load the version 1 simplex definition
1054
+
1055
+ Parameters
1056
+ ----------
1057
+ simpDict : dict
1058
+ The simplex definition dictionary
1059
+ create : bool, optional
1060
+ Create any missing blendshapes as the system is loaded. If False, error on missing.
1061
+ Defaults to True
1062
+ pBar : QProgressDialog, optional
1063
+ If provided, display progress in this dialog
1064
+
1065
+ Returns
1066
+ -------
1067
+
1068
+ """
1069
+ preRet = self.DCC.preLoad(self, simpDict, create=create, pBar=pBar)
1070
+ try:
1071
+ self.falloffs = [Falloff(f[0], self, *f[1:]) for f in simpDict["falloffs"]]
1072
+ groupNames = simpDict["groups"]
1073
+
1074
+ if pBar is not None:
1075
+ maxLen = max(list(map(len, simpDict["shapes"])))
1076
+ pBar.setLabelText("_" * maxLen)
1077
+ pBar.setValue(0)
1078
+ pBar.setMaximum(len(simpDict["shapes"]) + 1)
1079
+
1080
+ shapes = []
1081
+ for s in simpDict["shapes"]:
1082
+ if not self._incPBar(pBar, s):
1083
+ return
1084
+ shapes.append(Shape(s, self))
1085
+
1086
+ self.restShape = shapes[0]
1087
+ self.restShape.isRest = True
1088
+
1089
+ progs = []
1090
+ for p in simpDict["progressions"]:
1091
+ progShapes = [shapes[i] for i in p[1]]
1092
+ progFalloffs = [self.falloffs[i] for i in p[4]]
1093
+ progPairs = [ProgPair(self, s, pv) for s, pv in zip(progShapes, p[2])]
1094
+ progs.append(Progression(p[0], self, progPairs, p[3], progFalloffs))
1095
+
1096
+ self.sliders = []
1097
+ self.sliderGroups = []
1098
+ createdSlidergroups = {}
1099
+ for s in simpDict["sliders"]:
1100
+ sliderProg = progs[s[1]]
1101
+
1102
+ gn = groupNames[s[2]]
1103
+ if gn in createdSlidergroups:
1104
+ sliderGroup = createdSlidergroups[gn]
1105
+ else:
1106
+ sliderGroup = Group(gn, self, Slider)
1107
+ createdSlidergroups[gn] = sliderGroup
1108
+
1109
+ Slider(s[0], self, sliderProg, sliderGroup)
1110
+
1111
+ self.combos = []
1112
+ self.comboGroups = []
1113
+ createdComboGroups = {}
1114
+ for c in simpDict["combos"]:
1115
+ prog = progs[c[1]]
1116
+ sliderIdxs, sliderVals = list(zip(*c[2]))
1117
+ sliders = [self.sliders[i] for i in sliderIdxs]
1118
+ pairs = list(map(ComboPair, sliders, sliderVals))
1119
+ if len(c) >= 4:
1120
+ gn = groupNames[c[3]]
1121
+ else:
1122
+ gn = "DEPTH_0"
1123
+
1124
+ if gn in createdComboGroups:
1125
+ comboGroup = createdComboGroups[gn]
1126
+ else:
1127
+ comboGroup = Group(gn, self, Combo)
1128
+ createdComboGroups[gn] = comboGroup
1129
+
1130
+ cmb = Combo(c[0], self, pairs, prog, comboGroup, None)
1131
+ cmb.simplex = self
1132
+
1133
+ self.traversals = []
1134
+ self.traversalGroups = []
1135
+ createdTraversalGroups = {}
1136
+ if "traversals" in simpDict:
1137
+ for t in simpDict["traversals"]:
1138
+ name = t["name"]
1139
+ prog = progs[t["prog"]]
1140
+
1141
+ pcIdx = t["progressControl"]
1142
+ pcSearch = (
1143
+ self.sliders
1144
+ if t["progressType"].lower() == "slider"
1145
+ else self.combos
1146
+ )
1147
+ pc = pcSearch[pcIdx]
1148
+ pFlip = t["progressFlip"]
1149
+ pp = TravPair(pc, -1 if pFlip else 1, "progress")
1150
+
1151
+ mcIdx = t["multiplierControl"]
1152
+ mcSearch = (
1153
+ self.sliders
1154
+ if t["multiplierType"].lower() == "slider"
1155
+ else self.combos
1156
+ )
1157
+ mc = mcSearch[mcIdx]
1158
+ mFlip = t["multiplierFlip"]
1159
+ mm = TravPair(mc, -1 if mFlip else 1, "multiplier")
1160
+
1161
+ gn = groupNames[t.get("group", 2)]
1162
+ if gn in createdTraversalGroups:
1163
+ travGroup = createdTraversalGroups[gn]
1164
+ else:
1165
+ travGroup = Group(gn, self, Traversal)
1166
+ createdTraversalGroups[gn] = travGroup
1167
+
1168
+ color = QColor(*t.get("color", (0, 0, 0)))
1169
+
1170
+ trav = Traversal(name, self, mm, pp, prog, travGroup, color)
1171
+ trav.simplex = self
1172
+
1173
+ for x in itertools.chain(self.sliders, self.combos, self.traversals):
1174
+ x.prog.name = x.name
1175
+ finally:
1176
+ self.DCC.postLoad(self, preRet)
1177
+
1178
+ def storeExtras(self, simpDict):
1179
+ """Store any unknown keys when dumping, just in case they're important elsewhere
1180
+
1181
+ Parameters
1182
+ ----------
1183
+ simpDict : dict
1184
+ The simplex definition dictionary
1185
+
1186
+ Returns
1187
+ -------
1188
+
1189
+ """
1190
+ sd = copy.deepcopy(simpDict)
1191
+ knownTopLevel = [
1192
+ "encodingVersion",
1193
+ "systemName",
1194
+ "clusterName",
1195
+ "falloffs",
1196
+ "combos",
1197
+ "shapes",
1198
+ "sliders",
1199
+ "groups",
1200
+ "traversals",
1201
+ "progressions",
1202
+ ]
1203
+
1204
+ for ktn in knownTopLevel:
1205
+ if ktn in sd:
1206
+ del sd[ktn]
1207
+ self._extras = sd
1208
+
1209
+ def loadJSON(self, jsString):
1210
+ """Convenience method to load a JSON string definition
1211
+
1212
+ Parameters
1213
+ ----------
1214
+ jsString : str
1215
+ The json formatted definition string
1216
+
1217
+ Returns
1218
+ -------
1219
+
1220
+ """
1221
+ self.loadDefinition(json.loads(jsString))
1222
+
1223
+ def getRestName(self):
1224
+ """Get the default rest shape name
1225
+
1226
+ Parameters
1227
+ ----------
1228
+
1229
+ Returns
1230
+ -------
1231
+ : str
1232
+ The default rest shape name
1233
+
1234
+ """
1235
+ return "Rest_{0}".format(self.name)
1236
+
1237
+ def dump(self):
1238
+ """Dump the definition dictionary to a json string
1239
+
1240
+ Parameters
1241
+ ----------
1242
+
1243
+ Returns
1244
+ -------
1245
+ : str
1246
+ The json formatted definition string
1247
+
1248
+ """
1249
+ return json.dumps(self.buildDefinition())
1250
+
1251
+ def exportAbc(self, path, pBar=None):
1252
+ """Export the current mesh to a .smpx formatted file
1253
+
1254
+ Parameters
1255
+ ----------
1256
+ path : str
1257
+ The path to export to
1258
+ pBar : QProgressDialog, optional
1259
+ If provided, display progress in this dialog
1260
+
1261
+ Returns
1262
+ -------
1263
+
1264
+ """
1265
+ defDict = self.buildDefinition()
1266
+ jsString = json.dumps(defDict)
1267
+
1268
+ arch, abcMesh = buildAlembicArchiveData(path, self.name, jsString, True)
1269
+ try:
1270
+ self.DCC.exportAbc(
1271
+ self.DCC.mesh,
1272
+ abcMesh,
1273
+ defDict,
1274
+ world=False,
1275
+ ensureCorrect=True,
1276
+ pBar=pBar,
1277
+ )
1278
+ finally:
1279
+ del arch, abcMesh
1280
+
1281
+ def exportOther(self, path, dccMesh, world=False, ensureCorrect=False, pBar=None):
1282
+ """Export shapes from a mesh that isn't part of the current system
1283
+
1284
+ The export process for shapes differs from DCC to DCC.
1285
+ In Maya, every blendshape is activated, one by one and the point posisitions
1286
+ are read from the target mesh. This allows exportOther to work
1287
+
1288
+ In XSI, the blendshape properties are read directly, so there's no chance
1289
+ to process the new shapes (which means this won't work in XSI)
1290
+
1291
+ Parameters
1292
+ ----------
1293
+ path : str
1294
+ The output path for the .smpx file
1295
+ dccMesh : object
1296
+ The system-external DCC mesh to export
1297
+ world : bool, optional
1298
+ Whether to do the export in worldspace. Defaults to False
1299
+ pBar : QProgressDialog, optional
1300
+ If provided, display progress in this dialog
1301
+
1302
+ """
1303
+ defDict = self.buildDefinition()
1304
+ jsString = json.dumps(defDict)
1305
+
1306
+ arch, abcMesh = buildAlembicArchiveData(path, self.name, jsString, True)
1307
+ try:
1308
+ self.DCC.exportOtherAbc(dccMesh, abcMesh, defDict, world=world, pBar=pBar)
1309
+ finally:
1310
+ del arch, abcMesh
1311
+
1312
+ def setSlidersWeights(self, sliders, weights):
1313
+ """Set the weights of multiple sliders as one method
1314
+
1315
+ Parameters
1316
+ ----------
1317
+ sliders : [Slider, ....]
1318
+ The list of Sliders to set weights for
1319
+ weights : [float, ....]
1320
+ The weights to set
1321
+
1322
+ Returns
1323
+ -------
1324
+
1325
+ """
1326
+ with undoContext(self.DCC):
1327
+ for slider, weight in zip(sliders, weights):
1328
+ slider.value = weight
1329
+ self.DCC.setSlidersWeights(sliders, weights)
1330
+ for model in self.models:
1331
+ for slider in sliders:
1332
+ model.itemDataChanged(slider)
1333
+
1334
+ def extractRestShape(self, offset=0):
1335
+ """Extract the rest shape to a mesh in the DCC
1336
+
1337
+ Parameters
1338
+ ----------
1339
+ offset : float
1340
+ The offset value given to the extracted mesh (Default value = 0)
1341
+
1342
+ Returns
1343
+ -------
1344
+
1345
+ """
1346
+ if self.restShape is None:
1347
+ return None
1348
+ return self.DCC.extractShape(self.restShape, live=False, offset=offset)
1349
+
1350
+ def buildRestShape(self):
1351
+ """Build and store a rest shape for this system"""
1352
+ self.restShape = Shape.buildRest(self)
1353
+ return self.restShape
1354
+
1355
+ def buildInputVectors(
1356
+ self,
1357
+ keepSliders=None,
1358
+ ignoreSliders=None,
1359
+ depthCutoff=None,
1360
+ ignoreFloaters=False,
1361
+ ignoreTraversals=False,
1362
+ extremes=False,
1363
+ ):
1364
+ """This is kind of a specialized function. Often, I have to sum combo deltas
1365
+ into the full sculpted shape. But to do that, I have to build the inputs to the
1366
+ solver that enable each shape, and I need a name for each shape.
1367
+ This function gives me both.
1368
+
1369
+ Parameters
1370
+ ----------
1371
+ keepSliders : set([str, ....]), optional
1372
+ The returned sliders will have names that are part of this list
1373
+ ignoreSliders : set([str, ....]), optional
1374
+ A set of Slider names to ignore as part of this process
1375
+ depthCutoff : int, optional
1376
+ The maximum number of Sliders allowed per Combo
1377
+ (Defaults to None which allows all Combos)
1378
+ ignoreFloaters : bool, optional
1379
+ Ignore Combos with values other than -1 and 1
1380
+ extremes : bool, optional
1381
+ Only build activations for sliders and combos at -1 and 1
1382
+
1383
+ Returns
1384
+ -------
1385
+ : [str, ...]
1386
+ The names of the shapes that are activated in each list
1387
+ : [[float, ...], ...]
1388
+ A list of activation values for the entire system
1389
+
1390
+ """
1391
+ # InputVector comes from the c++ std::vector
1392
+ # Get all endpoint shapes from the progressions
1393
+ shapeNames = []
1394
+ inVecs = []
1395
+ keyIdxs = []
1396
+ ignoreSliders = ignoreSliders or set()
1397
+ ignoreSliders = set(ignoreSliders)
1398
+ indexByShape = {shape: idx for idx, shape in enumerate(self.shapes)}
1399
+
1400
+ for slIdx, slider in enumerate(self.sliders):
1401
+ if slider.name in ignoreSliders:
1402
+ continue
1403
+ if keepSliders is not None and slider.name not in keepSliders:
1404
+ continue
1405
+
1406
+ pairs = [p for p in slider.prog.pairs if not p.shape.isRest]
1407
+ if extremes:
1408
+ pairs = [p for p in pairs if abs(p.value) == 1.0]
1409
+
1410
+ for pp in pairs:
1411
+ inVec = [0.0] * len(self.sliders)
1412
+ inVec[slIdx] = pp.value
1413
+ shapeNames.append(pp.shape.name)
1414
+ inVecs.append(inVec)
1415
+ keyIdxs.append(indexByShape[pp.shape])
1416
+
1417
+ for combo in self.combos:
1418
+ if ignoreFloaters and combo.isFloating():
1419
+ continue
1420
+ if depthCutoff is not None and len(combo.pairs) > depthCutoff:
1421
+ continue
1422
+ if ignoreSliders & {i.name for i in combo.getSliders()}:
1423
+ # if the combo's sliders are in ignoreSliders
1424
+ continue
1425
+
1426
+ pairs = [p for p in combo.prog.pairs if not p.shape.isRest]
1427
+ if extremes:
1428
+ pairs = [p for p in pairs if abs(p.value) == 1.0]
1429
+
1430
+ iv = combo.getInputVector()
1431
+ for pp in pairs:
1432
+ inVecs.append([x * pp.value for x in iv])
1433
+ shapeNames.append(pp.shape.name)
1434
+ keyIdxs.append(indexByShape[pp.shape])
1435
+
1436
+ for trav in self.traversals:
1437
+ # Extremes doesn't make sense at all for traversals
1438
+ if ignoreTraversals:
1439
+ continue
1440
+ pairs = [p for p in trav.prog.pairs if not p.shape.isRest]
1441
+ if extremes:
1442
+ pairs = [p for p in pairs if abs(p.value) == 1.0]
1443
+
1444
+ for pp in pairs:
1445
+ inVecs.append(trav.getInputVector(pp.value))
1446
+ shapeNames.append(pp.shape.name)
1447
+ keyIdxs.append(indexByShape[pp.shape])
1448
+
1449
+ return shapeNames, inVecs, keyIdxs
1450
+
1451
+ def evaluateInputs(self, inVecs):
1452
+ """Get the shape activation vectors that are paired with the given input vectors
1453
+ It will probably be useful to pass the returned inVecs from `buildInputVectors`
1454
+
1455
+ This will use the compiled python solver, and may not be available
1456
+
1457
+ Parameters
1458
+ ----------
1459
+ inVecs : [[SliderVal, ...], ...]
1460
+ A list of lists of sliderValues. Each sub-list has to have the same number of
1461
+ items as there are sliders in the current simplex system
1462
+
1463
+ Returns
1464
+ -------
1465
+ : [[ShapeVal, ...], ...]
1466
+ A list of lists of shapeValues resulting from the given inVecs. This returns
1467
+ the activations of all the shape values. Each sub-list will have the same
1468
+ number of items as there are shapes in the current system.
1469
+ """
1470
+ from pysimplex import PySimplex
1471
+
1472
+ solver = PySimplex(self.dump())
1473
+ return [solver.solve(iv) for iv in inVecs]
1474
+
1475
+ def controllersByDepth(self):
1476
+ """Get the shapes ordered by the depth of their controllers
1477
+ in the simplex hierarchy
1478
+ This is often useful when doing vertex position computations
1479
+
1480
+ Returns
1481
+ -------
1482
+ : [Shape, ...]
1483
+ A list of all shapes in the depth order
1484
+ """
1485
+ ctrlOrder = self.sliders[:]
1486
+ combosByDepth = {}
1487
+ for c in self.combos:
1488
+ combosByDepth.setdefault(len(c.pairs), []).append(c)
1489
+
1490
+ for depth in sorted(combosByDepth.keys()):
1491
+ combos = combosByDepth[depth]
1492
+ regular, floating = [], []
1493
+ for c in combos:
1494
+ lst = floating if c.isFloating() else regular
1495
+ lst.append(c)
1496
+ ctrlOrder.extend(regular + floating)
1497
+
1498
+ travByDepth = {}
1499
+ for t in self.traversals:
1500
+ travByDepth.setdefault(len(t.startPoint.pairs), []).append(t)
1501
+
1502
+ for depth in sorted(travByDepth.keys()):
1503
+ ctrlOrder.extend(travByDepth[depth])
1504
+
1505
+ return ctrlOrder
1506
+
1507
+ # SPLIT CODE
1508
+ def buildSplitterList(self, foList):
1509
+ """The way deepcopy works is that every object visited is added to the 'memo' dictionary,
1510
+ keyed by its id(). This way, you don't have to re-copy an object if you've already seen
1511
+ it. This means that if I make a memo that already contains objects that I don't want copied,
1512
+ then I should just be able to use deepcopy, and that will handle keeping references to the
1513
+ un-copied objects.
1514
+
1515
+ For example: If X references A, and I want to split X into L and R, then I would still want
1516
+ L to reference A *and* R to reference A. This process just auto-handles that
1517
+ I think that's is kinda neat.
1518
+
1519
+ Parameters
1520
+ ----------
1521
+ foList : [Falloff, ....]
1522
+ A list of Falloff objects *that all share the same split axis*
1523
+
1524
+ Returns
1525
+ -------
1526
+ : [object, ....]
1527
+ A list of objects to be split
1528
+ : dict
1529
+ A dict of {object: Falloff} saying what falloff should be used to split each objct
1530
+ : dict
1531
+ The memo to start the deepcopy with
1532
+
1533
+ """
1534
+ # Add all items to the memo.
1535
+ memo = {}
1536
+ memo[id(self)] = self
1537
+ stack = Stack()
1538
+ stack.enabled = False
1539
+ memo[id(self.stack)] = stack
1540
+ memo[id(self.DCC)] = self.DCC
1541
+
1542
+ memList = [
1543
+ self.groups,
1544
+ self.sliders,
1545
+ self.combos,
1546
+ self.traversals,
1547
+ self.falloffs,
1548
+ self.shapes,
1549
+ self.progs,
1550
+ ]
1551
+
1552
+ for lst in memList:
1553
+ for item in lst:
1554
+ memo[id(item)] = item
1555
+ # splitApplied needs to be part of the item so it persists
1556
+ # through the copy. Otherwise I'd have to keep track of it
1557
+ item._splitApplied = set()
1558
+
1559
+ # Using the memo from here would mean that nothing got copied
1560
+ # because all items are in it
1561
+
1562
+ toSplit = [] # A list of objects to be split along the shared foList axis
1563
+
1564
+ # A dictionary of {object: set(falloff)}. When recursing down the hierarchy,
1565
+ # some objects may be split by many falloffs. Keep track of that in this dict
1566
+ splitBySet = {}
1567
+
1568
+ for prog in self.progs:
1569
+ # I take pains to this with lists (rather than sets) so it keeps order
1570
+ sect = [i for i in foList if i in prog.falloffs]
1571
+ if sect:
1572
+ # Because I can only split an item once on an axis
1573
+ # Assume that the foList is in priority order
1574
+ # ... So I can just grab the first (highest priority)
1575
+ # falloff affecting this item
1576
+ splitFalloff = sect[0]
1577
+ ctrl = prog.controller
1578
+
1579
+ toSplit.append(prog)
1580
+ toSplit.append(ctrl)
1581
+ splitBySet.setdefault(prog, set()).add(splitFalloff)
1582
+ splitBySet.setdefault(ctrl, set()).add(splitFalloff)
1583
+ for pair in prog.pairs:
1584
+ toSplit.append(pair.shape)
1585
+ splitBySet.setdefault(pair.shape, set()).add(splitFalloff)
1586
+
1587
+ # Also add the downstream combos, and their progs
1588
+ dss = []
1589
+ if isinstance(ctrl, Slider):
1590
+ dss.extend(self.getDownstreamCombos(ctrl))
1591
+ dss.extend(self.getDownstreamTraversals(ctrl))
1592
+
1593
+ for ds in dss:
1594
+ toSplit.append(ds)
1595
+ toSplit.append(ds.prog)
1596
+ splitBySet.setdefault(ds, set()).add(splitFalloff)
1597
+ splitBySet.setdefault(ds.prog, set()).add(splitFalloff)
1598
+ for pair in ds.prog.pairs:
1599
+ toSplit.append(pair.shape)
1600
+ splitBySet.setdefault(pair.shape, set()).add(splitFalloff)
1601
+
1602
+ # Dict of {item : falloff}
1603
+ splitBy = {}
1604
+ for item, foSet in splitBySet.items():
1605
+ # Because I can only split an item once on an axis
1606
+ # Assume that the foList is in priority order
1607
+ # So get the min-indexed falloff in the set
1608
+ idx = min([foList.index(f) for f in foSet])
1609
+ splitBy[item] = foList[idx]
1610
+
1611
+ toSplit = set(toSplit)
1612
+ toSplit.discard(self.restShape)
1613
+ # Get the items to split that haven't already had a split applied along this axis
1614
+ toSplit = [i for i in toSplit if foList[0].axis not in i._splitApplied]
1615
+ # If I can't apply a sided name ot this item, then it can't be split
1616
+ toSplit = [i for i in toSplit if foList[0].canRename(i)]
1617
+
1618
+ # Remove the splitter items from the memo, ensuring they actually get copied
1619
+ for sp in toSplit:
1620
+ try:
1621
+ del memo[id(sp)]
1622
+ except KeyError:
1623
+ print("SP", sp, sp.name)
1624
+ raise
1625
+ sp._splitApplied.add(foList[0].axis.lower())
1626
+
1627
+ return toSplit, splitBy, memo
1628
+
1629
+ def split(self, pBar=None):
1630
+ """Return a split deepcopy of the system.
1631
+ The new system will be a dummy system containing all the shapes as numpy arrays which can be
1632
+ exported to a .smpx file
1633
+
1634
+ Parameters
1635
+ ----------
1636
+ pBar : QProgressDialog, optional
1637
+ If provided, display progress in this dialog
1638
+
1639
+ Returns
1640
+ -------
1641
+ : Simplex :
1642
+ A newly split system
1643
+
1644
+ """
1645
+ if np is None:
1646
+ raise RuntimeError("Numpy is not available, and splitting requires it")
1647
+
1648
+ if pBar is not None:
1649
+ pBar.setValue(0)
1650
+ pBar.setLabelText("Building Split System")
1651
+
1652
+ # Very first thing: Ensure that every object with a falloff is fully splittable
1653
+ # Meaning that splittable progs only contain splittable shapes. And splittable progs
1654
+ # are only controlled by splittable controllers
1655
+ for fo in self.falloffs:
1656
+ controllers = self.sliders + self.combos + self.traversals
1657
+ for ctrl in controllers:
1658
+ prog = ctrl.prog
1659
+
1660
+ pSplit = fo.canRename(prog)
1661
+ cSplit = fo.canRename(ctrl)
1662
+ sSplit = [s for s in prog.getShapes() if not s.isRest]
1663
+ sSplit = [fo.canRename(shape) for shape in sSplit]
1664
+ sSplitSame = all(i == sSplit[0] for i in sSplit)
1665
+ sSplit = sSplit[0]
1666
+ if not sSplitSame:
1667
+ shapes = [i.name for i in prog.getShapes()]
1668
+ msg = "Bad shapes: {0}".format(", ".join(shapes))
1669
+ raise ValueError(
1670
+ "Mix of splittable and un-splittable shapes in a progression\n"
1671
+ + msg
1672
+ )
1673
+
1674
+ if pSplit != sSplit:
1675
+ msg = "Bad Prog: {0}".format(prog.name)
1676
+ raise ValueError("A progression is not fully splittable\n" + msg)
1677
+
1678
+ if pSplit != cSplit:
1679
+ msg = "Bad prog: {0}\nBad Controller:{1}".format(
1680
+ prog.name, ctrl.name
1681
+ )
1682
+ raise ValueError("A controller is not fully splittable\n" + msg)
1683
+
1684
+ # Create the initial deepcopy
1685
+ splitSmpx = copy.deepcopy(self)
1686
+ splitSmpx.DCC.dummyLoad(self.DCC, pBar=pBar)
1687
+
1688
+ # Sort the falloffs by which axis the split on
1689
+ foByAxis = {}
1690
+ for fo in splitSmpx.falloffs:
1691
+ foByAxis.setdefault(fo.axis.lower(), []).append(fo)
1692
+
1693
+ for axis, foList in foByAxis.items():
1694
+ if pBar is not None:
1695
+ pBar.setLabelText("Splitting On {0} axis".format(axis))
1696
+ QApplication.processEvents()
1697
+ else:
1698
+ print("Splitting On {0} axis".format(axis))
1699
+
1700
+ # Get the items to split, and the memo that ensures *only* those items will be copied
1701
+ toSplit, splitBy, memo = splitSmpx.buildSplitterList(foList)
1702
+
1703
+ # DeepCopy the items twice. Once for each side of the split
1704
+ lSideSplitList = copy.deepcopy(toSplit, memo=copy.copy(memo))
1705
+ rSideSplitList = copy.deepcopy(toSplit, memo=copy.copy(memo))
1706
+
1707
+ if pBar is not None:
1708
+ pBar.setMaximum(len(toSplit))
1709
+ QApplication.processEvents()
1710
+
1711
+ # Loop through the copied items and make the replacements
1712
+ for i, (oldItem, lItem, rItem) in enumerate(
1713
+ zip(toSplit, lSideSplitList, rSideSplitList)
1714
+ ):
1715
+ if pBar is not None:
1716
+ pBar.setValue(i + 1)
1717
+ QApplication.processEvents()
1718
+
1719
+ # Get thefalloff that will split oldItem into lItem and rItem
1720
+ fo = splitBy[oldItem]
1721
+
1722
+ # Rename the newly split items
1723
+ fo.splitRename(lItem, 0)
1724
+ fo.splitRename(rItem, 1)
1725
+
1726
+ # Apply the falloff weights to any shapes
1727
+ if isinstance(oldItem, Shape):
1728
+ fo.applyFalloff(lItem, 0)
1729
+ fo.applyFalloff(rItem, 1)
1730
+
1731
+ # Maybe for all this, get the index of the oldItem in the group
1732
+ # and insert rather than append??
1733
+
1734
+ # Remove the oldItem from any groups and add the newItems
1735
+ if hasattr(oldItem, "group"):
1736
+ oldItem.group.items.remove(oldItem)
1737
+ oldItem.group = None
1738
+ lItem.group.items.append(lItem)
1739
+ rItem.group.items.append(rItem)
1740
+
1741
+ # Remove the oldItem from the simplex storage, and add the newItems
1742
+ if isinstance(oldItem, Slider):
1743
+ splitSmpx.sliders.remove(oldItem)
1744
+ splitSmpx.sliders.append(lItem)
1745
+ splitSmpx.sliders.append(rItem)
1746
+ elif isinstance(oldItem, Combo):
1747
+ splitSmpx.combos.remove(oldItem)
1748
+ splitSmpx.combos.append(lItem)
1749
+ splitSmpx.combos.append(rItem)
1750
+ elif isinstance(oldItem, Traversal):
1751
+ splitSmpx.traversals.remove(oldItem)
1752
+ splitSmpx.traversals.append(lItem)
1753
+ splitSmpx.traversals.append(rItem)
1754
+ elif isinstance(oldItem, Shape):
1755
+ splitSmpx.shapes.remove(oldItem)
1756
+ # Part of deepCopy ensures the new system uses the DummyDCC
1757
+ # So this just removes the shape verts from the DummyDCC dictionary
1758
+ # and doesn't actually delete the shape from anywhere important
1759
+ splitSmpx.DCC.deleteShape(oldItem)
1760
+ splitSmpx.shapes.append(lItem)
1761
+ splitSmpx.shapes.append(rItem)
1762
+
1763
+ splitSmpx.DCC.pushAllShapeVertices(splitSmpx.shapes)
1764
+ return splitSmpx