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,1148 @@
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
+ """Alembic files can be difficult to work with, and can be *very* slow in Python
19
+ This is a library of convenience functions with the numpy speed optimizations
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import os
25
+
26
+ import numpy as np
27
+ import numpy.typing as npt
28
+ from alembic.Abc import (
29
+ IArchive,
30
+ ICompoundProperty,
31
+ IObject,
32
+ OArchive,
33
+ OCompoundProperty,
34
+ OStringProperty,
35
+ )
36
+ from alembic.AbcGeom import (
37
+ GeometryScope,
38
+ IPolyMesh,
39
+ IXform,
40
+ ON3fGeomParamSample,
41
+ OPolyMesh,
42
+ OPolyMeshSchema,
43
+ OPolyMeshSchemaSample,
44
+ OV2fGeomParamSample,
45
+ OXform,
46
+ )
47
+ from imath import Box3d, IntArray, UnsignedIntArray, V2f, V2fArray, V3fArray
48
+
49
+ try:
50
+ from imathnumpy import arrayToNumpy
51
+ except ImportError:
52
+ arrayToNumpy = None
53
+
54
+
55
+ from typing import (
56
+ TYPE_CHECKING,
57
+ Any,
58
+ TypeVar,
59
+ Union,
60
+ overload,
61
+ )
62
+
63
+ if TYPE_CHECKING:
64
+ from alembic.AbcGeom import _IBase # A helper typing-only class
65
+ from Qt.QtWidgets import QProgressDialog
66
+ else:
67
+ _IBase = QProgressDialog = Any
68
+
69
+ npfloat = npt.NDArray[Union[np.float32, np.float64]]
70
+ npint = npt.NDArray[Union[np.int32, np.int64]]
71
+
72
+ T = TypeVar("T", bound=Union[IntArray, UnsignedIntArray, V2fArray, V3fArray])
73
+
74
+
75
+ def pbPrint(
76
+ pBar: QProgressDialog | None,
77
+ message: str | None = None,
78
+ val: int | None = None,
79
+ maxVal: int | None = None,
80
+ _pbPrintLastComma=None,
81
+ ) -> None:
82
+ """A function that handles displaying messages in a QProgressDialog or printing to stdout
83
+
84
+ Don't forget to call QApplication.processEvents() after using this function
85
+
86
+ Parameters
87
+ ----------
88
+ pBar : QProgressDialog or None
89
+ An optional progress bar
90
+ message : str or None
91
+ An optional message to display
92
+ val : int or None
93
+ An optional progress value to display
94
+ maxVal : int or None
95
+ An optional maximum value to display
96
+ _pbPrintLastComma: object
97
+ INTERNAL USE ONLY
98
+ """
99
+ _pbPrintLastComma = [] if _pbPrintLastComma is None else _pbPrintLastComma
100
+
101
+ if pBar is not None:
102
+ if val is not None:
103
+ pBar.setValue(val)
104
+ if message is not None:
105
+ pBar.setLabelText(message)
106
+ else:
107
+ if message is not None:
108
+ if val is not None:
109
+ if maxVal is not None:
110
+ print(message, f"{val + 1: <4} of {maxVal: <4}\r", end=" ")
111
+ else:
112
+ print(message, f"{val + 1: <4}\r", end=" ")
113
+ # This is the ugliest, most terrible thing I think I've ever written
114
+ # Abusing the static default object to check if the last time
115
+ # this function was used, there was a trailing comma
116
+ # But damn if it doesn't make me laugh
117
+ if not _pbPrintLastComma:
118
+ _pbPrintLastComma.append("")
119
+ else:
120
+ if _pbPrintLastComma:
121
+ print(_pbPrintLastComma.pop())
122
+ print(message)
123
+
124
+
125
+ def mkArray(aType: type[T], iList: npt.NDArray) -> T:
126
+ """Makes the alembic-usable c++ typed 2-d arrays
127
+
128
+ Parameters
129
+ ----------
130
+ aType : imath type
131
+ The type of the output array
132
+ iList : list or np.array
133
+ The input iterable.
134
+
135
+ Returns
136
+ -------
137
+ : aType
138
+ The input list translated into an aType array
139
+ """
140
+ if isinstance(iList, aType):
141
+ return iList
142
+
143
+ size = len(iList)
144
+ array = aType(size)
145
+ if arrayToNumpy is None:
146
+ if isinstance(iList, np.ndarray):
147
+ for i in range(size):
148
+ array[i] = tuple(iList[i].tolist())
149
+ else:
150
+ for i in range(size):
151
+ array[i] = tuple(iList[i])
152
+ else:
153
+ nplist = np.array(iList)
154
+ memView = arrayToNumpy(array)
155
+ np.copyto(memView, nplist)
156
+ return array
157
+
158
+
159
+ def mk1dArray(aType: type[T], iList: npt.NDArray) -> T:
160
+ """Makes the alembic-usable c++ typed 1-d arrays
161
+
162
+ Parameters
163
+ ----------
164
+ aType : imath type
165
+ The type of the output array
166
+ iList : list or np.array
167
+ The input iterable.
168
+
169
+ Returns
170
+ -------
171
+ : aType
172
+ The input list translated into an aType array
173
+ """
174
+ if isinstance(iList, aType):
175
+ return iList
176
+
177
+ array = aType(len(iList))
178
+ if arrayToNumpy is None or aType is UnsignedIntArray:
179
+ for i in range(len(iList)):
180
+ # Gotta cast to int because an "int" from numpy has
181
+ # the type np.int32, which makes this conversion angry
182
+ array[i] = int(iList[i])
183
+ return array
184
+ else:
185
+ nplist = np.array(iList)
186
+ memView = arrayToNumpy(array)
187
+ np.copyto(memView, nplist)
188
+ return array
189
+
190
+
191
+ def mkSampleVertexPoints(pts: npfloat) -> V3fArray:
192
+ """Make an imath array of vertices
193
+
194
+ Parameters
195
+ ----------
196
+ pts : list or np.array
197
+ The input points
198
+
199
+ Returns
200
+ -------
201
+ : V3fArray
202
+ The output list
203
+ """
204
+ return mkArray(V3fArray, pts)
205
+
206
+
207
+ def mkSampleIntArray(vals: npint) -> IntArray:
208
+ """Make an imath array of integers
209
+
210
+ Parameters
211
+ ----------
212
+ pts : list or np.array
213
+ The input integers
214
+
215
+ Returns
216
+ -------
217
+ : IntArray
218
+ The output list
219
+ """
220
+ return mk1dArray(IntArray, vals)
221
+
222
+
223
+ def mkSampleUIntArray(vals: npint) -> UnsignedIntArray:
224
+ """Make an imath array of unsigned integers
225
+
226
+ Parameters
227
+ ----------
228
+ pts : list or np.array
229
+ The input unsigned integers
230
+
231
+ Returns
232
+ -------
233
+ : UnsignedIntArray
234
+ The output list
235
+ """
236
+ return mk1dArray(UnsignedIntArray, vals)
237
+
238
+
239
+ def mkSampleUvArray(uvs: npfloat) -> V2fArray:
240
+ """Make an imath array of uvs
241
+
242
+ Parameters
243
+ ----------
244
+ uvs : list or np.array
245
+ The input uvs
246
+
247
+ Returns
248
+ -------
249
+ : V2fArray
250
+ The output list
251
+ """
252
+ array = V2fArray(len(uvs))
253
+ setter = V2f(0, 0)
254
+ for i in range(len(uvs)):
255
+ setter.setValue(float(uvs[i][0]), float(uvs[i][1]))
256
+ array[i] = setter
257
+ return array
258
+
259
+
260
+ def mkUvSample(uvs: npfloat, indexes: npint | None = None) -> OV2fGeomParamSample:
261
+ """Take an array, and make a poly mesh sample of the uvs
262
+
263
+ Parameters
264
+ ----------
265
+ uvs : list or np.array
266
+ The input uvs
267
+ indexes : list or np.array or None
268
+ The optional face indices of the uvs
269
+
270
+ Returns
271
+ -------
272
+ : OV2fGeomParamSample
273
+ The UV sample
274
+ """
275
+ ary = mkSampleUvArray(uvs)
276
+ if indexes is None:
277
+ return OV2fGeomParamSample(ary, GeometryScope.kFacevaryingScope)
278
+ idxs = mkSampleUIntArray(indexes)
279
+ return OV2fGeomParamSample(ary, idxs, GeometryScope.kFacevaryingScope)
280
+
281
+
282
+ def mkNormalSample(norms: npfloat, indexes: npint | None = None) -> ON3fGeomParamSample:
283
+ """Take an array, and make a poly mesh sample of the normals
284
+
285
+ Parameters
286
+ ----------
287
+ norms : list or np.array
288
+ The input normals
289
+ indexes : list or np.array or None
290
+ The optional face indices of the normals
291
+
292
+ Returns
293
+ -------
294
+ : ON3fGeomParamSample
295
+ The Normal sample
296
+ """
297
+ ary = mkArray(V3fArray, norms)
298
+ if indexes is None:
299
+ return ON3fGeomParamSample(ary, GeometryScope.kFacevaryingScope)
300
+ idxs = mkSampleUIntArray(indexes)
301
+ return ON3fGeomParamSample(ary, idxs, GeometryScope.kFacevaryingScope)
302
+
303
+
304
+ def setAlembicSample(
305
+ omeshSch: OPolyMeshSchema,
306
+ points: V3fArray,
307
+ faceCount: IntArray,
308
+ faceIndex: IntArray,
309
+ bounds: Box3d | None = None,
310
+ uvs: OV2fGeomParamSample | None = None,
311
+ normals: ON3fGeomParamSample | None = None,
312
+ ) -> None:
313
+ """Set an alembic sample to the output mesh with the given properties"""
314
+ # Do it this way because the defaults for these arguments are some value other than None
315
+ kwargs = {}
316
+ if uvs is not None:
317
+ kwargs["iUVs"] = uvs
318
+ if normals is not None:
319
+ kwargs["iNormals"] = normals
320
+
321
+ s = OPolyMeshSchemaSample(points, faceIndex, faceCount, **kwargs)
322
+ if bounds is not None:
323
+ omeshSch.getChildBoundsProperty().setValue(bounds)
324
+ omeshSch.set(s)
325
+
326
+
327
+ def getSampleArrayIndex(
328
+ imesh: IPolyMesh, index: int = 0, pBar: QProgressDialog | None = None
329
+ ) -> npfloat:
330
+ """Get the per-frame vertex positions for a mesh
331
+
332
+ Parameters
333
+ ----------
334
+ imesh : IPolyMesh
335
+ The input alembic mesh object
336
+ index: int
337
+ The sample index to retrieve
338
+
339
+ Returns
340
+ -------
341
+ : np.array or list
342
+ The per-frame vertex positions
343
+ """
344
+ meshSchema = imesh.getSchema()
345
+ posProp = meshSchema.getPositionsProperty()
346
+ s = posProp.samples[index]
347
+ if arrayToNumpy is not None:
348
+ return arrayToNumpy(s).copy()
349
+ return np.array([list(s.x), list(s.y), list(s.z)]).T
350
+
351
+
352
+ def getSampleArray(imesh: IPolyMesh, pBar: QProgressDialog | None = None) -> npfloat:
353
+ """Get the per-frame vertex positions for a mesh
354
+
355
+ Parameters
356
+ ----------
357
+ imesh : IPolyMesh
358
+ The input alembic mesh object
359
+
360
+ Returns
361
+ -------
362
+ : np.array or list
363
+ The per-frame vertex positions
364
+ """
365
+ meshSchema = imesh.getSchema()
366
+ posProp = meshSchema.getPositionsProperty()
367
+ numShapes = len(posProp.samples)
368
+ if arrayToNumpy is not None:
369
+ shapes = np.empty((len(posProp.samples), len(posProp.samples[0]), 3))
370
+ for i, s in enumerate(posProp.samples):
371
+ pbPrint(pBar, message="Reading Shape", val=i, maxVal=numShapes)
372
+ shapes[i] = arrayToNumpy(s)
373
+ return shapes
374
+ else:
375
+ shapes = []
376
+ for i, s in enumerate(posProp.samples):
377
+ pbPrint(pBar, message="Reading Shape", val=i, maxVal=numShapes)
378
+ shapes.append((list(s.x), list(s.y), list(s.z)))
379
+ shapes = np.array(shapes)
380
+ shapes = shapes.transpose((0, 2, 1))
381
+ return shapes
382
+
383
+
384
+ def getStaticMeshData(imesh: IPolyMesh) -> tuple[IntArray, IntArray]:
385
+ """Get all the generally non-changing data for a mesh
386
+
387
+ Parameters
388
+ ----------
389
+ imesh : IPolyMesh
390
+ The input alembic mesh object
391
+
392
+ Returns
393
+ -------
394
+ : IntArray
395
+ A flat alembic array of vertex indices for the faces
396
+ : IntArray
397
+ The number of vertices per face
398
+ """
399
+ sch = imesh.getSchema()
400
+ faces = sch.getFaceIndicesProperty().samples[0]
401
+ counts = sch.getFaceCountsProperty().samples[0]
402
+ return faces, counts
403
+
404
+
405
+ def getStaticMeshArrays(imesh: IPolyMesh) -> tuple[npint, npint]:
406
+ """Get all the generally non-changing data for a mesh as numpy arrays
407
+
408
+ Parameters
409
+ ----------
410
+ imesh : IPolyMesh
411
+ The input alembic mesh object
412
+
413
+ Returns
414
+ -------
415
+ : np.array or list
416
+ A flat of vertex indices for the faces as np.array if possible
417
+ : np.array or list
418
+ The number of vertices per face as np.array if possible
419
+ """
420
+ faces, counts = getStaticMeshData(imesh)
421
+ if arrayToNumpy is not None:
422
+ faces = arrayToNumpy(faces).copy()
423
+ counts = arrayToNumpy(counts).copy()
424
+ else:
425
+ faces, counts = np.array(faces), np.array(counts)
426
+ return faces, counts
427
+
428
+
429
+ def getUvSample(imesh: IPolyMesh) -> OV2fGeomParamSample | None:
430
+ """Get the UV's for a mesh
431
+
432
+ Parameters
433
+ ----------
434
+ imesh : IPolyMesh
435
+ The input alembic mesh object
436
+
437
+ Returns
438
+ -------
439
+ : OV2fGeomParamSample
440
+ The UV Sample
441
+ """
442
+ imeshsch = imesh.getSchema()
443
+ uvParam = imeshsch.getUVsParam()
444
+
445
+ if not uvParam.valid():
446
+ return None
447
+
448
+ uvValue = uvParam.getValueProperty().getValue()
449
+ if uvParam.isIndexed():
450
+ idxValue = uvParam.getIndexProperty().getValue()
451
+ uv = OV2fGeomParamSample(uvValue, idxValue, GeometryScope.kFacevaryingScope)
452
+ else:
453
+ uv = OV2fGeomParamSample(uvValue, GeometryScope.kFacevaryingScope)
454
+ return uv
455
+
456
+
457
+ def getUvArray(imesh: IPolyMesh) -> npfloat | None:
458
+ """Get the uv positions for a mesh
459
+
460
+ Parameters
461
+ ----------
462
+ imesh : IPolyMesh
463
+ The input alembic mesh object
464
+
465
+ Returns
466
+ -------
467
+ : list or np.array or None
468
+ The UVs if they exist as a numpy array if possible
469
+ """
470
+ imeshsch = imesh.getSchema()
471
+ uvParam = imeshsch.getUVsParam()
472
+ if uvParam.valid():
473
+ uvProp = uvParam.getValueProperty()
474
+ uvVals = uvProp.getValue()
475
+ if arrayToNumpy is None:
476
+ uv = list(zip(uvVals.x, uvVals.y))
477
+ uv = np.array(uv)
478
+ else:
479
+ uv = arrayToNumpy(uvVals)
480
+ else:
481
+ uv = None
482
+ return uv
483
+
484
+
485
+ def getFlatUvFaces(imesh: IPolyMesh) -> tuple[npint | None, bool | None]:
486
+ """Get the UV structure for a mesh if it's indexed. If un-indexed, return None
487
+ This means that if we have valid UVs, but invalid uvFaces, then we're un-indexed
488
+ and can handle the data appropriately for export without keeping track of index-ness
489
+
490
+ Parameters
491
+ ----------
492
+ imesh : IPolyMesh
493
+ The input alembic mesh object
494
+
495
+ Returns
496
+ -------
497
+ : [int, ...] or np.array
498
+ The UVFace structure
499
+ : bool
500
+ Whether we share uvs between uvFaces (True), or we have a uv per face-vertex (False)
501
+ """
502
+ sch = imesh.getSchema()
503
+ iuvs = sch.getUVsParam()
504
+ idxs = None
505
+ indexed = None
506
+ if iuvs.valid():
507
+ if iuvs.isIndexed():
508
+ indexed = True
509
+ idxs = iuvs.getIndexProperty().getValue()
510
+ idxs = np.array(idxs)
511
+ else:
512
+ indexed = False
513
+ rawCount = sum(list(sch.getFaceCountsProperty().samples[0]))
514
+ idxs = np.arange(rawCount)
515
+
516
+ return idxs, indexed
517
+
518
+
519
+ def getUvFaces(imesh: IPolyMesh) -> list[list[int]] | None:
520
+ """Get the UV structure for a mesh if it's indexed. If un-indexed, return None
521
+ This means that if we have valid UVs, but invalid uvFaces, then we're un-indexed
522
+ and can handle the data appropriately for export without keeping track of index-ness
523
+
524
+ Parameters
525
+ ----------
526
+ imesh : IPolyMesh
527
+ The input alembic mesh object
528
+
529
+ Returns
530
+ -------
531
+ : [[int, ...], ...]
532
+ The UVFace structure
533
+ """
534
+ sch = imesh.getSchema()
535
+ rawCounts = sch.getFaceCountsProperty().samples[0]
536
+ iuvs = sch.getUVsParam()
537
+ uvFaces = None
538
+ if iuvs.valid():
539
+ uvFaces = []
540
+ uvCounter = 0
541
+ if iuvs.isIndexed():
542
+ idxs = list(iuvs.getIndexProperty().getValue())
543
+ for count in rawCounts:
544
+ uvFaces.append(list(idxs[uvCounter : uvCounter + count]))
545
+ uvCounter += count
546
+ return uvFaces
547
+
548
+
549
+ def getMeshFaces(imesh: IPolyMesh) -> list[list[int]]:
550
+ """Get The vertex indices used per face
551
+
552
+ Parameters
553
+ ----------
554
+ imesh : IPolyMesh
555
+ The input alembic mesh object
556
+
557
+ Returns
558
+ -------
559
+ : [[int, ...], ...]
560
+ The UVFace structure
561
+ """
562
+ rawFaces, rawCounts = getStaticMeshData(imesh)
563
+ faces = []
564
+ ptr = 0
565
+ for count in rawCounts:
566
+ chunk = rawFaces[ptr : ptr + count]
567
+ faces.append(list(chunk))
568
+ ptr += count
569
+ return faces
570
+
571
+
572
+ def getPointCount(imesh: IPolyMesh) -> int:
573
+ """Get the number of vertices in a mesh
574
+
575
+ Parameters
576
+ ----------
577
+ imesh : IPolyMesh
578
+ The input alembic mesh object
579
+
580
+ Returns
581
+ -------
582
+ : int
583
+ The number of vertices in the mesh
584
+ """
585
+ meshSchema = imesh.getSchema()
586
+ posProp = meshSchema.getPositionsProperty()
587
+ return len(posProp.samples[0])
588
+
589
+
590
+ B = TypeVar("B", bound=_IBase)
591
+
592
+
593
+ @overload
594
+ def findAlembicObject(
595
+ obj: IObject, abcType: None = None, name: str | None = None
596
+ ) -> IObject | None: ...
597
+
598
+
599
+ @overload
600
+ def findAlembicObject(
601
+ obj: IObject, abcType: type[B], name: str | None = None
602
+ ) -> B | None: ...
603
+
604
+
605
+ def findAlembicObject(
606
+ obj: IObject, abcType: type[B] | None = None, name: str | None = None
607
+ ) -> IObject | B | None:
608
+ """Finds a single object in an alembic archive by name and/or type
609
+ If only type is specified, then the first object of that type
610
+ encountered will be returned
611
+ """
612
+ md = obj.getMetaData()
613
+ if abcType is None:
614
+ if name is None or obj.getName() == name:
615
+ return obj
616
+ elif abcType.matches(md):
617
+ if name is None or obj.getName() == name:
618
+ return abcType(obj.getParent(), obj.getName())
619
+ for child in obj.children:
620
+ out = findAlembicObject(child, abcType, name)
621
+ if out is not None:
622
+ return out
623
+ return None
624
+
625
+
626
+ def findAllAlembicObjects(
627
+ obj: IObject,
628
+ abcType: type[_IBase] | None = None,
629
+ out: list[IObject] | None = None,
630
+ ) -> list[IObject]:
631
+ """Finds all objects of a type in an alembic archive"""
632
+ md = obj.getMetaData()
633
+ out = [] if out is None else out
634
+ if abcType is None:
635
+ out.append(obj)
636
+ elif abcType.matches(md):
637
+ out.append(abcType(obj.getParent(), obj.getName()))
638
+ for child in obj.children:
639
+ findAllAlembicObjects(child, abcType, out)
640
+ return out
641
+
642
+
643
+ def getTypedIObject(obj: IObject) -> _IBase | None:
644
+ from alembic.AbcGeom import (
645
+ ICamera,
646
+ ICurves,
647
+ ILight,
648
+ INuPatch,
649
+ IPoints,
650
+ IPolyMesh,
651
+ ISubD,
652
+ IXform,
653
+ )
654
+
655
+ md = obj.getMetaData()
656
+ for abcType in (
657
+ IXform,
658
+ IPolyMesh,
659
+ ICamera,
660
+ ICurves,
661
+ ILight,
662
+ INuPatch,
663
+ IPoints,
664
+ ISubD,
665
+ ):
666
+ if abcType.matches(md):
667
+ return abcType(obj.getParent(), obj.getName())
668
+ return None
669
+
670
+
671
+ def getMesh(infile: str) -> IPolyMesh | None:
672
+ """Get the first found mesh object from the alembic filepath"""
673
+ iarch = IArchive(str(infile))
674
+ ipolymsh = findAlembicObject(iarch.getTop(), abcType=IPolyMesh)
675
+ return ipolymsh
676
+
677
+
678
+ def writeStringProperty(
679
+ props: OCompoundProperty, key: str, value: str, ogawa: bool = True
680
+ ) -> None:
681
+ """Write the definition string to an alembic OObject
682
+
683
+ HDF5 (which we must still support) has a character limit
684
+ to string properties. Splitting the string must be handled
685
+ in a uniform way, so this function must be used
686
+
687
+ Parameters
688
+ ----------
689
+ props : OCompoundProperty
690
+ The alembic OObject properties
691
+ value : str
692
+ The simplex definition string
693
+ ogawa : bool
694
+ If the output is ogawa
695
+
696
+ """
697
+ if len(value) > 65000 and not ogawa:
698
+ value = str(value)
699
+ numChunks = (len(value) // 65000) + 1
700
+ chunkSize = (len(value) // numChunks) + 1
701
+ for c in range(numChunks):
702
+ prop = OStringProperty(props, f"{key}{c}")
703
+ prop.setValue(value[chunkSize * c : chunkSize * (c + 1)])
704
+ else:
705
+ prop = OStringProperty(props, str(key))
706
+ prop.setValue(str(value))
707
+
708
+
709
+ def readStringProperty(props: ICompoundProperty, key: str) -> str:
710
+ """Read the definition string from an alembic OObject
711
+
712
+ HDF5 (which we must still support) has a character limit
713
+ to string properties. Splitting the string must be handled
714
+ in a uniform way, so this function must be used
715
+
716
+ Parameters
717
+ ----------
718
+ props : ICompoundProperty
719
+ The alembic IObject properties
720
+
721
+ Returns
722
+ -------
723
+ : str
724
+ The simplex definition string
725
+ """
726
+ if not props.valid():
727
+ raise ValueError(".smpx file is missing the alembic user properties")
728
+
729
+ try:
730
+ prop = props.getProperty(key)
731
+ except KeyError:
732
+ parts = []
733
+ for c in range(10):
734
+ try:
735
+ prop = props.getProperty(f"{key}{c}")
736
+ except KeyError:
737
+ if c == 0:
738
+ raise
739
+ break
740
+ else:
741
+ parts.append(prop.getValue())
742
+ else:
743
+ raise ValueError("That is a HELL of a long simplex definition")
744
+ jsString = "".join(parts)
745
+ else:
746
+ jsString = prop.getValue()
747
+
748
+ return jsString
749
+
750
+
751
+ def flattenFaces(faces: list[list[int]]) -> tuple[npint, npint]:
752
+ """Take a nested list representation of faces
753
+ and turn it into a flat face/count representation
754
+
755
+ Parameters
756
+ ----------
757
+ faces : [[int, ...], ...]
758
+ The nested list representation
759
+
760
+ Returns
761
+ -------
762
+ : np.array or list
763
+ The flat list of face connectivity
764
+ : np.array or list
765
+ The flat list of vertices per face
766
+
767
+ """
768
+ faceCounts, faceIdxs = [], []
769
+ for f in faces:
770
+ faceCounts.append(len(f))
771
+ faceIdxs.extend(f)
772
+ return np.array(faceCounts), np.array(faceIdxs)
773
+
774
+
775
+ def unflattenFaces(faces: npint, counts: npint) -> list[list[int]]:
776
+ """Take a flat face/count representation of faces
777
+ and turn it into a nested list representation
778
+
779
+ Parameters
780
+ ----------
781
+ faces : np.array
782
+ The flat list of face connectivity
783
+ counts : np.array
784
+ The flat list of vertices per face
785
+
786
+ Returns
787
+ -------
788
+ : [[int, ...], ...]
789
+ The nested list representation
790
+ """
791
+ out, ptr = [], 0
792
+ for c in counts:
793
+ out.append(faces[ptr : ptr + c].tolist())
794
+ ptr += c
795
+ return out
796
+
797
+
798
+ def buildAbc(
799
+ outPath: str,
800
+ points: npfloat,
801
+ faces: npint,
802
+ faceCounts: npint | None = None,
803
+ uvs: npfloat | None = None,
804
+ uvFaces: npint | None = None,
805
+ normals: npfloat | None = None,
806
+ normFaces: npint | None = None,
807
+ name: str = "polymsh",
808
+ shapeSuffix: str = "Shape",
809
+ transformSuffix: str = "",
810
+ propDict: dict[str, str] | None = None,
811
+ ogawa: bool = True,
812
+ pBar: QProgressDialog | None = None,
813
+ ) -> None:
814
+ """
815
+ Build a single-mesh alembic file from all of the non-alembic raw data
816
+
817
+ Parameters
818
+ ----------
819
+ outPath: str
820
+ The output path for the alembic file
821
+ points: list or ndarray
822
+ The list or array of points. Single multiple frames supported
823
+ faces: list
824
+ A list of lists of face indices, or a flattened list of indices.
825
+ If flat, then faceCounts must be provided
826
+ faceCounts: list
827
+ A list of the number of vertices per face. Defaults to None
828
+ uvs: list or ndarray
829
+ The Uvs for this mesh. Defaults to None
830
+ uvFaces: list
831
+ A list of lists of face indices, or a flattened list of indices.
832
+ If flat, then faceCounts must be provided. Defaults to None
833
+ normals: list or ndarray
834
+ The Normals for this mesh. Defaults to None
835
+ normFaces: list
836
+ A list of lists of face indices, or a flattened list of indices.
837
+ If flat, then faceCounts must be provided. Defaults to None
838
+ name: str
839
+ The name to give this mesh. Defaults to "polymsh"
840
+ shapeSuffix: str
841
+ The suffix to add to the shape of this mesh. Defaults to "Shape"
842
+ transformSuffix: str
843
+ The suffix to add to the transform of this mesh. Defaults to ""
844
+ propDict: dict
845
+ A dictionary of properties to add to the xform object
846
+ ogawa : bool
847
+ Whether to write to the Ogawa (True) or HDF5 (False) backend
848
+ pBar : QProgressDialog, optional
849
+ An optional progress dialog
850
+ """
851
+ if faceCounts is None:
852
+ # All the faces are in list-of-list format
853
+ # put them in index-count format
854
+ faceCounts, faces = flattenFaces(faces)
855
+ if uvFaces is not None:
856
+ _, uvFaces = flattenFaces(uvFaces)
857
+ if normFaces is not None:
858
+ _, normFaces = flattenFaces(normFaces)
859
+
860
+ faceCounts = mkSampleIntArray(faceCounts)
861
+ faces = mkSampleIntArray(faces)
862
+
863
+ if not isinstance(uvs, OV2fGeomParamSample):
864
+ if uvFaces is not None and uvs is not None:
865
+ uvs = mkUvSample(uvs, indexes=uvFaces)
866
+
867
+ if not isinstance(normals, ON3fGeomParamSample):
868
+ if normFaces is not None and normals is not None:
869
+ normals = mkNormalSample(normals, indexes=normFaces)
870
+
871
+ oarch = OArchive(str(outPath), ogawa)
872
+ parent, opar, props, omesh, sch = None, None, None, None, None
873
+ try:
874
+ parent = oarch.getTop()
875
+ opar = OXform(parent, str(name + transformSuffix))
876
+ if propDict:
877
+ props = opar.getSchema().getUserProperties()
878
+ for k, v in propDict.items():
879
+ writeStringProperty(props, str(k), str(v), ogawa=ogawa)
880
+
881
+ omesh = OPolyMesh(opar, str(name + shapeSuffix))
882
+
883
+ points = np.array(points)
884
+ if len(points.shape) == 2:
885
+ points = points[None, ...]
886
+
887
+ sch = omesh.getSchema()
888
+ for i, frame in enumerate(points):
889
+ pbPrint(pBar, message="Exporting Shape", val=i, maxVal=len(points))
890
+ abcFrame = mkSampleVertexPoints(frame)
891
+ setAlembicSample(sch, abcFrame, faceCounts, faces, uvs=uvs, normals=normals)
892
+
893
+ pbPrint(pBar, message="Done Exporting")
894
+ finally:
895
+ # Make sure all this gets deleted so the file is freed
896
+ del parent, opar, props, omesh, sch
897
+
898
+
899
+ # Simplex format specific stuff
900
+ def getSmpxArchiveData(abcPath: str) -> tuple[IArchive, IPolyMesh, str]:
901
+ """Read and return the low level relevant data from a simplex alembic
902
+
903
+ Parameters
904
+ ----------
905
+ abcPath : str
906
+ The path to the .smpx file
907
+
908
+ Returns
909
+ -------
910
+ : IArchive
911
+ An opened Alembic IArchive object handle
912
+ : IPolyMesh
913
+ An Alembic Mesh handle
914
+ : str
915
+ The json definition string
916
+ """
917
+ if not os.path.isfile(str(abcPath)):
918
+ raise OSError("File does not exist: " + str(abcPath))
919
+ iarch = IArchive(str(abcPath)) # because alembic hates unicode
920
+ top, par, abcMesh = [None] * 3
921
+ try:
922
+ top = iarch.getTop()
923
+ par = top.children[0]
924
+ par = IXform(top, par.getName())
925
+ abcMesh = par.children[0]
926
+ abcMesh = IPolyMesh(par, abcMesh.getName())
927
+ # I *could* come up with a generic property reader
928
+ # but it's useless for me at this time
929
+ sch = par.getSchema()
930
+ props = sch.getUserProperties()
931
+ jsString = readStringProperty(props, "simplex")
932
+
933
+ except Exception:
934
+ # ensure that the .smpx file is released
935
+ iarch, top, par, abcMesh = [None] * 4
936
+ raise
937
+
938
+ # Must return the archive, otherwise it gets GC'd
939
+ return iarch, abcMesh, jsString
940
+
941
+
942
+ def readSmpx(
943
+ path: str, pBar: QProgressDialog | None = None
944
+ ) -> tuple[str, npint, npfloat, npint, npfloat | None, npint | None]:
945
+ """Read and return the raw alembic vertex/face data in the flat alembic style
946
+
947
+ Parameters
948
+ ----------
949
+ abcPath : str
950
+ The path to the .smpx file
951
+ pBar : QProgressDialog, optional
952
+ An optional progress dialog
953
+
954
+ Returns
955
+ -------
956
+ : str
957
+ The simplex definition string
958
+ : [int, ...] or np.array
959
+ The number of vertices per face
960
+ : [[(float*3), ...], ...] or np.array
961
+ The vertex positions per shape
962
+ : [int, ...] or np.array
963
+ The flat indexes per face
964
+ : [(float*2), ...] or np.array or None
965
+ The UV's
966
+ : [int, ...] or np.array
967
+ The flat indexes per uv-face
968
+ """
969
+ iarch, abcMesh, jsString = getSmpxArchiveData(path)
970
+ try:
971
+ faces, counts = getStaticMeshArrays(abcMesh)
972
+ verts = getSampleArray(abcMesh, pBar=pBar)
973
+ uvs = getUvArray(abcMesh)
974
+ uvFaces, _ = getFlatUvFaces(abcMesh)
975
+ finally:
976
+ del iarch, abcMesh
977
+ return jsString, counts, verts, faces, uvs, uvFaces
978
+
979
+
980
+ def buildSmpx(
981
+ outPath: str,
982
+ points: npfloat,
983
+ faces: npint,
984
+ jsString: str,
985
+ name: str,
986
+ faceCounts: npint | None = None,
987
+ uvs: npfloat | None = None,
988
+ uvFaces: npint | None = None,
989
+ ogawa: bool = True,
990
+ pBar: QProgressDialog | None = None,
991
+ ) -> None:
992
+ """
993
+ Build a simplex output from raw data
994
+
995
+ Parameters
996
+ ----------
997
+ outPath: str
998
+ The output path for the alembic file
999
+ points: list or ndarray
1000
+ The list or array of points. Single multiple frames supported
1001
+ faces: list
1002
+ A list of lists of face indices, or a flattened list of indices.
1003
+ If flat, then faceCounts must be provided
1004
+ jsString : str
1005
+ The simplex definition string
1006
+ name: str
1007
+ The name to give this mesh
1008
+ faceCounts: list
1009
+ A list of the number of vertices per face. Defaults to None
1010
+ uvs: list or ndarray
1011
+ The Uvs for this mesh. Defaults to None
1012
+ uvFaces: list
1013
+ A list of lists of face indices, or a flattened list of indices.
1014
+ If flat, then faceCounts must be provided. Defaults to None
1015
+ ogawa : bool
1016
+ Whether to write to the Ogawa (True) or HDF5 (False) backend
1017
+ pBar : QProgressDialog, optional
1018
+ An optional progress dialog
1019
+ """
1020
+ buildAbc(
1021
+ outPath,
1022
+ points,
1023
+ faces,
1024
+ faceCounts=faceCounts,
1025
+ uvs=uvs,
1026
+ uvFaces=uvFaces,
1027
+ name=name,
1028
+ shapeSuffix="",
1029
+ transformSuffix="",
1030
+ propDict={"simplex": jsString},
1031
+ ogawa=ogawa,
1032
+ pBar=pBar,
1033
+ )
1034
+
1035
+
1036
+ def buildAlembicArchiveData(
1037
+ path: str, name: str, jsString: str, ogawa: bool
1038
+ ) -> tuple[OArchive | None, OPolyMesh | None]:
1039
+ """Set up an output alembic archive with a mesh ready for writing
1040
+
1041
+ Parameters
1042
+ ----------
1043
+ path : str
1044
+ The output file path
1045
+ name : str
1046
+ The name of the system
1047
+ jsString : str
1048
+ The simplex definition string
1049
+ ogawa : bool
1050
+ Whether to open in Ogawa (True) or HDF5 (False) mode
1051
+
1052
+ Returns
1053
+ -------
1054
+ : OArchive
1055
+ The opened alembic output archive
1056
+ : OPolyMesh
1057
+ The mesh to write the shape data to
1058
+
1059
+ """
1060
+ arch = OArchive(str(path), ogawa)
1061
+ par, props, abcMesh = [None] * 3
1062
+ try:
1063
+ par = OXform(arch.getTop(), str(name))
1064
+ props = par.getSchema().getUserProperties()
1065
+ writeStringProperty(props, "simplex", jsString, ogawa=ogawa)
1066
+ abcMesh = OPolyMesh(par, str(name))
1067
+ except Exception:
1068
+ arch, par, props, abcMesh = [None] * 4
1069
+ raise
1070
+ return arch, abcMesh
1071
+
1072
+
1073
+ def readFalloffData(abcPath: str) -> dict[str, npfloat]:
1074
+ """Load the relevant data from a simplex alembic
1075
+
1076
+ Parameters
1077
+ ----------
1078
+ abcPath : str
1079
+ Path to the .smpx file
1080
+
1081
+ """
1082
+ if not os.path.isfile(str(abcPath)):
1083
+ raise OSError("File does not exist: " + str(abcPath))
1084
+ iarch = IArchive(str(abcPath)) # because alembic hates unicode
1085
+ top, par, systemSchema, foPropPar, foProp = [None] * 5
1086
+ try:
1087
+ top = iarch.getTop()
1088
+ par = top.children[0]
1089
+ par = IXform(top, par.getName())
1090
+ systemSchema = par.getSchema()
1091
+ props = systemSchema.getUserProperties()
1092
+ foDict = {}
1093
+ try:
1094
+ foPropPar = props.getProperty("falloffs")
1095
+ except KeyError:
1096
+ pass
1097
+ else:
1098
+ nps = foPropPar.getNumProperties()
1099
+ for i in range(nps):
1100
+ foProp = foPropPar.getProperty(i)
1101
+ foDict[foProp.getName()] = np.array(foProp.getValue())
1102
+ finally:
1103
+ iarch, top, par, systemSchema, foPropPar, foProp = [None] * 6
1104
+
1105
+ return foDict
1106
+
1107
+
1108
+ def getIArchive(filepath: str | list[str]) -> IArchive:
1109
+ """Get the IArchive from the given path, but check if the file exists
1110
+ first and raise an appropriate error if it doesn't
1111
+
1112
+ Parameters
1113
+ ----------
1114
+ abcPath : str
1115
+ Path to the .smpx file
1116
+
1117
+ Returns
1118
+ -------
1119
+ IArchive :
1120
+ The opened IArchive
1121
+ """
1122
+ if not filepath:
1123
+ raise ValueError("Invalid Filepath: {0}".format(filepath))
1124
+
1125
+ # Alembic 1.7+ allows for opening multiple caches at the same time
1126
+ # since I use that, I will just *always* use a list for consistency
1127
+ if isinstance(filepath, str):
1128
+ filepath = [filepath]
1129
+
1130
+ if not isinstance(filepath, (list, tuple)):
1131
+ raise TypeError("Invalid Filepath Type: {0}".format(filepath))
1132
+
1133
+ # Make sure all the paths are stringified so alembic doesn't complain
1134
+ # Alembic crashes with unicode filepaths in py2
1135
+ filepath = [str(i) for i in filepath]
1136
+
1137
+ # Check for file existence
1138
+ for fp in filepath:
1139
+ if not os.path.exists(str(fp)):
1140
+ raise OSError("Filepath does not exist: {0}".format(fp))
1141
+
1142
+ try:
1143
+ return IArchive(filepath)
1144
+ except Exception as e:
1145
+ # Make sure to include the filepath list in any other errors that alembic throws
1146
+ errArgs = list(e.args)
1147
+ errArgs[0] = f"{errArgs[0]}: {filepath}"
1148
+ raise type(e)(*errArgs) from e