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