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