simplex-solver 3.1.0__39-abi3-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. simplex_solver-3.1.0.dist-info/METADATA +90 -0
  2. simplex_solver-3.1.0.dist-info/RECORD +79 -0
  3. simplex_solver-3.1.0.dist-info/WHEEL +5 -0
  4. simplexui/__init__.py +53 -0
  5. simplexui/_version.py +1 -0
  6. simplexui/channelBox.py +858 -0
  7. simplexui/comboCheckDialog.py +343 -0
  8. simplexui/commands/__init__.py +16 -0
  9. simplexui/commands/alembicCommon.py +991 -0
  10. simplexui/commands/applyCorrectives.py +451 -0
  11. simplexui/commands/correctiveInterface.py +261 -0
  12. simplexui/commands/expandedExport.py +436 -0
  13. simplexui/commands/hdf5Convert.py +60 -0
  14. simplexui/commands/mayaCorrectiveInterface.py +161 -0
  15. simplexui/commands/mayatonumpy.py +375 -0
  16. simplexui/commands/mesh.py +1081 -0
  17. simplexui/commands/numpytoimath.py +319 -0
  18. simplexui/commands/poseblendlib.py +166 -0
  19. simplexui/commands/reorderSimplexPoints.py +102 -0
  20. simplexui/commands/rigidAlign.py +99 -0
  21. simplexui/commands/smpxBlend.py +629 -0
  22. simplexui/commands/unsubdivide.py +1227 -0
  23. simplexui/commands/uvTransfer.py +977 -0
  24. simplexui/dragFilter.py +299 -0
  25. simplexui/falloffDialog.py +471 -0
  26. simplexui/img/ChefHead.png +0 -0
  27. simplexui/img/frozen.png +0 -0
  28. simplexui/interface/__init__.py +28 -0
  29. simplexui/interface/dummyInterface.py +1585 -0
  30. simplexui/interface/mayaInterface.py +3271 -0
  31. simplexui/interfaceModel.py +1053 -0
  32. simplexui/interfaceModelTrees.py +441 -0
  33. simplexui/items/__init__.py +42 -0
  34. simplexui/items/accessor.py +213 -0
  35. simplexui/items/combo.py +852 -0
  36. simplexui/items/falloff.py +778 -0
  37. simplexui/items/group.py +297 -0
  38. simplexui/items/progression.py +743 -0
  39. simplexui/items/shape.py +443 -0
  40. simplexui/items/simplex.py +1764 -0
  41. simplexui/items/slider.py +738 -0
  42. simplexui/items/stack.py +154 -0
  43. simplexui/items/traversal.py +966 -0
  44. simplexui/main.pyw +22 -0
  45. simplexui/menu/__init__.py +69 -0
  46. simplexui/menu/dummyPlugins/__init__.py +16 -0
  47. simplexui/menu/genericPlugins/__init__.py +16 -0
  48. simplexui/menu/genericPlugins/_builtins.py +268 -0
  49. simplexui/menu/genericPlugins/checkPossibleCombos.py +45 -0
  50. simplexui/menu/genericPlugins/exportSplit.py +59 -0
  51. simplexui/menu/genericPlugins/showFalloffs.py +24 -0
  52. simplexui/menu/genericPlugins/showTraversals.py +24 -0
  53. simplexui/menu/genericPlugins/simplexUvTransfer.py +107 -0
  54. simplexui/menu/genericPlugins/unsubdivide.py +70 -0
  55. simplexui/menu/mayaPlugins/__init__.py +16 -0
  56. simplexui/menu/mayaPlugins/exportOther.py +43 -0
  57. simplexui/menu/mayaPlugins/extractProgressives.py +65 -0
  58. simplexui/menu/mayaPlugins/freezeCombo.py +245 -0
  59. simplexui/menu/mayaPlugins/generateShapeIncrementals.py +97 -0
  60. simplexui/menu/mayaPlugins/importObjs.py +193 -0
  61. simplexui/menu/mayaPlugins/linearizeTraversal.py +48 -0
  62. simplexui/menu/mayaPlugins/makeShelfBtn.py +65 -0
  63. simplexui/menu/mayaPlugins/relaxToSelection.py +75 -0
  64. simplexui/menu/mayaPlugins/reloadDefinition.py +33 -0
  65. simplexui/menu/mayaPlugins/snapToNeutral.py +72 -0
  66. simplexui/menu/mayaPlugins/softSelectToCluster.py +200 -0
  67. simplexui/menu/mayaPlugins/tweakMix.py +134 -0
  68. simplexui/menu/mayaPlugins/updateRestShape.py +105 -0
  69. simplexui/pysimplex.dll.a +0 -0
  70. simplexui/pysimplex.pyd +0 -0
  71. simplexui/simplexDialog.py +1454 -0
  72. simplexui/travCheckDialog.py +397 -0
  73. simplexui/traversalDialog.py +271 -0
  74. simplexui/ui/comboCheckDialog.ui +475 -0
  75. simplexui/ui/falloffDialog.ui +243 -0
  76. simplexui/ui/simplexDialog.ui +1458 -0
  77. simplexui/ui/travCheckDialog.ui +488 -0
  78. simplexui/ui/traversalDialog.ui +532 -0
  79. simplexui/utils.py +320 -0
@@ -0,0 +1,977 @@
1
+ # Copyright 2016, Blur Studio
2
+ #
3
+ # This file is part of Simplex.
4
+ #
5
+ # Simplex is free software: you can redistribute it and/or modify
6
+ # it under the terms of the GNU Lesser General Public License as published by
7
+ # the Free Software Foundation, either version 3 of the License, or
8
+ # (at your option) any later version.
9
+ #
10
+ # Simplex is distributed in the hope that it will be useful,
11
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ # GNU Lesser General Public License for more details.
14
+ #
15
+ # You should have received a copy of the GNU Lesser General Public License
16
+ # along with Simplex. If not, see <http://www.gnu.org/licenses/>.
17
+
18
+ # pylint: disable=invalid-name
19
+ import numpy as np
20
+
21
+ INF = float("inf")
22
+ EPS = 1e-7
23
+
24
+
25
+ ########################
26
+ # Mean Value Coords
27
+ ########################
28
+
29
+
30
+ def _lerp(idx, corners, p):
31
+ # If I'm here, I know that p lies on the line
32
+ # between the corners at idx and idx+1.
33
+ # Return the lerp value
34
+ ip = (idx + 1) % len(corners)
35
+ c1 = corners[idx]
36
+ c2 = corners[ip]
37
+ base = c1 - c2
38
+ proj = np.dot(p - c2, base)
39
+ b = proj / (base**2).sum()
40
+ ret = np.zeros(len(corners))
41
+ ret[idx] = b
42
+ ret[ip] = 1.0 - b
43
+ return ret
44
+
45
+
46
+ def mvc(corners, p, tol=EPS):
47
+ """Get the Mean Value Coordinates of a point p in the polygon defined by corners
48
+
49
+ Parameters
50
+ ----------
51
+ corners : [int, ...]
52
+ A list of corner indices
53
+ p : np.array
54
+ The array of points
55
+ tol : float
56
+ A small tolerance value, defaulting to the global EPS
57
+
58
+ Returns
59
+ -------
60
+ : list
61
+ The normalized list of barycentric weights for this point in the polygon
62
+
63
+ """
64
+ spokes = corners - p
65
+ spokeLens = (spokes * spokes).sum(axis=1)
66
+
67
+ # Check if p is on top of a vertex
68
+ for i, v in enumerate(spokeLens):
69
+ if v < tol:
70
+ bary = np.zeros(len(corners))
71
+ bary[i] = 1.0
72
+ return bary
73
+
74
+ rspokes = np.roll(spokes, -1, axis=0)
75
+ areas = np.cross(spokes, rspokes) * 0.5
76
+ dots = (spokes * rspokes).sum(axis=1)
77
+
78
+ for i, v in enumerate(areas):
79
+ if v < tol and dots[i] < 0.0:
80
+ return _lerp(i, corners, p)
81
+
82
+ spokeLens = spokeLens**0.5
83
+ rspokeLens = np.roll(spokeLens, -1)
84
+ t = areas / (spokeLens * rspokeLens + dots)
85
+ rawWeights = (np.roll(t, 1) + t) / spokeLens
86
+ return rawWeights / sum(rawWeights)
87
+
88
+
89
+ def mmvc(rawFaces, points, samples, uvToFace, tol=EPS):
90
+ """Multi-MeanValueCoords
91
+ Get the MVC's of many points over many faces using numpy
92
+
93
+ Parameters
94
+ ----------
95
+ rawFaces : [[int, ...], ...]
96
+ A list of face index lists
97
+ points : np.array
98
+ A numpy array of uv points
99
+ samples : np.array
100
+ A numpy array of points to get the barycentric coords for
101
+ uvToFace : {int: [int, ...], ...}
102
+ A dictionary of UV indices to a list of Face Indices
103
+ tol : float
104
+ A small tolerance value, defaulting to the global EPS
105
+
106
+ Returns
107
+ -------
108
+ : {fc: (wh, barys)}
109
+ A dictionary of face counts to a tuple containing the indices of the face indices
110
+ checked, and the barycentric coords
111
+
112
+ """
113
+ uvIdxs, faceIdxs = sorted(zip(*list(uvToFace.items())))
114
+ uvIdxs = np.array(uvIdxs)
115
+ faces = [rawFaces[fi] for fi in faceIdxs]
116
+ faceLens = np.array([len(i) for i in faces])
117
+ fcs = np.unique(faceLens)
118
+
119
+ out = {}
120
+ for fc in fcs:
121
+ wh = np.where(faceLens == fc)[0]
122
+ cIdxs = np.array([faces[i] for i in wh])
123
+ barys = np.zeros(cIdxs.shape)
124
+ qIdxs = uvIdxs[wh]
125
+ out[fc] = (qIdxs, barys) # edit barys in-place
126
+
127
+ # cornerses is a [f, fc, 2] array
128
+ # where f is num of faces, fc is verts per face, and 2 because uv is 2d
129
+ # pts is [f, 2] array where f is num faces
130
+ cornerses = points[cIdxs]
131
+ pts = samples[qIdxs]
132
+
133
+ # Get the "spokes" from the query point to the face corners
134
+ # and get their squared lengths
135
+ spokes = cornerses - pts[:, None, :]
136
+ spokeLens2 = (spokes * spokes).sum(axis=-1)
137
+
138
+ # Handle any samples that are directly on top of a corner
139
+ # (where the spoke length is zero)
140
+ zeros = np.any(spokeLens2 < tol, axis=1)
141
+ onPoint = np.where(zeros)
142
+ offPoint = np.where(~zeros)
143
+ if onPoint[0].size:
144
+ pIdxs = spokeLens2[onPoint].argmin(axis=1)
145
+ barys[onPoint, pIdxs] = 1.0
146
+
147
+ if not offPoint[0].size:
148
+ continue
149
+
150
+ # Ignore those points that have already been computed
151
+ idxs = offPoint[0]
152
+ spokes = spokes[offPoint]
153
+ spokeLens2 = spokeLens2[offPoint]
154
+
155
+ # Get the signed area of each triangle created by the spokes
156
+ # and the dot product for the angle between each
157
+ rspokes = np.roll(spokes, -1, axis=1)
158
+ areas = np.cross(spokes, rspokes) * 0.5
159
+ dots = (spokes * rspokes).sum(axis=-1)
160
+
161
+ # Handle any samples that are directly on an edge between
162
+ # two corners. (Where the triangle area is 0, and the
163
+ # dot product is negative)
164
+ aareas = abs(areas)
165
+ zeros = aareas < tol
166
+ ndots = dots < 0.0
167
+ zn = zeros & ndots
168
+ toLerp = np.any(zn, axis=-1)
169
+ onEdge = np.where(toLerp)
170
+ offEdge = np.where(~toLerp)
171
+ if onEdge[0].size:
172
+ subIdx = idxs[onEdge]
173
+ pIdxs = zn[onEdge].argmax(axis=-1)
174
+ xIdxs = (pIdxs + 1) % fc
175
+
176
+ ppIdxs = cIdxs[subIdx, pIdxs]
177
+ xpIdxs = cIdxs[subIdx, xIdxs]
178
+
179
+ cp = pts[subIdx]
180
+ pp = points[ppIdxs]
181
+ xp = points[xpIdxs]
182
+
183
+ bases = pp - xp
184
+ diff = cp - xp
185
+ proj = (bases * diff).sum(axis=-1)
186
+ b = proj / (bases**2).sum(axis=1)
187
+ mb = 1.0 - b
188
+ barys[subIdx, pIdxs] = b
189
+ barys[subIdx, xIdxs] = mb
190
+
191
+ if not offEdge[0].size:
192
+ continue
193
+
194
+ idxs = idxs[offEdge]
195
+ dots = dots[offEdge]
196
+ areas = areas[offEdge]
197
+ spokeLens2 = spokeLens2[offEdge]
198
+ spokeLens = spokeLens2**0.5
199
+ rspokeLens = np.roll(spokeLens, -1, axis=1)
200
+
201
+ t = areas / (spokeLens * rspokeLens + dots)
202
+ rawWeights = (np.roll(t, -1, axis=1) + t) / spokeLens
203
+ b = rawWeights / rawWeights.sum(axis=1)[..., None]
204
+ barys[idxs] = b
205
+
206
+ ret = {}
207
+ for qIdxs, barys in out.values():
208
+ for qi, b in zip(qIdxs, barys):
209
+ ret[qi] = (uvToFace[qi], b)
210
+
211
+ return ret
212
+
213
+
214
+ ########################
215
+ # Sweep algorithm
216
+ ########################
217
+
218
+
219
+ def triArea(a, b, c):
220
+ """Use the cross-ish-product to find the area of the triangle
221
+ Depending on the winding, the area could be positive or negative
222
+
223
+ Parameters
224
+ ----------
225
+ a : [float, float, float]
226
+ The first point
227
+ b : [float, float, float]
228
+ The second point
229
+ c : [float, float, float]
230
+ The third point
231
+
232
+ Returns
233
+ -------
234
+ : float
235
+ The area of the triangle
236
+
237
+ """
238
+ return (a[0] * (c[1] - b[1]) + b[0] * (a[1] - c[1]) + c[0] * (b[1] - a[1])) / 2.0
239
+
240
+
241
+ def pointInTri(p, a, b, c, tol=EPS):
242
+ """Check that the point is inside the triangle
243
+
244
+ Parameters
245
+ ----------
246
+ p : [float, float, float]
247
+ The point to check is inside the triangle
248
+ a : [float, float, float]
249
+ The first point of the triangle
250
+ b : [float, float, float]
251
+ The second point of the triangle
252
+ c : [float, float, float]
253
+ The third point of the triangle
254
+ tol : float
255
+ A small tolerance value, defaulting to the global EPS
256
+
257
+ Returns
258
+ -------
259
+ : bool
260
+ Whether the point is inside the given triangle
261
+
262
+ """
263
+ area = abs(triArea(a, b, c))
264
+ chis = abs(triArea(p, b, c)) + abs(triArea(a, p, c)) + abs(triArea(a, b, p))
265
+ return abs(area - chis) < tol
266
+
267
+
268
+ def sweep(qPoints, uvs, tris, pBar=None):
269
+ """Get what triangle each query point is inside
270
+
271
+ Runs a sweep-line algorithm to check for points in triangles.
272
+ Imagine a uv layout, and a bunch of points on the layout.
273
+ Now imagine a vertical line sweeping across the uv plane from the left
274
+ to the right. The sorted u-values of certain properties then handled
275
+ one-by-one.
276
+
277
+ The algorithm keeps track of what triangles the vertical line is currently intersecting.
278
+
279
+ * This is done by storing the min and max u-values for each triangle.
280
+ * If the u-value encountered is the min for a tri, that tri is added to the list
281
+ * If the u-value encountered is the max for a tri, that tri is removed from the list
282
+
283
+ Then, each time a query point is encountered, it only has to check the intersection list
284
+
285
+ Parameters
286
+ ----------
287
+ qPoints : np.array
288
+ The points to get barycentric coordinates of
289
+ uvs : np.array
290
+ The UVs we're searching
291
+ tris : np.array
292
+ The Nx3 array of triangle indices
293
+ pBar : QProgressDialog, optional
294
+ An optional progress dialog
295
+
296
+ Returns
297
+ -------
298
+ : {int: int, ...}
299
+ A dictionary of out[pointIndex] = triIndex
300
+ : set()
301
+ A set containing the pointIndexes that weren't found in a triangle
302
+
303
+ """
304
+ tpts = uvs[tris] # [tIdx, abc, xy]
305
+
306
+ allmxs, allmns = tpts.max(axis=1), tpts.min(axis=1)
307
+ ymxs, ymns = allmxs[:, 1], allmns[:, 1]
308
+ mxs, mns = allmxs[:, 0], allmns[:, 0]
309
+ qpx = qPoints[:, 0]
310
+ qpSIdxs, mxSIdxs, mnSIdxs = np.argsort(qpx), np.argsort(mxs), np.argsort(mns)
311
+ qpSIdx, mxSIdx, mnSIdx = 0, 0, 0
312
+ qpIdx, mxIdx, mnIdx = qpSIdxs[qpSIdx], mxSIdxs[mxSIdx], mnSIdxs[mnSIdx]
313
+ qp, mx, mn = qpx[qpIdx], mxs[mxIdx], mns[mnIdx]
314
+
315
+ out = {}
316
+ missing = set()
317
+
318
+ if pBar is not None:
319
+ pBar.setValue(0)
320
+ allVals = len(qpSIdxs) + len(mxSIdxs) + len(mnSIdxs)
321
+ pBar.setRange(0, allVals)
322
+ pBar.setLabelText("Sweeping ...")
323
+ from Qt.QtWidgets import QApplication
324
+
325
+ QApplication.processEvents()
326
+
327
+ # skip any triangles to the left of the first query point
328
+ # The algorithm will stop once we hit the last query point
329
+ skip = [qp > m for m in mxs]
330
+ activeTris = [False for _ in mxs] # For fast membership testing
331
+ atSet = set() # For fast iteration
332
+
333
+ while True:
334
+ if pBar is not None:
335
+ cVal = qpSIdx + mnSIdx + mxSIdx
336
+ if cVal % 1283 == 0: # Just a random prime
337
+ pBar.setValue(cVal)
338
+ pBar.setLabelText("Sweeping ...\n{0}/{1}".format(cVal, allVals))
339
+ QApplication.processEvents()
340
+ if pBar.wasCanceled():
341
+ raise RuntimeError("Cancelled!")
342
+
343
+ if mn <= mx and mn <= qp:
344
+ # Always add triangles first if possible
345
+ aTriIdx = mnSIdxs[mnSIdx]
346
+ if not activeTris[aTriIdx] and not skip[aTriIdx]:
347
+ activeTris[aTriIdx] = True
348
+ atSet.add(aTriIdx)
349
+
350
+ mnSIdx += 1
351
+ if mnSIdx != len(mnSIdxs):
352
+ mnIdx = mnSIdxs[mnSIdx]
353
+ mn = mns[mnIdx]
354
+ else:
355
+ mn = mxs[mxSIdxs[-1]] + 1
356
+
357
+ elif qp <= mx:
358
+ # Check query points between adding and removing
359
+ qPoint = qPoints[qpIdx]
360
+ yv = qPoint[1]
361
+ # A linear search is faster than more complex collections here
362
+ for t in atSet:
363
+ if ymns[t] <= yv <= ymxs[t]:
364
+ a, b, c = uvs[tris[t]]
365
+ if pointInTri(qPoint, a, b, c):
366
+ out[qpIdx] = t
367
+ break
368
+ else:
369
+ missing.add(qpIdx)
370
+
371
+ qpSIdx += 1
372
+ if qpSIdx == len(qpSIdxs):
373
+ break
374
+ qpIdx = qpSIdxs[qpSIdx]
375
+ qp = qpx[qpIdx]
376
+
377
+ else:
378
+ # always remove triangles last
379
+ aTriIdx = mxSIdxs[mxSIdx]
380
+ if activeTris[aTriIdx] and not skip[aTriIdx]:
381
+ activeTris[aTriIdx] = False
382
+ atSet.remove(aTriIdx)
383
+
384
+ mxSIdx += 1
385
+ if mxSIdx != len(mxSIdxs):
386
+ mxIdx = mxSIdxs[mxSIdx]
387
+ mx = mxs[mxIdx]
388
+
389
+ return out, missing
390
+
391
+
392
+ ########################
393
+ # Triangulation
394
+ ########################
395
+
396
+
397
+ def inBox(point, mxs, mns):
398
+ """Check if a point is inside the bounding box
399
+
400
+ Parameters
401
+ ----------
402
+ point : np.array
403
+ A 3d point
404
+ mxs : np.array
405
+ The max values of all the coordinates per axis
406
+ mns : np.array
407
+ The min values of all the coordinates per axis
408
+
409
+ Returns
410
+ -------
411
+ : bool
412
+ Whether the point is in the given bounding box
413
+
414
+ """
415
+ return np.all(point <= mxs) and np.all(point >= mns)
416
+
417
+
418
+ def _isEar(a, b, c, polygon, tol=EPS):
419
+ """Check if the points a,b,c of the polygon could be their own triangle"""
420
+ signedArea = triArea(a, b, c)
421
+
422
+ # Check that the triange is wound the correct way.
423
+ if signedArea > 0:
424
+ return False
425
+
426
+ # Check that the triangle has non-zero area
427
+ # we already know the area is negative from above
428
+ if -signedArea < tol:
429
+ return False
430
+
431
+ # Check that none of the other points in the polygon are contained in triangle
432
+ for p in polygon:
433
+ if p not in (a, b, c):
434
+ if pointInTri(p, a, b, c, tol=tol):
435
+ return False
436
+ return True
437
+
438
+
439
+ def earclip(idxs, verts):
440
+ """Simple earclipping algorithm
441
+ For a polygon with n points it will return n-2 triangles.
442
+
443
+ Parameters
444
+ ----------
445
+ idxs : [int, ...]
446
+ The indices that make up a polygon
447
+ verts : np.array
448
+ All the UV positions
449
+
450
+ Returns
451
+ -------
452
+ : [[int, int, int], ...]
453
+ A list of triangle indices
454
+
455
+ """
456
+ earVerts = []
457
+ tris = []
458
+ idxs = list(idxs)
459
+ polygon = [tuple(verts[i]) for i in idxs]
460
+
461
+ numPts = len(polygon)
462
+ for i in range(numPts):
463
+ prev = polygon[i - 2]
464
+ cur = polygon[i - 1]
465
+ nxt = polygon[i]
466
+ if _isEar(prev, cur, nxt, polygon):
467
+ earVerts.append(cur)
468
+
469
+ while earVerts and numPts >= 3:
470
+ ear = earVerts.pop()
471
+ i = polygon.index(ear)
472
+ pi, ni = i - 1, (i + 1) % numPts
473
+
474
+ prevPt = polygon[pi]
475
+ nxtPt = polygon[ni]
476
+ tris.append((idxs[pi], idxs[i], idxs[ni]))
477
+
478
+ polygon.pop(i)
479
+ idxs.pop(i)
480
+ numPts -= 1
481
+ if numPts > 3:
482
+ prePrePt = polygon[i - 2]
483
+ nxtNxtPt = polygon[(i + 1) % numPts]
484
+
485
+ groups = [
486
+ (prePrePt, prevPt, nxtPt, polygon),
487
+ (prevPt, nxtPt, nxtNxtPt, polygon),
488
+ ]
489
+
490
+ for group in groups:
491
+ p = group[1]
492
+ if _isEar(*group):
493
+ if p not in earVerts:
494
+ earVerts.append(p)
495
+ elif p in earVerts:
496
+ earVerts.remove(p)
497
+ return tris
498
+
499
+
500
+ def triangulateUVs(faces, uvs):
501
+ """Take a set of uvFaces and uv points, and triangulate it
502
+
503
+ Parameters
504
+ ----------
505
+ faces : [[int, ...], ...]
506
+ A uv face structure
507
+ uvs : np.array
508
+ The uv positions
509
+
510
+ Returns
511
+ -------
512
+ : np.array
513
+ A Nx3 array of uv indexes making triangles
514
+ : [int, ...]
515
+ A list where the index is the triangle index, and the value is the face index
516
+ : {(int, int): int, ...}
517
+ A dictionary of border edge pairs to border faces
518
+
519
+ """
520
+ uvs = np.array(uvs)
521
+ triMap = []
522
+ tris = []
523
+ borderFaceMap = {}
524
+ # Build the naiive triangulation
525
+ # And get the borders while I'm looping
526
+ for f, face in enumerate(faces):
527
+ for i in range(2, len(face)):
528
+ triMap.append(f)
529
+ tris.append((face[0], face[i - 1], face[i]))
530
+
531
+ for i in range(len(face)):
532
+ ep = (face[i - 1], face[i])
533
+ if ep[0] > ep[1]:
534
+ ep = (ep[1], ep[0])
535
+ if ep in borderFaceMap:
536
+ borderFaceMap.pop(ep)
537
+ else:
538
+ borderFaceMap[ep] = f
539
+
540
+ tris = np.array(tris)
541
+ tuvs = uvs[tris]
542
+
543
+ # Get the area using a 2d-pseudo-cross-product
544
+ a = tuvs[:, 0] - tuvs[:, 1]
545
+ b = tuvs[:, 2] - tuvs[:, 1]
546
+ signedAreas = a[:, 0] * b[:, 1] - a[:, 1] * b[:, 0]
547
+
548
+ # Things with negative area are wound backwards in this case
549
+ negArea = np.where(signedAreas < 0)
550
+
551
+ # Do we need to retriangulate any of the polys
552
+ retri = sorted({triMap[i] for i in negArea[0]})
553
+ if retri:
554
+ tris = tris.tolist()
555
+ tmpFaceMap = {}
556
+ # tmpFaceMap is only good while we re-triangulate
557
+ # it has to be re-built after
558
+ for t, f in enumerate(triMap):
559
+ tmpFaceMap.setdefault(f, []).append(t)
560
+
561
+ for f in retri[::-1]:
562
+ good = earclip(faces[f], uvs)
563
+ tidxs = tmpFaceMap[f]
564
+ tris[tidxs[0] : tidxs[-1] + 1] = good
565
+ triMap[tidxs[0] : tidxs[-1] + 1] = [f] * len(good)
566
+ tris = np.array(tris)
567
+
568
+ return tris, triMap, borderFaceMap
569
+
570
+
571
+ ########################
572
+ # UV Transferring
573
+ ########################
574
+
575
+ MISSING = {}
576
+
577
+
578
+ def cooSparseMul(M, v):
579
+ """Multply the sparse matrix by the vector
580
+
581
+ Parameters
582
+ ----------
583
+ M : SparseMatrix
584
+ My own sparse matrix representation
585
+ v : np.array
586
+ A vector
587
+
588
+ Returns
589
+ -------
590
+ : np.array
591
+ The result of the multiplication
592
+ """
593
+ # Using scipy is at least 2x faster than the
594
+ # pure numpy implementation. But even that
595
+ # is about 5x faster than using a dense matrix
596
+ try:
597
+ from scipy import sparse
598
+ except ImportError:
599
+ # No scipy, use numpy
600
+ # The numpy universal function (ufunc) .add.at()
601
+ # makes this possible without any python looping
602
+ row, col, val, shape = M
603
+ v = v.swapaxes(0, -2)
604
+ vshape = val.shape + tuple([1] * (len(v) - 1))
605
+ val = val.reshape(vshape)
606
+ out = np.zeros(shape[:1] + v.shape[1:])
607
+ np.add.at(out, row, val * v[col])
608
+ out = out.swapaxes(0, -2)
609
+ else:
610
+ row, col, val, shape = M
611
+ spM = sparse.coo_matrix((val, (row, col)), shape=shape)
612
+ spM = sparse.csr_matrix(spM)
613
+ if len(v.shape) == 3:
614
+ out = np.array([spM.dot(frm) for frm in v])
615
+ else:
616
+ out = spM.dot(v)
617
+ return out
618
+
619
+
620
+ def getUvCorrelation(samples, points, faces, tol=0.0001, handleMissing=True, pBar=None):
621
+ """Get the per-face correlation of the sample points in uv space.
622
+
623
+ Parameters
624
+ ----------
625
+ samples : np.array
626
+ The sample points
627
+ points : np.array
628
+ The background points
629
+ faces : [[int, ...], ...]
630
+ The Face list
631
+ tol : float
632
+ A small tolerance value, defaulting to the global EPS
633
+ handleMissing :
634
+ (Default value = True)
635
+ pBar : QProgressDialog, optional
636
+ An optional progress dialog
637
+
638
+ Returns
639
+ -------
640
+ : {idx: (idx, [float, ...]), ...}
641
+ A dictionary from the sample index to a faceIdx/cornerWeights pair
642
+
643
+ """
644
+ tris, triMap, borderMap = triangulateUVs(faces, points)
645
+ swept, missing = sweep(samples, points, tris, pBar=pBar)
646
+ uvToFace = {uvI: triMap[tI] for uvI, tI in swept.items()}
647
+ # import __main__
648
+ # __main__.__dict__.update(locals())
649
+ # raise RuntimeError("STOPPIT")
650
+ if pBar is not None:
651
+ pBar.setValue(0)
652
+ pBar.setRange(0, len(uvToFace))
653
+ pBar.setLabelText("Calculate Mean Value Coords")
654
+ from Qt.QtWidgets import QApplication
655
+
656
+ QApplication.processEvents()
657
+
658
+ # mvcDict = {}
659
+ # for i, (uvIdx, faceIdx) in enumerate(uvToFace.iteritems()):
660
+ # if pBar is not None:
661
+ # pBar.setValue(i)
662
+ # pBar.setLabelText("Calculate Mean Value Coords\n{0}/{1}".format(i, len(uvToFace)))
663
+ # QApplication.processEvents()
664
+ # uv = samples[uvIdx]
665
+ # corners = points[faces[faceIdx]]
666
+ # bary = mvc(corners, uv)
667
+ # mvcDict[uvIdx] = (faceIdx, bary)
668
+
669
+ mvcDict = mmvc(faces, points, samples, uvToFace)
670
+
671
+ # find the closest border
672
+ # Just use a brute-force search
673
+ # ... for now
674
+
675
+ if missing and handleMissing:
676
+ if pBar is not None:
677
+ pBar.setValue(0)
678
+ pBar.setLabelText("Handle Missing")
679
+ QApplication.processEvents()
680
+ tol = tol**2
681
+ bk = list(borderMap.keys())
682
+ borders = np.array(bk)
683
+ bStarts = points[borders[:, 0]]
684
+ bEnds = points[borders[:, 1]]
685
+
686
+ bDiff = bEnds - bStarts
687
+ bLens2 = (bDiff * bDiff).sum(axis=1)
688
+ for mIdx in missing:
689
+ mp = samples[mIdx]
690
+ dSquared = _mpCheck(bStarts, bDiff, bLens2, mp)
691
+ minIdx = np.argmin(dSquared)
692
+ if dSquared[mIdx] < tol:
693
+ faceIdx = borderMap[bk[minIdx]]
694
+ corners = points[faces[faceIdx]]
695
+ bary = mvc(corners, mp)
696
+ mvcDict[mIdx] = (faceIdx, bary)
697
+
698
+ return mvcDict
699
+
700
+
701
+ def _mpCheck(a, d, dr2, pt):
702
+ """Point to Multi-segment squared distance. Uses pre-computed values"""
703
+ lerp = ((pt - a) * d).sum(axis=1) / dr2
704
+ lerp = np.clip(lerp, 0, 1)
705
+ xy = (lerp[:, None] * d) + a
706
+ _dxy = xy - pt
707
+ return (_dxy * _dxy).sum(axis=1)
708
+
709
+
710
+ def getVertCorrelation(
711
+ sUvFaces, sUvs, tVertFaces, tUvFaces, tUvs, tol=0.0001, pBar=None
712
+ ):
713
+ """Build the vertex position correlation between two meshes
714
+ by looking through UV-space. Handle combining multiple uvs
715
+ per vertex, and having samples that live outside the coverage
716
+
717
+ Parameters
718
+ ----------
719
+ sUvFaces : [[int, ...], ...]
720
+ The source UVFace list
721
+ sUvs : np.array
722
+ The source UV positions
723
+ tVertFaces : [[int, ...], ...]
724
+ The target vertex face list
725
+ tUvFaces : [[int, ...], ...]
726
+ The target UV face list
727
+ tUvs : np.array
728
+ The target UV positions
729
+ tol : float
730
+ A small tolerance value, defaulting to the global EPS
731
+ pBar : QProgressDialog, optional
732
+ An optional progress dialog
733
+
734
+ Returns
735
+ -------
736
+ : {idx: (idx, [float, ...]), ...}
737
+ A dictionary from the sample index to a faceIdx/cornerWeights pair
738
+ """
739
+ childUvToVert = {}
740
+ cNumVerts = -1
741
+ for vF, uvF in zip(tVertFaces, tUvFaces):
742
+ for vIdx, uvIdx in zip(vF, uvF):
743
+ cNumVerts = max(cNumVerts, vIdx)
744
+ childUvToVert[uvIdx] = vIdx
745
+
746
+ mvcUvDict = getUvCorrelation(tUvs, sUvs, sUvFaces, tol=tol, pBar=pBar)
747
+
748
+ mvcVertDict = {}
749
+ for uvIdx in range(len(tUvs)):
750
+ if uvIdx not in mvcUvDict:
751
+ continue
752
+ mvcVertDict.setdefault(childUvToVert[uvIdx], []).append(mvcUvDict[uvIdx])
753
+
754
+ missing = set(range(cNumVerts)) - mvcVertDict.keys()
755
+ if missing:
756
+ import time
757
+
758
+ v = time.time()
759
+ print(
760
+ "Missing correspondences found. Stored in uvTransfer.MISSING[{0}]".format(v)
761
+ )
762
+ MISSING[v] = missing
763
+
764
+ return mvcVertDict
765
+
766
+
767
+ def applyTransfer(parVerts, parFaces, correlation, outputSize):
768
+ """Given a vertex corelation, a driver, and driven points,
769
+ Apply the driver deformation to the driven. This could be
770
+ for one frame, or many frames
771
+
772
+ Parameters
773
+ ----------
774
+ parVerts : np.array
775
+ The "parent" vertex positions
776
+ parFaces : [[int, ...], ...]
777
+ The "parent" face list
778
+ correlation : {int: [int, ...], ...}
779
+ A dict correlatng the vertIdx to its possible correlations
780
+ outputSize : (int, ...)
781
+ A numpy output size tuple
782
+
783
+ Returns
784
+ -------
785
+ : np.array
786
+ The new vertex positions
787
+
788
+ """
789
+ if len(parVerts.shape) == 2:
790
+ parVerts = parVerts[None, ...]
791
+
792
+ rows, cols, vals = [], [], []
793
+ for cVertIdx, corrPoss in correlation.items():
794
+ if len(corrPoss) == 1:
795
+ pFaceIdx, bary = corrPoss[0]
796
+ else:
797
+ # pick the one with the highest sum-of-squares
798
+ x = [sum(bary * bary) for _, bary in corrPoss]
799
+ idx = x.index(max(x))
800
+ pFaceIdx, bary = corrPoss[idx]
801
+
802
+ rows.extend([cVertIdx] * len(bary))
803
+ vals.extend(bary)
804
+ cols.extend(parFaces[pFaceIdx])
805
+ M = np.array(rows), np.array(cols), np.array(vals), (outputSize, parVerts.shape[-2])
806
+ out = cooSparseMul(M, parVerts)
807
+ return out
808
+
809
+
810
+ def uvTransfer(
811
+ srcFaces,
812
+ srcUvFaces,
813
+ srcVerts,
814
+ srcUvs,
815
+ tarFaces,
816
+ tarUvFaces,
817
+ tarVerts,
818
+ tarUvs,
819
+ tol=0.0001,
820
+ pBar=None,
821
+ ):
822
+ """A helper function that transfers pre-loaded data.
823
+ The source data will be transferred onto the tar data
824
+
825
+ Parameters
826
+ ----------
827
+ srcFaces : [[int, ...], ...]
828
+ The source vertex face list
829
+ srcUvFaces : [[int, ...], ...]
830
+ The source uv face list
831
+ srcUvs : np.array
832
+ The source UV positions
833
+ tarFaces : [[int, ...], ...]
834
+ The target vertex face list
835
+ tarUvFaces : [[int, ...], ...]
836
+ The target uv face list
837
+ tarUvs : np.array
838
+ The Target UV Positions
839
+ srcVerts : np.array
840
+ The source Vertex positions
841
+ tarVerts : np.array
842
+ The target Vertex positions
843
+ tol : float
844
+ A small tolerance value, defaulting to the global EPS
845
+ pBar : QProgressDialog, optional
846
+ An optional progress dialog
847
+
848
+ Returns
849
+ -------
850
+ : np.array
851
+ The new target vert positions
852
+
853
+ """
854
+ corr = getVertCorrelation(
855
+ srcUvFaces, srcUvs, tarFaces, tarUvFaces, tarUvs, tol=tol, pBar=pBar
856
+ )
857
+ if pBar is not None:
858
+ pBar.setValue(0)
859
+ pBar.setLabelText("Apply Transfer")
860
+ from Qt.QtWidgets import QApplication
861
+
862
+ QApplication.processEvents()
863
+
864
+ return applyTransfer(srcVerts, srcFaces, corr, len(tarVerts))
865
+
866
+
867
+ def uvTransferLoad(
868
+ srcPath, tarPath, srcUvSet="default", tarUvSet="default", tol=0.0001, pBar=None
869
+ ):
870
+ """Transfer the shape from the source to the target through uv space
871
+ Return the data needed to write out the result
872
+
873
+ Parameters
874
+ ----------
875
+ srcPath : str
876
+ The source mesh path (obj, abc, or smpx)
877
+ tarPath : str
878
+ The target mesh path (obj, abc, or smpx)
879
+ srcUvSet : str
880
+ The name of the uv set to use on the source
881
+ tarUvSet : str
882
+ The name of the uv set to use on the target
883
+ tol : float
884
+ A small tolerance value, defaulting to the global EPS
885
+ pBar : QProgressDialog, optional
886
+ An optional progress dialog
887
+
888
+ Returns
889
+ -------
890
+ : np.array
891
+ The target vertex positions
892
+ : list
893
+ The target vertex faces
894
+ : np.array
895
+ The target uvs
896
+ : list
897
+ The target uv faces
898
+
899
+ """
900
+ from . import alembicCommon as abc
901
+ from .mesh import Mesh
902
+
903
+ if srcPath.endswith(".abc") or srcPath.endswith(".smpx"):
904
+ src = Mesh.loadAbc(srcPath, ensureWinding=False)
905
+ srcVerts = abc.getSampleArray(abc.getMesh(srcPath))
906
+ elif srcPath.endswith(".obj"):
907
+ src = Mesh.loadObj(srcPath, ensureWinding=False)
908
+ srcVerts = np.array(src.vertArray)
909
+
910
+ if tarPath.endswith(".abc"):
911
+ tar = Mesh.loadAbc(tarPath, ensureWinding=False)
912
+ elif tarPath.endswith(".obj"):
913
+ tar = Mesh.loadObj(tarPath, ensureWinding=False)
914
+
915
+ srcFaces = src.faceVertArray
916
+ srcUvFaces = src.uvFaceMap[srcUvSet]
917
+ srcUvs = np.array(src.uvMap[srcUvSet])
918
+
919
+ tarFaces = tar.faceVertArray
920
+ tarUvFaces = tar.uvFaceMap[tarUvSet]
921
+ tarUvs = np.array(tar.uvMap[tarUvSet])
922
+ oldTarVerts = np.array(tar.vertArray)
923
+ tarVerts = uvTransfer(
924
+ srcFaces,
925
+ srcUvFaces,
926
+ srcVerts,
927
+ srcUvs,
928
+ tarFaces,
929
+ tarUvFaces,
930
+ oldTarVerts,
931
+ tarUvs,
932
+ tol=tol,
933
+ pBar=pBar,
934
+ )
935
+
936
+ return tarVerts, tarFaces, tarUvs, tarUvFaces
937
+
938
+
939
+ def uvTransferFiles(
940
+ srcPath,
941
+ tarPath,
942
+ outAbcPath,
943
+ srcUvSet="default",
944
+ tarUvSet="default",
945
+ tol=0.0001,
946
+ pBar=None,
947
+ ):
948
+ """Transfer the shape from the source to the target through uv space
949
+ and write out the result
950
+
951
+ Parameters
952
+ ----------
953
+ srcPath : str
954
+ The source mesh path (obj, abc, or smpx)
955
+ tarPath : str
956
+ The target mesh path (obj, abc, or smpx)
957
+ outAbcPath : str
958
+ The path to the output .abc file
959
+ srcUvSet : str
960
+ The name of the uv set to use on the source
961
+ tarUvSet : str
962
+ The name of the uv set to use on the target
963
+ tol : float
964
+ A small tolerance value, defaulting to the global EPS
965
+ pBar : QProgressDialog, optional
966
+ An optional progress dialog
967
+
968
+ Returns
969
+ -------
970
+
971
+ """
972
+ from . import alembicCommon as abc
973
+
974
+ tarVerts, tarFaces, tarUvs, tarUvFaces = uvTransferLoad(
975
+ srcPath, tarPath, srcUvSet=srcUvSet, tarUvSet=tarUvSet, tol=tol, pBar=pBar
976
+ )
977
+ abc.buildAbc(outAbcPath, tarVerts, tarFaces, uvs=tarUvs, uvFaces=tarUvFaces)