-
Notifications
You must be signed in to change notification settings - Fork 42
/
ModelingCloth28.py
3235 lines (2497 loc) · 118 KB
/
ModelingCloth28.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# You are at the top. If you attempt to go any higher
# you will go beyond the known limits of the code
# universe where there are most certainly monsters
# to do:
# self colisions
# maybe do dynamic margins for when cloth is moving fast
# object collisions
# Other:
# option to cache animation?
# Custom Source shape option for animated shapes
# Sewing
# Could create super sewing that doesn't use edges but uses scalars along the edge to place virtual points
# sort of a barycentric virtual spring. Could even use it to sew to faces if I can think of a ui for where on the face.
# On an all triangle mesh, where sew edges come together there are long strait lines. This probably causes those edges to fold.
# in other words... creating diagonal springs between these edges will not solve the fold problem. Bend spring could do this.
# Bend springs:
# need to speed things up
# When faces have various sizes, the forces don't add up
# add curl by shortening bending springs on one axis or diagonal
# independantly scale bending springs and structural to create buckling
# specific to using as blender addon:
"""Bug list"""
# if a subsurf modifier is on the cloth, the grab tool freaks
# updates to addons
# https://www.youtube.com/watch?v=Mjy-zGG3Wk4
bl_info = {
"name": "Modeling Cloth",
"author": "Rich Colburn, email: [email protected]",
"version": (1, 0),
"blender": (2, 80, 0),
"location": "View3D > Extended Tools > Modeling Cloth",
"description": "Maintains the surface area of an object so it behaves like cloth",
"warning": "Your future self is planning to travel back in time to kill you.",
"wiki_url": "",
"category": '3D View'}
import bpy
import bmesh
import numpy as np
from numpy import newaxis as nax
from bpy_extras import view3d_utils
import time
import mathutils
#enable_numexpr = True
enable_numexpr = False
if enable_numexpr:
import numexpr as ne
you_have_a_sense_of_humor = False
#you_have_a_sense_of_humor = True
if you_have_a_sense_of_humor:
import antigravity
def get_co(ob, arr=None, key=None): # key
"""Returns vertex coords as N x 3"""
c = len(ob.data.vertices)
if arr is None:
arr = np.zeros(c * 3, dtype=np.float32)
if key is not None:
ob.data.shape_keys.key_blocks[key].data.foreach_get('co', arr.ravel())
arr.shape = (c, 3)
return arr
ob.data.vertices.foreach_get('co', arr.ravel())
arr.shape = (c, 3)
return arr
def get_proxy_co(ob, arr, me):
"""Returns vertex coords with modifier effects as N x 3"""
if arr is None:
arr = np.zeros(len(me.vertices) * 3, dtype=np.float32)
arr.shape = (arr.shape[0] //3, 3)
c = arr.shape[0]
me.vertices.foreach_get('co', arr.ravel())
arr.shape = (c, 3)
return arr
def triangulate(me, cloth=None):
"""Requires a mesh. Returns an index array for viewing co as triangles"""
obm = bmesh.new()
obm.from_mesh(me)
bmesh.ops.triangulate(obm, faces=obm.faces)
count = len(obm.faces)
tri_idx = np.array([[v.index for v in f.verts] for f in obm.faces])
# cloth can be the cloth object. Adds data to the class for the bend springs
# Identify bend spring groups. Each edge gets paired with two points on tips of tris around edge
# Restricted to edges with two linked faces on a triangulated version of the mesh
#"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
#cloth = None #!!!!!!!!!!!!!!!!!!!!!
#"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
#print("new=======================================")
if cloth is not None:
link_ed = [e for e in obm.edges if len(e.link_faces) == 2]
# exclude pinned: (pin bool is those verts that are not pinned)
# for each edge...
# if either of the link faces of that edge
# contain a vert that is not pinned
# we keep that edge.
# get the two verts from the link faces
fv = np.array([[[v.index for v in f.verts] for f in e.link_faces] for e in link_ed])
fv.shape = (fv.shape[0],6)
pindex = np.arange(cloth.pin_bool.shape[0])[cloth.pin_bool]
sub_bend = [np.any(np.in1d(fv[i], pindex)) for i in range(fv.shape[0])]
#print(sub_bend)
link_ed = np.array(link_ed)[sub_bend]
#print(sub_bend, "this is sub bend")
#print(cloth.pin_bool, "did this work???")
cloth.bend_eidx = np.array([[e.verts[0].index, e.verts[1].index] for e in link_ed])
fv = np.array([[[v.index for v in f.verts] for f in e.link_faces] for e in link_ed])
fv.shape = (fv.shape[0],6)
cloth.bend_tips = np.array([[idx for idx in fvidx if idx not in e] for e, fvidx in zip(cloth.bend_eidx, fv)])
obm.free()
return tri_idx
def tri_normals_in_place(object, tri_co, start=False):
"""Takes N x 3 x 3 set of 3d triangles and
generates unit normals and origins in the class"""
object.origins = tri_co[:,0]
object.cross_vecs = tri_co[:,1:] - object.origins[:, nax]
object.normals = np.cross(object.cross_vecs[:,0], object.cross_vecs[:,1])
object.nor_dots = np.einsum("ij, ij->i", object.normals, object.normals)
if start:
object.source_area = np.sqrt(object.nor_dots)
object.source_total_area = np.sum(np.sqrt(object.nor_dots))
object.normals /= np.sqrt(object.nor_dots)[:, nax]
def get_tri_normals(tr_co):
"""Takes N x 3 x 3 set of 3d triangles and
returns vectors around the triangle,
non-unit normals and origins"""
origins = tr_co[:,0]
cross_vecs = tr_co[:,1:] - origins[:, nax]
return cross_vecs, np.cross(cross_vecs[:,0], cross_vecs[:,1]), origins
def closest_points_edge(vec, origin, p):
"""Returns the location of the points on the edge,
p is an Nx3 vector array"""
vec2 = p - origin
d = (vec2 @ vec) / (vec @ vec)
cp = vec * d[:, nax]
return cp, d
def proxy_in_place(object, me):
"""Overwrite vert coords with modifiers in world space"""
me.vertices.foreach_get('co', object.co.ravel())
object.co = apply_transforms(object.ob, object.co)
def apply_rotation(object):
"""When applying vectors such as normals we only need
to rotate"""
m = np.array(object.ob.matrix_world)
mat = m[:3, :3].T
object.v_normals = object.v_normals @ mat
def proxy_v_normals_in_place(object, world=True, me=None):
"""Overwrite vert coords with modifiers in world space"""
me.vertices.foreach_get('normal', object.v_normals.ravel())
if world:
apply_rotation(object)
def proxy_v_normals(ob, me):
"""Overwrite vert coords with modifiers in world space"""
arr = np.zeros(len(me.vertices) * 3, dtype=np.float32)
me.vertices.foreach_get('normal', arr)
arr.shape = (arr.shape[0] //3, 3)
m = np.array(ob.matrix_world, dtype=np.float32)
mat = m[:3, :3].T # rotates backwards without T
return arr @ mat
def apply_transforms(ob, co):
"""Get vert coords in world space"""
m = np.array(ob.matrix_world, dtype=np.float32)
mat = m[:3, :3].T # rotates backwards without T
loc = m[:3, 3]
return co @ mat + loc
def apply_in_place(ob, arr, cloth):
"""Overwrite vert coords in world space"""
m = np.array(ob.matrix_world, dtype=np.float32)
mat = m[:3, :3].T # rotates backwards without T
loc = m[:3, 3]
arr[:] = arr @ mat + loc
def applied_key_co(ob, arr=None, key=None):
"""Get vert coords in world space"""
c = len(ob.data.vertices)
if arr is None:
arr = np.zeros(c * 3, dtype=np.float32)
ob.data.shape_keys.key_blocks[key].data.foreach_get('co', arr)
arr.shape = (c, 3)
m = np.array(ob.matrix_world)
mat = m[:3, :3].T # rotates backwards without T
loc = m[:3, 3]
return co @ mat + loc
def revert_transforms(ob, co):
"""Set world coords on object.
Run before setting coords to deal with object transforms
if using apply_transforms()"""
m = np.linalg.inv(ob.matrix_world)
mat = m[:3, :3].T # rotates backwards without T
loc = m[:3, 3]
return co @ mat + loc
def revert_in_place(ob, co):
"""Revert world coords to object coords in place."""
m = np.linalg.inv(ob.matrix_world)
mat = m[:3, :3].T # rotates backwards without T
loc = m[:3, 3]
co[:] = co @ mat + loc
def revert_rotation(ob, co):
"""When reverting vectors such as normals we only need
to rotate"""
m = np.array(ob.matrix_world)
mat = m[:3, :3] # rotates backwards without T
return co @ mat
def get_last_object():
"""Finds cloth objects for keeping settings active
while selecting other objects like pins"""
cloths = [i for i in bpy.data.objects if i.modeling_cloth] # so we can select an empty and keep the settings menu up
if "object" not in dir(bpy.context):
return
if bpy.context.object is None:
return
if bpy.context.active_object.modeling_cloth:
return cloths, bpy.context.active_object
if len(cloths) > 0:
ob = extra_data['last_object']
return cloths, ob
return None, None
def get_v_nor(ob, nor_arr):
ob.data.vertices.foreach_get('normal', nor_arr.ravel())
return nor_arr
def closest_point_edge(e1, e2, p):
'''Returns the location of the point on the edge'''
vec1 = e2 - e1
vec2 = p - e1
d = np.dot(vec2, vec1) / np.dot(vec1, vec1)
cp = e1 + vec1 * d
return cp
def get_weights(ob, name):
"""Returns a numpy array containing the weights of
the group as indicated by the string name. If there
is no such group returns weights of zero."""
v_count = len(ob.data.vertices)
arr = np.zeros(v_count, dtype=np.float32)
if name not in ob.vertex_groups:
return arr
ind = ob.vertex_groups[name].index
for i in range(v_count):
if len(ob.data.vertices[i].groups) > 0:
for j in ob.data.vertices[i].groups:
if j.group == ind:
arr[i] = j.weight
return arr
def get_bmesh(obj=None):
ob = get_last_object()[1]
if ob is None:
ob = obj
obm = bmesh.new()
if ob.mode == 'OBJECT':
obm.from_mesh(ob.data)
elif ob.mode == 'EDIT':
obm = bmesh.from_edit_mesh(ob.data)
return obm
def get_extend_springs(cloth, extend_springs=False):
ob = cloth.ob
obm = get_bmesh(ob)
obm.edges.ensure_lookup_table()
obm.verts.ensure_lookup_table()
obm.faces.ensure_lookup_table()
v_count = len(obm.verts)
sew = np.array([len(i.link_faces)==0 for i in obm.edges])
# get linear edges
e_count = len(obm.edges)
eidx = np.zeros(e_count * 2, dtype=np.int32)
ob.data.edges.foreach_get('vertices', eidx)
eidx.shape = (e_count, 2)
sew_eidx = eidx[sew]
pure = eidx[~sew]
# deal with sew verts connected to more than one edge
s_t_rav = sew_eidx.T.ravel()
s_uni, s_inv, s_counts = np.unique(s_t_rav, return_inverse=True, return_counts=True)
s_multi = s_counts > 1
multi_groups = None
if np.any(s_counts):
multi_groups = []
ls = sew_eidx[:,0]
rs = sew_eidx[:,1]
for i in s_uni[s_multi]:
gr = np.array([i])
gr = np.append(gr, ls[rs==i])
gr = np.append(gr, rs[ls==i])
multi_groups.append(gr)
uniidx = []
for i in obm.verts:
faces = i.link_faces
f_verts = [[v for v in f.verts if v != i] for f in faces]
if len(f_verts) > 0:
lv = np.hstack(f_verts)
for v in lv:
uniidx.append([i.index, v.index])
flip = np.sort(uniidx, axis=1)
uni = np.empty(shape=(0,2), dtype=np.int32)
for i in range(v_count):
this = flip[flip[:,0] == i]
if this.shape[0] > 0:
idx = this[np.unique(this[:,1], return_index=True)[1]]
uni = np.append(uni, idx, axis=0)
if extend_springs:
extend = []
pure = np.array(uniidx)
for i in range(pure.shape[0]):
this = pure[pure[:,0] == i]
if this.shape[0] > 0:
other = this[:,1]
for j in other:
faces = obm.verts[j].link_faces
f_verts = [[v for v in f.verts if (v.index != j) & (v.index !=i)] for f in faces]
lv = np.hstack(f_verts)
for v in lv:
extend.append([i, v.index])
extend = np.array(extend)
e_flip = np.sort(extend, axis=1)
e_uni = np.empty(shape=(0,2), dtype=np.int32)
for i in range(v_count):
this = e_flip[e_flip[:,0] == i]
if this.shape[0] > 0:
idx = this[np.unique(this[:,1], return_index=True)[1]]
e_uni = np.append(e_uni, idx, axis=0)
cloth.eidx = e_uni
return
cloth.eidx = uni
cloth.sew_edges = sew_eidx
cloth.multi_sew = multi_groups
cloth.pure_eidx = pure #for experimental edge self collisions
#return uni, e_uni, sew_eidx, multi_groups, pure
def get_unique_diagonal_edges(ob):
"""Creates a unique set of diagonal edges"""
diag_eidx = []
start = 0
stop = 0
step_size = [len(i.verts) for i in obm.faces]
p_v_count = np.sum(step_size)
p_verts = np.ones(p_v_count, dtype=np.int32)
ob.data.polygons.foreach_get('vertices', p_verts)
# can only be understood on a good day when the coffee flows (uses rolling and slicing)
# creates uniqe diagonal edge sets
for f in obm.faces:
fv_count = len(f.verts)
stop += fv_count
if fv_count > 3: # triangles are already connected by linear springs
skip = 2
f_verts = p_verts[start:stop]
for fv in range(len(f_verts)):
if fv > 1: # as we go around the loop of verts in face we start overlapping
skip = fv + 1 # this lets us skip the overlap so we don't have mirror duplicates
roller = np.roll(f_verts, fv)
for r in roller[skip:-1]:
diag_eidx.append([roller[0], r])
start += fv_count
return diag_eidx
def add_virtual_springs(remove=False):
lo = get_last_object()
if lo is None:
return
if lo[1] is None:
return
cloth = data[lo[1].name]
obm = get_bmesh()
obm.verts.ensure_lookup_table()
count = len(obm.verts)
idxer = np.arange(count, dtype=np.int32)
sel = np.array([v.select for v in obm.verts])
selected = idxer[sel]
if remove:
ls = cloth.virtual_springs[:, 0]
in_sel = np.in1d(ls, idxer[sel])
deleter = np.arange(ls.shape[0], dtype=np.int32)[in_sel]
reduce = np.delete(cloth.virtual_springs, deleter, axis=0)
cloth.virtual_springs = reduce
if cloth.virtual_springs.shape[0] == 0:
cloth.virtual_springs.shape = (0, 2)
return
existing = np.append(cloth.eidx, cloth.virtual_springs, axis=0)
flip = existing[:, ::-1]
existing = np.append(existing, flip, axis=0)
ls = existing[:,0]
springs = []
for i in idxer[sel]:
# to avoid duplicates:
# where this vert occurs on the left side of the existing spring list
v_in = existing[i == ls]
v_in_r = v_in[:,1]
not_in = selected[~np.in1d(selected, v_in_r)]
idx_set = not_in[not_in != i]
for sv in idx_set:
springs.append([i, sv])
virtual_springs = np.array(springs, dtype=np.int32)
if virtual_springs.shape[0] == 0:
virtual_springs.shape = (0, 2)
cloth.virtual_springs = np.append(cloth.virtual_springs, virtual_springs, axis=0)
# gets appended to eidx in the cloth_init function after calling get connected polys in case geometry changes
def generate_guide_mesh():
"""Makes the arrow that appears when creating pins"""
verts = [[0.0, 0.0, 0.0], [-0.01, -0.01, 0.1], [-0.01, 0.01, 0.1], [0.01, -0.01, 0.1], [0.01, 0.01, 0.1], [-0.03, -0.03, 0.1], [-0.03, 0.03, 0.1], [0.03, 0.03, 0.1], [0.03, -0.03, 0.1], [-0.01, -0.01, 0.2], [-0.01, 0.01, 0.2], [0.01, -0.01, 0.2], [0.01, 0.01, 0.2]]
edges = [[0, 5], [5, 6], [6, 7], [7, 8], [8, 5], [1, 2], [2, 4], [4, 3], [3, 1], [5, 1], [2, 6], [4, 7], [3, 8], [9, 10], [10, 12], [12, 11], [11, 9], [3, 11], [9, 1], [2, 10], [12, 4], [6, 0], [7, 0], [8, 0]]
faces = [[0, 5, 6], [0, 6, 7], [0, 7, 8], [0, 8, 5], [1, 3, 11, 9], [1, 2, 6, 5], [2, 4, 7, 6], [4, 3, 8, 7], [3, 1, 5, 8], [12, 10, 9, 11], [4, 2, 10, 12], [3, 4, 12, 11], [2, 1, 9, 10]]
name = 'ModelingClothPinGuide'
if 'ModelingClothPinGuide' in bpy.data.objects:
mesh_ob = bpy.data.objects['ModelingClothPinGuide']
else:
mesh = bpy.data.meshes.new('ModelingClothPinGuide')
mesh.from_pydata(verts, edges, faces)
mesh.update()
mesh_ob = bpy.data.objects.new(name, mesh)
bpy.context.collection.objects.link(mesh_ob)
#mesh_ob.show_x_ray = True
return mesh_ob
def create_giude():
"""Spawns the guide"""
if 'ModelingClothPinGuide' in bpy.data.objects:
mesh_ob = bpy.data.objects['ModelingClothPinGuide']
return mesh_ob
mesh_ob = generate_guide_mesh()
bpy.context.view_layer.objects.active = mesh_ob
bpy.ops.object.material_slot_add()
if 'ModelingClothPinGuide' in bpy.data.materials:
mat = bpy.data.materials['ModelingClothPinGuide']
else:
mat = bpy.data.materials.new(name='ModelingClothPinGuide')
#mat.use_transparency = True
#mat.alpha = 0.35
#mat.emit = 2
#mat.game_settings.alpha_blend = 'ALPHA_ANTIALIASING'
#mat.diffuse_color = (1, 1, 0)
#mesh_ob.material_slots[0].material = mat
return mesh_ob
def delete_giude():
"""Deletes the arrow"""
if 'ModelingClothPinGuide' in bpy.data.objects:
bpy.data.objects.remove(bpy.data.objects['ModelingClothPinGuide'])
if 'ModelingClothPinGuide' in bpy.data.meshes:
guide_mesh = bpy.data.meshes['ModelingClothPinGuide']
guide_mesh.user_clear()
bpy.data.meshes.remove(guide_mesh)
def update_source(cloth):
# measure bend source if using dynamic source:
cloth.source_angles = bend_springs(cloth, cloth.sco, None)
# linear spring measure
cloth.ob.data.shape_keys.key_blocks['modeling cloth source key'].data.foreach_get('co', cloth.sco.ravel())
svecs = cloth.sco[cloth.eidx[:, 1]] - cloth.sco[cloth.eidx[:, 0]]
cloth.sdots = np.einsum('ij,ij->i', svecs, svecs)
def scale_source(multiplier, cloth=None):
"""grow or shrink the source shape"""
ob = get_last_object()[1]
if ob is not None:
if ob.modeling_cloth:
count = len(ob.data.vertices)
co = np.zeros(count*3, dtype=np.float32)
ob.data.shape_keys.key_blocks['modeling cloth source key'].data.foreach_get('co', co)
co.shape = (count, 3)
mean = np.mean(co, axis=0)
co -= mean
co *= multiplier
co += mean
ob.data.shape_keys.key_blocks['modeling cloth source key'].data.foreach_set('co', co.ravel())
if hasattr(data[ob.name], 'cy_dists'):
data[ob.name].cy_dists *= multiplier
# recalculate in cloth: (so you don't have to have dynamic source on)
update_source(data[ob.name])
def reset_shapes(ob=None):
"""Sets the modeling cloth key to match the source key.
Will regenerate shape keys if they are missing"""
if ob is None:
if bpy.context.active_object.modeling_cloth:
ob = bpy.context.active_object
else:
ob = extra_data['last_object']
if ob.data.shape_keys == None:
ob.shape_key_add('Basis')
if 'modeling cloth source key' not in ob.data.shape_keys.key_blocks:
ob.shape_key_add('modeling cloth source key')
if 'modeling cloth key' not in ob.data.shape_keys.key_blocks:
ob.shape_key_add('modeling cloth key')
ob.data.shape_keys.key_blocks['modeling cloth key'].value=1
keys = ob.data.shape_keys.key_blocks
count = len(ob.data.vertices)
co = np.zeros(count * 3, dtype=np.float32)
keys['Basis'].data.foreach_get('co', co)
#co = applied_key_co(ob, None, 'modeling cloth source key')
#keys['modeling cloth source key'].data.foreach_set('co', co)
keys['modeling cloth key'].data.foreach_set('co', co)
# reset the data stored in the class
data[ob.name].vel[:] = 0
co.shape = (co.shape[0]//3, 3)
data[ob.name].co = co
data[ob.name].vel_start = np.copy(co)
keys['modeling cloth key'].mute = True
keys['modeling cloth key'].mute = False
def get_spring_mix(ob, eidx):
rs = []
ls = []
minrl = []
mixy = np.zeros(len(ob.data.vertices))
for i in range(len(ob.data.vertices)):
x = np.sum(eidx[:,0] == i)
y = np.sum(eidx[:,1] == i)
mixy[i] += x
mixy[i] += y
for i in eidx:
r = eidx[eidx == i[1]].shape[0]
l = eidx[eidx == i[0]].shape[0]
rs.append (min(r,l))
ls.append (min(r,l))
mix = 1 / np.array(rs + ls) ** 1.2
mix = np.array(rs + ls)
return mix, mixy[:, nax]
def update_pin_group():
"""Updates the cloth data after changing mesh or vertex weight pins"""
ob = get_last_object()[1]
if ob.name in data:
create_instance(new=False)
def collision_data_update(self, context):
if self.modeling_cloth_self_collision:
create_instance(new=False)
def refresh_noise(self, context):
if self.name in data:
zeros = np.zeros(data[self.name].count, dtype=np.float32)
random = np.random.random(data[self.name].count)
zeros[:] = random
data[self.name].noise = ((zeros + -0.5) * self.modeling_cloth_noise * 0.1)[:, nax]
def generate_wind(wind_vec, cloth):
"""Maintains a wind array and adds it to the cloth vel"""
tri_nor = cloth.normals #/ np.array(cloth.ob.scale) # non-unit calculated by tri_normals_in_place() per each triangle
w_vec = revert_rotation(cloth.ob, wind_vec) / np.array(cloth.ob.scale)
turb = cloth.ob.modeling_cloth_turbulence
if turb != 0:
w_vec += (np.random.random(3).astype(np.float32) - 0.5) * turb * np.mean(w_vec) * 4
# only blow on verts facing the wind
perp = np.abs(tri_nor @ (w_vec * np.array(cloth.ob.scale)))
cloth.wind += w_vec
cloth.wind *= perp[:, nax][:, nax]
# reshape for add.at
shape = cloth.wind.shape
cloth.wind.shape = (shape[0] * 3, 3)
cloth.wind *= cloth.tri_mix
np.add.at(cloth.vel, cloth.tridex.ravel(), cloth.wind)
cloth.wind.shape = shape
def generate_inflate(cloth):
"""Blow it up baby!"""
shape = cloth.inflate.shape
force = cloth.ob.modeling_cloth_inflate
norms = cloth.normals
#area = np.sqrt(cloth.nor_dots)
#area = ((cloth.source_area ** 2) + cloth.source_area) / 2
area = cloth.source_area# ** 2 #) + cloth.source_area) / 2
total_area = cloth.source_area
current_area = np.sum(area)
div = current_area / total_area
#return
#bippy = (norms * area[:, nax]) * force# * cloth.tri_mix) * force
bippy = (norms) * force# * cloth.tri_mix) * force
#print(bippy.shape)
#return
this = np.tile(bippy, 3)# * force * cloth.tri_mix #* div# * .02# * div
this.shape = (shape[0] * 3, 3)
this *= cloth.tri_mix
np.add.at(cloth.vel, cloth.tridex.ravel(), this)
return
if False:
tri_nor = cloth.normals #* cloth.ob.modeling_cloth_inflate # non-unit calculated by tri_normals_in_place() per each triangle
#tri_nor /= np.einsum("ij, ij->i", tri_nor, tri_nor)[:, nax]
# reshape for add.at
shape = cloth.inflate.shape
cloth.inflate += tri_nor[:, nax] * cloth.ob.modeling_cloth_inflate# * cloth.nor_dots[:,nax]
cloth.inflate.shape = (shape[0] * 3, 3)
cloth.inflate *= (cloth.tri_mix)# * cloth.nor_dots)
root = np.sqrt(cloth.nor_dots)
sum = np.sum(root)
div = cloth.source_area / sum
cloth.inflate *= np.repeat((cloth.nor_dots), 3)[:,nax] #* div
this = np.tile(cloth.normals * cloth.source_area, 3) * div
this.shape = (shape[0] * 3, 3)
#print(cloth.tri_mix.shape)
np.add.at(cloth.vel, cloth.tridex.ravel(), this)
cloth.inflate.shape = shape
#cloth.inflate *= 0
def get_quat(rad, axis):
theta = (rad * 0.5)
w = np.cos(theta)
q_axis = axis * np.sin(theta)[:, nax]
return w, q_axis
def q_rotate(co, w, axis):
"""Takes an N x 3 numpy array and returns that array rotated around
the axis by the angle in radians w. (standard quaternion)"""
move1 = np.cross(axis, co)
move2 = np.cross(axis, move1)
move1 *= w[:, nax]
return co + (move1 + move2) * 2
def bend_springs(cloth, co, measure=None):
bend_eidx, tips = cloth.bend_eidx, cloth.bend_tips
# if we have no springs...
if tips.shape[0] < 1:
return
tips_co = co[tips]
bls, brs = bend_eidx[:,0], bend_eidx[:, 1]
b_oris = co[bls]
be_vecs = co[brs] - b_oris
te_vecs = tips_co - b_oris[:, nax]
bcp_dots = np.einsum('ij,ikj->ik', be_vecs, te_vecs)
be_dots = np.einsum('ij,ij->i', be_vecs, be_vecs)
b_div = np.nan_to_num(bcp_dots / be_dots[:, nax])
tcp = be_vecs[:, nax] * b_div[:, :, nax]
# tip vecs from cp
tcp_vecs = te_vecs - tcp
tcp_dots = np.einsum('ijk,ijk->ij',tcp_vecs, tcp_vecs)
u_tcp_vecs = tcp_vecs / np.sqrt(tcp_dots)[:, :, nax]
u_tcp_ls = u_tcp_vecs[:, 0]
u_tcp_rs = u_tcp_vecs[:, 1]
# dot of unit tri tips around axis
angle_dot = np.einsum('ij,ij->i', u_tcp_ls, u_tcp_rs)
#paralell = angle_dot < -.9999999
angle = np.arccos(np.clip(angle_dot, -1, 1)) # values outside and arccos gives nan
#angle = np.arccos(angle_dot) # values outside and arccos gives nan
# get the angle sign
tcp_cross = np.cross(u_tcp_vecs[:, 0], u_tcp_vecs[:, 1])
sign = np.sign(np.einsum('ij,ij->i', be_vecs, tcp_cross))
if measure is None:
s = np.arccos(angle_dot)
s *= sign
s[angle_dot < -.9999999] = np.pi
return s
angle *= sign
# rotate edges with quaternypoos
u_be_vecs = be_vecs / np.sqrt(be_dots)[:, nax]
b_dif = angle - measure
l_ws, l_axes = get_quat(b_dif, u_be_vecs)
r_ws, r_axes = l_ws, -l_axes
# move tcp vecs so their origin is in the middle:
#u_tcp_vecs *= 0.5
# should I rotate the unit vecs or the source?
# rotating the unit vecs here.
stiff = cloth.ob.modeling_cloth_bend_stiff * 0.0057
rot_ls = q_rotate(u_tcp_ls, l_ws, l_axes)
l_force = (rot_ls - u_tcp_ls) * stiff
rot_rs = q_rotate(u_tcp_rs, r_ws, r_axes)
r_force = (rot_rs - u_tcp_rs) * stiff
np.add.at(cloth.co, tips[:, 0], l_force)
np.add.at(cloth.co, tips[:, 1], r_force)
np.subtract.at(cloth.co, bend_eidx.ravel(), np.tile(r_force * .5, 2).reshape(r_force.shape[0] * 2, 3))
np.subtract.at(cloth.co, bend_eidx.ravel(), np.tile(l_force * .5, 2).reshape(l_force.shape[0] * 2, 3))
# sewing functions ---------------->>>
def create_sew_edges():
bpy.ops.mesh.bridge_edge_loops()
bpy.ops.mesh.delete(type='ONLY_FACE')
return
# To do:
#highlight a sew edge
#compare vertex counts
#subdivide to match counts
#distribute and smooth back into mesh
#create sew lines
# sewing functions ---------------->>>
class Cloth(object):
pass
def create_instance(new=True):
"""Creates instance of cloth object with attributes needed for engine"""
for i in bpy.data.meshes:
if i.users == 0:
bpy.data.meshes.remove(i)
if new:
cloth = Cloth()
cloth.ob = bpy.context.active_object # based on what the user has as the active object
cloth.pin_list = [] # these will not be moved by the engine
cloth.hook_list = [] # these will be moved by hooks and updated to the engine
cloth.virtual_springs = np.empty((0,2), dtype=np.int32) # so we can attach points to each other without regard to topology
cloth.sew_springs = [] # edges with no faces attached can be set to shrink
else: # if we set a modeling cloth object and have something else selected, the most recent object will still have it's settings exposed in the ui
ob = get_last_object()[1]
cloth = data[ob.name]
cloth.ob = ob
bpy.context.view_layer.objects.active = cloth.ob
cloth.idxer = np.arange(len(cloth.ob.data.vertices), dtype=np.int32)
# data only accesible through object mode
mode = cloth.ob.mode
if mode == 'EDIT':
bpy.ops.object.mode_set(mode='OBJECT')
# data is read from a source shape and written to the display shape so we can change the target springs by changing the source shape
cloth.name = cloth.ob.name
if cloth.ob.data.shape_keys == None:
cloth.ob.shape_key_add(name='Basis')
if 'modeling cloth source key' not in cloth.ob.data.shape_keys.key_blocks:
cloth.ob.shape_key_add(name='modeling cloth source key')
if 'modeling cloth key' not in cloth.ob.data.shape_keys.key_blocks:
cloth.ob.shape_key_add(name='modeling cloth key')
cloth.ob.data.shape_keys.key_blocks['modeling cloth key'].value=1
cloth.count = len(cloth.ob.data.vertices)
# we can set a large group's pin state using the vertex group. No hooks are used here
if 'modeling_cloth_pin' not in cloth.ob.vertex_groups:
cloth.ob.vertex_groups.new(name='modeling_cloth_pin')
cloth.pin_weights = get_weights(cloth.ob, 'modeling_cloth_pin')
# pin bool sets all weights more than zero as pinned
on_off = False
if on_off:
cloth.pin_bool = ~cloth.pin_weights.astype(np.bool)
# for use with weights with different values
w_bool = cloth.pin_weights == 1
cloth.pin_bool = ~(w_bool)
# Spring Relationships
# Extend Springs
get_extend_springs(cloth) # uni, e_uni, sew_eidx, multi_groups, pure
if cloth.ob.modeling_cloth_extend_springs:
get_extend_springs(cloth, extend_springs=True)
# Virtual Springs
if cloth.virtual_springs.shape[0] > 0:
cloth.eidx = np.append(cloth.eidx, cloth.virtual_springs, axis=0)
cloth.eidx_tiler = cloth.eidx.T.ravel()
#mixology, cloth.spring_counts = get_spring_mix(cloth.ob, cloth.eidx)
#cloth.spring_counts = get_spring_mix(cloth.ob, cloth.eidx)
pindexer = np.arange(cloth.count, dtype=np.int32)[cloth.pin_bool]
unpinned = np.in1d(cloth.eidx_tiler, pindexer)
#cloth.eidx_tiler = cloth.eidx_tiler[unpinned]
cloth.unpinned = unpinned
# unique edges------------>>>
cloth.pcount = pindexer.shape[0]
cloth.pindexer = pindexer
cloth.sco = np.zeros(cloth.count * 3, dtype=np.float32)
cloth.ob.data.shape_keys.key_blocks['modeling cloth source key'].data.foreach_get('co', cloth.sco)
cloth.sco.shape = (cloth.count, 3)
cloth.co = np.zeros(cloth.count * 3, dtype=np.float32)
cloth.ob.data.shape_keys.key_blocks['modeling cloth key'].data.foreach_get('co', cloth.co)
cloth.co.shape = (cloth.count, 3)
co = cloth.co
cloth.vel = np.zeros(cloth.count * 3, dtype=np.float32)
cloth.vel_start = np.zeros(cloth.count * 3, dtype=np.float32)
cloth.vel_start.shape = (cloth.count, 3)
cloth.vel.shape = (cloth.count, 3)
cloth.self_col_vel = np.copy(co)
cloth.weighted_average = np.copy(co)
cloth.weighted_average[:] = 0
cloth.weight_sum = np.zeros(co.shape[0], dtype=np.float32)
cloth.v_normals = np.zeros(co.shape, dtype=np.float32)
# blended pinning:
cloth.weighted = (cloth.pin_weights < 1) & (cloth.pin_weights > 0)
cloth.blended_co = cloth.co[cloth.weighted]
cloth.blend_weights = cloth.pin_weights[cloth.weighted][:,nax]
#noise---
noise_zeros = np.zeros(cloth.count, dtype=np.float32)
random = np.random.random(cloth.count).astype(np.float32)
noise_zeros[:] = random
cloth.noise = ((noise_zeros + -0.5) * cloth.ob.modeling_cloth_noise * 0.1)[:, nax]
cloth.waiting = False
cloth.clicked = False # for the grab tool
# this helps with extra springs behaving as if they had more mass---->>>
#cloth.mix = mixology[unpinned][:, nax]
# -------------->>>
# new self collisions:
cloth.tridex = triangulate(cloth.ob.data, cloth)
cloth.eidxer = np.arange(cloth.pure_eidx.shape[0])
cloth.tridexer = np.arange(cloth.tridex.shape[0], dtype=np.int32)
cloth.tri_co = cloth.co[cloth.tridex]
tri_normals_in_place(cloth, cloth.tri_co, start=True) # non-unit normals
# -------------->>>
tri_uni, tri_inv, tri_counts = np.unique(cloth.tridex, return_inverse=True, return_counts=True)
cloth.tri_mix = (1 / tri_counts[tri_inv])[:, nax]
cloth.wind = np.zeros(cloth.tri_co.shape, dtype=np.float32)
cloth.inflate = np.zeros(cloth.tri_co.shape, dtype=np.float32)
bpy.ops.object.mode_set(mode=mode)
# for use with a static source shape:
cloth.source_angles = bend_springs(cloth, cloth.sco, None)
svecs = cloth.sco[cloth.eidx[:, 1]] - cloth.sco[cloth.eidx[:, 0]]
cloth.sdots = np.einsum('ij,ij->i', svecs, svecs)
# softbody via mean
cloth.soft_list = [i for i in bpy.data.objects if i.modeling_cloth_softbody_goal]
cloth.soft_data = {}
if cloth.soft_list:
cloth.soft_move = np.zeros(cloth.co.shape[0] * 3, dtype=np.float32)
cloth.soft_move.shape = (cloth.co.shape[0], 3)
for i in cloth.soft_list:
soft_target = revert_transforms(cloth.ob, np.array(i.location))
#cloth.soft_target = soft_target
target_vecs = soft_target - co
soft_dots = np.einsum('ij,ij->i', target_vecs, target_vecs)
cloth.soft_data[i.name + 'soft_dots'] = soft_dots