forked from coreynguyen/rumblerosesxx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bpy_rumblerosesxx.py
2782 lines (2303 loc) · 102 KB
/
bpy_rumblerosesxx.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
""" ======================================================================
Python Code: [X360] Rumble Roses XX (for Blender 3.0.1)
Author: mariokart64n
Date: February 19, 2022
Version: 0.1
======================================================================
ChangeLog:
2022-02-19
Script Written
====================================================================== """
import bpy # Needed to interface with blender
from bpy_extras.io_utils import ImportHelper # needed for OT_TestOpenFilebrowser
import struct # Needed for Binary Reader
import random
import math
from pathlib import Path # Needed for os stuff
useOpenDialog = True
# ====================================================================================
# MAXCSRIPT FUNCTIONS
# ====================================================================================
# These function are written to mimic native functions in
# maxscript. This is to make porting my old maxscripts
# easier, so alot of these functions may be redundant..
# ====================================================================================
#
signed, unsigned = 0, 1 # Enums for read function
seek_set, seek_cur, seek_end = 0, 1, 2 # Enums for seek function
SEEK_ABS, SEEK_REL, SEEK_END = 0, 1, 2 # Enums for seek function
def deleteScene(include=[]):
if len(include) > 0:
# Exit and Interactions
if bpy.context.view_layer.objects.active != None:
bpy.ops.object.mode_set(mode='OBJECT')
# Select All
bpy.ops.object.select_all(action='SELECT')
# Loop Through Each Selection
for o in bpy.context.view_layer.objects.selected:
for t in include:
if o.type == t:
bpy.data.objects.remove(o, do_unlink=True)
break
# De-Select All
bpy.ops.object.select_all(action='DESELECT')
return None
def rancol4():
return (random.uniform(0.0, 1.0), random.uniform(0.0, 1.0), random.uniform(0.0, 1.0), 1.0)
def rancol3():
return (random.uniform(0.0, 1.0), random.uniform(0.0, 1.0), random.uniform(0.0, 1.0))
def ceil (num):
n = float(int(num))
if num > n: n += 1.0
return n
def cross(vec1=(0.0, 0.0, 0.0), vec2=(0.0, 0.0, 0.0)):
return (
vec2[1] * vec1[2] - vec2[2] * vec1[1],
vec2[2] * vec1[0] - vec2[0] * vec1[2],
vec2[0] * vec1[1] - vec2[1] * vec1[0]
)
def dot(a=(0.0, 0.0, 0.0), b=(0.0, 0.0, 0.0)):
return sum(map(lambda pair: pair[0] * pair[1], zip(a, b)))
#def abs(val=0.0):
# return (-val if val < 0 else val)
def sqrt(n=0.0, l=0.001):
# x = n
# root = 0.0
# count = 0
# while True:
# count += 1
# if x == 0: break
# root = 0.5 * (x + (n / x))
# if abs(root - x) < l: break
# x = root
# return root
return math.sqrt(n)
def normalize(vec=(0.0, 0.0, 0.0)):
div = sqrt((vec[0] * vec[0]) + (vec[1] * vec[1]) + (vec[2] * vec[2]))
return (
(vec[0] / div) if vec[0] != 0 else 0.0,
(vec[1] / div) if vec[1] != 0 else 0.0,
(vec[2] / div) if vec[2] != 0 else 0.0
)
def max(val1 = 0.0, val2 = 0.0):
return val1 if val1 > val2 else val2
def distance(vec1=(0.0, 0.0, 0.0), vec2=(0.0, 0.0, 0.0)):
return (sqrt((pow(vec2[0] - vec1[0], 2)) + (pow(vec2[1] - vec1[1], 2)) + (pow(vec2[2] - vec1[2], 2))))
def radToDeg(radian):
# return (radian * 57.295779513082320876798154814105170332405472466564)
return math.degrees(radian)
def degToRad(degree):
# return (degree * 0.017453292519943295769236907684886127134428718885417)
return math.radians(degree)
def bit():
def And(integer1, integer2): return (integer1 & integer2)
def Or(integer1, integer2): return (integer1 | integer2)
def Xor(integer1, integer2): return (integer1 ^ integer2)
def Not(integer1): return (~integer1)
def Get(integer1, integer2): return ((integer1 & (1 << integer2)) >> integer2)
def Set(integer1, integer2, boolean): return (integer1 ^ ((integer1 * 0 - (int(boolean))) ^ integer1) & ((integer1 * 0 + 1) << integer2))
def Shift(integer1, integer2): return ((integer1 >> -integer2) if integer2 < 0 else (integer1 << integer2))
def CharAsInt(string): return ord(int(string))
def IntAsChar(integer): return chr(int(integer))
def IntAsHex(integer): return format(integer, 'X')
def IntAsFloat(integer): return struct.unpack('f', integer.to_bytes(4, byteorder='little'))
def delete(objName):
select(objName)
bpy.ops.object.delete(use_global=False)
def delete_all():
if( len(bpy.data.objects) != 0 ):
bpy.ops.object.select_all(action = 'SELECT')
bpy.ops.object.delete(use_global=False)
class dummy:
object = None
def __init__(self, position = (0.0, 0.0, 0.0)):
self.object = bpy.data.objects.new("Empty", None )
bpy.context.scene.collection.objects.link(self.object)
self.object.empty_display_size = 1
self.object.empty_display_type = 'CUBE'
self.object.location = position
def position(self, pos=(0.0, 0.0, 0.0)):
if self.object != None: self.object.location = pos
def name(self, name=""):
if self.object != None and name != "": self.object.name = name
def showLinks(self, enable=False):
return enable
def showLinksOnly(self, enable=False):
return enable
class matrix3:
row1 = [1.0, 0.0, 0.0]
row2 = [0.0, 1.0, 0.0]
row3 = [0.0, 0.0, 1.0]
row4 = [0.0, 0.0, 0.0]
def __init__(self, rowA=[1.0, 0.0, 0.0], rowB=[0.0, 1.0, 0.0], rowC=[0.0, 0.0, 1.0], rowD=[0.0, 0.0, 0.0]):
if rowA == 0:
self.row1 = [0.0, 0.0, 0.0]
self.row2 = [0.0, 0.0, 0.0]
self.row3 = [0.0, 0.0, 0.0]
self.row4 = [0.0, 0.0, 0.0]
elif rowA == 1:
self.row1 = [1.0, 0.0, 0.0]
self.row2 = [0.0, 1.0, 0.0]
self.row3 = [0.0, 0.0, 1.0]
self.row4 = [0.0, 0.0, 0.0]
else:
self.row1 = rowA
self.row2 = rowB
self.row3 = rowC
self.row4 = rowD
def __repr__(self):
return (
"matrix3([" + str(self.row1[0]) +
", " + str(self.row1[1]) +
", " + str(self.row1[2]) +
"], [" + str(self.row2[0]) +
", " + str(self.row2[1]) +
", " + str(self.row2[2]) +
"], [" + str(self.row3[0]) +
", " + str(self.row3[1]) +
", " + str(self.row3[2]) +
"], [" + str(self.row4[0]) +
", " + str(self.row4[1]) +
", " + str(self.row4[2]) + "])"
)
def asMat3(self):
return (
(self.row1[0], self.row1[1], self.row1[2]),
(self.row2[0], self.row2[1], self.row2[2]),
(self.row3[0], self.row3[1], self.row3[2]),
(self.row4[0], self.row4[1], self.row4[2])
)
def asMat4(self):
return (
(self.row1[0], self.row1[1], self.row1[2], 0.0),
(self.row2[0], self.row2[1], self.row2[2], 0.0),
(self.row3[0], self.row3[1], self.row3[2], 0.0),
(self.row4[0], self.row4[1], self.row4[2], 1.0)
)
def inverse(self):
row1_3 = 0.0
row2_3 = 0.0
row3_3 = 0.0
row4_3 = 1.0
inv = [float] * 16
inv[0] = (self.row2[1] * self.row3[2] * row4_3 -
self.row2[1] * row3_3 * self.row4[2] -
self.row3[1] * self.row2[2] * row4_3 +
self.row3[1] * row2_3 * self.row4[2] +
self.row4[1] * self.row2[2] * row3_3 -
self.row4[1] * row2_3 * self.row3[2])
inv[4] = (-self.row2[0] * self.row3[2] * row4_3 +
self.row2[0] * row3_3 * self.row4[2] +
self.row3[0] * self.row2[2] * row4_3 -
self.row3[0] * row2_3 * self.row4[2] -
self.row4[0] * self.row2[2] * row3_3 +
self.row4[0] * row2_3 * self.row3[2])
inv[8] = (self.row2[0] * self.row3[1] * row4_3 -
self.row2[0] * row3_3 * self.row4[1] -
self.row3[0] * self.row2[1] * row4_3 +
self.row3[0] * row2_3 * self.row4[1] +
self.row4[0] * self.row2[1] * row3_3 -
self.row4[0] * row2_3 * self.row3[1])
inv[12] = (-self.row2[0] * self.row3[1] * self.row4[2] +
self.row2[0] * self.row3[2] * self.row4[1] +
self.row3[0] * self.row2[1] * self.row4[2] -
self.row3[0] * self.row2[2] * self.row4[1] -
self.row4[0] * self.row2[1] * self.row3[2] +
self.row4[0] * self.row2[2] * self.row3[1])
inv[1] = (-self.row1[1] * self.row3[2] * row4_3 +
self.row1[1] * row3_3 * self.row4[2] +
self.row3[1] * self.row1[2] * row4_3 -
self.row3[1] * row1_3 * self.row4[2] -
self.row4[1] * self.row1[2] * row3_3 +
self.row4[1] * row1_3 * self.row3[2])
inv[5] = (self.row1[0] * self.row3[2] * row4_3 -
self.row1[0] * row3_3 * self.row4[2] -
self.row3[0] * self.row1[2] * row4_3 +
self.row3[0] * row1_3 * self.row4[2] +
self.row4[0] * self.row1[2] * row3_3 -
self.row4[0] * row1_3 * self.row3[2])
inv[9] = (-self.row1[0] * self.row3[1] * row4_3 +
self.row1[0] * row3_3 * self.row4[1] +
self.row3[0] * self.row1[1] * row4_3 -
self.row3[0] * row1_3 * self.row4[1] -
self.row4[0] * self.row1[1] * row3_3 +
self.row4[0] * row1_3 * self.row3[1])
inv[13] = (self.row1[0] * self.row3[1] * self.row4[2] -
self.row1[0] * self.row3[2] * self.row4[1] -
self.row3[0] * self.row1[1] * self.row4[2] +
self.row3[0] * self.row1[2] * self.row4[1] +
self.row4[0] * self.row1[1] * self.row3[2] -
self.row4[0] * self.row1[2] * self.row3[1])
inv[2] = (self.row1[1] * self.row2[2] * row4_3 -
self.row1[1] * row2_3 * self.row4[2] -
self.row2[1] * self.row1[2] * row4_3 +
self.row2[1] * row1_3 * self.row4[2] +
self.row4[1] * self.row1[2] * row2_3 -
self.row4[1] * row1_3 * self.row2[2])
inv[6] = (-self.row1[0] * self.row2[2] * row4_3 +
self.row1[0] * row2_3 * self.row4[2] +
self.row2[0] * self.row1[2] * row4_3 -
self.row2[0] * row1_3 * self.row4[2] -
self.row4[0] * self.row1[2] * row2_3 +
self.row4[0] * row1_3 * self.row2[2])
inv[10] = (self.row1[0] * self.row2[1] * row4_3 -
self.row1[0] * row2_3 * self.row4[1] -
self.row2[0] * self.row1[1] * row4_3 +
self.row2[0] * row1_3 * self.row4[1] +
self.row4[0] * self.row1[1] * row2_3 -
self.row4[0] * row1_3 * self.row2[1])
inv[14] = (-self.row1[0] * self.row2[1] * self.row4[2] +
self.row1[0] * self.row2[2] * self.row4[1] +
self.row2[0] * self.row1[1] * self.row4[2] -
self.row2[0] * self.row1[2] * self.row4[1] -
self.row4[0] * self.row1[1] * self.row2[2] +
self.row4[0] * self.row1[2] * self.row2[1])
inv[3] = (-self.row1[1] * self.row2[2] * row3_3 +
self.row1[1] * row2_3 * self.row3[2] +
self.row2[1] * self.row1[2] * row3_3 -
self.row2[1] * row1_3 * self.row3[2] -
self.row3[1] * self.row1[2] * row2_3 +
self.row3[1] * row1_3 * self.row2[2])
inv[7] = (self.row1[0] * self.row2[2] * row3_3 -
self.row1[0] * row2_3 * self.row3[2] -
self.row2[0] * self.row1[2] * row3_3 +
self.row2[0] * row1_3 * self.row3[2] +
self.row3[0] * self.row1[2] * row2_3 -
(self.row3[0] * row1_3 * self.row2[2]))
inv[11] = (-self.row1[0] * self.row2[1] * row3_3 +
self.row1[0] * row2_3 * self.row3[1] +
self.row2[0] * self.row1[1] * row3_3 -
self.row2[0] * row1_3 * self.row3[1] -
self.row3[0] * self.row1[1] * row2_3 +
self.row3[0] * row1_3 * self.row2[1])
inv[15] = (self.row1[0] * self.row2[1] * self.row3[2] -
self.row1[0] * self.row2[2] * self.row3[1] -
self.row2[0] * self.row1[1] * self.row3[2] +
self.row2[0] * self.row1[2] * self.row3[1] +
self.row3[0] * self.row1[1] * self.row2[2] -
self.row3[0] * self.row1[2] * self.row2[1])
det = self.row1[0] * inv[0] + self.row1[1] * inv[4] + self.row1[2] * inv[8] + row1_3 * inv[12]
if det != 0:
det = 1.0 / det
return (matrix3(
[inv[0] * det, inv[1] * det, inv[2] * det],
[inv[4] * det, inv[5] * det, inv[6] * det],
[inv[8] * det, inv[9] * det, inv[10] * det],
[inv[12] * det, inv[13] * det, inv[14] * det]
))
else:
return matrix3(self.row1, self.row2, self.row3, self.row4)
def multiply(self, B):
C = matrix3()
A_row1_3, A_row2_3, A_row3_3, A_row4_3 = 0.0, 0.0, 0.0, 1.0
C.row1 = [
self.row1[0] * B.row1[0] + self.row1[1] * B.row2[0] + self.row1[2] * B.row3[0] + A_row1_3 * B.row4[0],
self.row1[0] * B.row1[1] + self.row1[1] * B.row2[1] + self.row1[2] * B.row3[1] + A_row1_3 * B.row4[1],
self.row1[0] * B.row1[2] + self.row1[1] * B.row2[2] + self.row1[2] * B.row3[2] + A_row1_3 * B.row4[2]
]
C.row2 = [
self.row2[0] * B.row1[0] + self.row2[1] * B.row2[0] + self.row2[2] * B.row3[0] + A_row2_3 * B.row4[0],
self.row2[0] * B.row1[1] + self.row2[1] * B.row2[1] + self.row2[2] * B.row3[1] + A_row2_3 * B.row4[1],
self.row2[0] * B.row1[2] + self.row2[1] * B.row2[2] + self.row2[2] * B.row3[2] + A_row2_3 * B.row4[2],
]
C.row3 = [
self.row3[0] * B.row1[0] + self.row3[1] * B.row2[0] + self.row3[2] * B.row3[0] + A_row3_3 * B.row4[0],
self.row3[0] * B.row1[1] + self.row3[1] * B.row2[1] + self.row3[2] * B.row3[1] + A_row3_3 * B.row4[1],
self.row3[0] * B.row1[2] + self.row3[1] * B.row2[2] + self.row3[2] * B.row3[2] + A_row3_3 * B.row4[2]
]
C.row4 = [
self.row4[0] * B.row1[0] + self.row4[1] * B.row2[0] + self.row4[2] * B.row3[0] + A_row4_3 * B.row4[0],
self.row4[0] * B.row1[1] + self.row4[1] * B.row2[1] + self.row4[2] * B.row3[1] + A_row4_3 * B.row4[1],
self.row4[0] * B.row1[2] + self.row4[1] * B.row2[2] + self.row4[2] * B.row3[2] + A_row4_3 * B.row4[2]
]
return C
def eulerAnglesToMatrix3 (rotXangle = 0.0, rotYangle = 0.0, rotZangle = 0.0):
# https://stackoverflow.com/a/47283530
cosY = math.cos(rotZangle)
sinY = math.sin(rotZangle)
cosP = math.cos(rotYangle)
sinP = math.sin(rotYangle)
cosR = math.cos(rotXangle)
sinR = math.sin(rotXangle)
m = matrix3 (
[cosP * cosY, cosP * sinY, -sinP],
[sinR * cosY * sinP - sinY * cosR, cosY * cosR + sinY * sinP * sinR, cosP * sinR],
[sinY * sinR + cosR * cosY * sinP, cosR * sinY * sinP - sinR * cosY, cosR * cosP],
[0.0, 0.0, 0.0]
)
return m
class skinOps:
mesh = None
skin = None
armature = None
def __init__(self, meshObj, armObj, skinName="Skin"):
self.mesh = meshObj
self.armature = armObj
if self.mesh != None:
for m in self.mesh.modifiers:
if m.type == "ARMATURE":
self.skin = m
break
if self.skin == None:
self.skin = self.mesh.modifiers.new(type="ARMATURE", name=skinName)
self.skin.use_vertex_groups = True
self.skin.object = self.armature
self.mesh.parent = self.armature
def addbone(self, boneName, update_flag=0):
# Adds a bone to the vertex group list
# print("boneName:\t%s" % boneName)
vertGroup = self.mesh.vertex_groups.get(boneName)
if not vertGroup:
self.mesh.vertex_groups.new(name=boneName)
return None
def NormalizeWeights(self, weight_array, roundTo=0):
# Makes All weights in the weight_array sum to 1.0
# Set roundTo 0.01 to limit weight; 0.33333 -> 0.33
n = []
if len(weight_array) > 0:
s = 0.0
n = [float] * len(weight_array)
for i in range(0, len(weight_array)):
if roundTo != 0:
n[i] = (float(int(weight_array[i] * (1.0 / roundTo)))) / (1.0 / roundTo)
else:
n[i] = weight_array[i]
s += n[i]
s = 1.0 / s
for i in range(0, len(weight_array)):
n[i] *= s
return n
def GetNumberBones(self):
# Returns the number of bones present in the vertex group list
num = 0
for b in self.armature.data.bones:
if self.mesh.vertex_groups.get(b.name):
num += 1
return num
def GetNumberVertices(self):
# Returns the number of vertices for the object the Skin modifier is applied to.
return len(self.mesh.data.vertices)
def ReplaceVertexWeights(self, vertex_integer, vertex_bone_array, weight_array):
# Sets the influence of the specified bone(s) to the specified vertex.
# Any influence weights for the bone(s) that are not specified are erased.
# If the bones and weights are specified as arrays, the arrays must be of the same size.
# Check that both arrays match
numWeights = len(vertex_bone_array)
if len(weight_array) == numWeights and numWeights > 0:
# Erase Any Previous Weight
for g in self.mesh.data.vertices[vertex_integer].groups:
self.mesh.vertex_groups[g.index].add([vertex_integer], 0.0, 'REPLACE')
# Add New Weights
for i in range(0, numWeights):
self.mesh.vertex_groups[vertex_bone_array[i]].add([vertex_integer], weight_array[i], 'REPLACE')
return True
return False
def GetVertexWeightCount(self, vertex_integer):
# Returns the number of bones (vertex groups) influencing the specified vertex.
num = 0
for g in self.mesh.vertices[vertex_integer].groups:
# need to write more crap
# basically i need to know if the vertex group is for a bone and is even label as deformable
# but lzy, me fix l8tr
num += 1
return num
def boneAffectLimit(self, limit):
# Reduce the number of bone influences affecting a single vertex
# I copied and pasted busted ass code from somewhere as an example to
# work from... still need to write this out but personally dont have a
# need for it
# for v in self.mesh.vertices:
# # Get a list of the non-zero group weightings for the vertex
# nonZero = []
# for g in v.groups:
# g.weight = round(g.weight, 4)
# if g.weight & lt; .0001:
# continue
# nonZero.append(g)
# # Sort them by weight decending
# byWeight = sorted(nonZero, key=lambda group: group.weight)
# byWeight.reverse()
# # As long as there are more than 'maxInfluence' bones, take the lowest influence bone
# # and distribute the weight to the other bones.
# while len(byWeight) & gt; limit:
# #print("Distributing weight for vertex %d" % (v.index))
# # Pop the lowest influence off and compute how much should go to the other bones.
# minInfluence = byWeight.pop()
# distributeWeight = minInfluence.weight / len(byWeight)
# minInfluence.weight = 0
# # Add this amount to the other bones
# for influence in byWeight:
# influence.weight = influence.weight + distributeWeight
# # Round off the remaining values.
# for influence in byWeight:
# influence.weight = round(influence.weight, 4)
return None
def GetVertexWeightBoneID(self, vertex_integer, vertex_bone_integer):
# Returns the vertex group index of the Nth bone affecting the specified vertex.
return None
def GetVertexWeight(self, vertex_integer, vertex_bone_integer):
# Returns the influence of the Nth bone affecting the specified vertex.
for v in mesh.data.vertices: # <MeshVertex> https://docs.blender.org/api/current/bpy.types.MeshVertex.html
weights = [g.weight for g in v.groups]
boneids = [g.group for g in v.groups]
# return [vert for vert in bpy.context.object.data.vertices if bpy.context.object.vertex_groups['vertex_group_name'].index in [i.group for i in vert.groups]]
return [vert for vert in bpy.context.object.data.vertices if
bpy.context.object.vertex_groups['vertex_group_name'].index in [i.group for i in vert.groups]]
def GetVertexWeightByBoneName(self, vertex_bone_name):
return [vert for vert in self.mesh.data.vertices if
self.mesh.data.vertex_groups[vertex_bone_name].index in [i.group for i in vert.groups]]
def GetSelectedBone(self):
# Returns the index of the current selected bone in the Bone list.
return self.mesh.vertex_groups.active_index
def GetBoneName(self, bone_index, nameflag_index=0):
# Returns the bone name or node name of a bone specified by ID.
name = ""
try:
name = self.mesh.vertex_groups[bone_index].name
except:
pass
return name
def GetListIDByBoneID(self, BoneID_integer):
# Returns the ListID index given the BoneID index value.
# The VertexGroupListID index is the index into the name-sorted.
# The BoneID index is the non-sorted index, and is the index used by other methods that require a bone index.
index = -1
try:
index = self.mesh.vertex_groups[self.armature.data.bones[BoneID_integer]].index
except:
pass
return index
def GetBoneIDByListID(self, bone_index):
# Returns the BoneID index given the ListID index value. The ListID index is the index into the name-sorted bone listbox.
# The BoneID index is the non-sorted index, and is the index used by other methods that require a bone index
index = -1
try:
index = self.armature.data.bones[self.mesh.vertex_groups[bone_index].name].index
except:
pass
return index
def weightAllVertices(self):
# Ensure all weights have weight and that are equal to a sum of 1.0
return None
def clearZeroWeights(self, limit=0.0):
# Removes weights that are a threshold
# for v in self.mesh.vertices:
# nonZero = []
# for g in v.groups:
# g.weight = round(g.weight, 4)
# if g.weight & le; limit:
# continue
# nonZero.append(g)
# # Sort them by weight decending
# byWeight = sorted(nonZero, key=lambda group: group.weight)
# byWeight.reverse()
# # As long as there are more than 'maxInfluence' bones, take the lowest influence bone
# # and distribute the weight to the other bones.
# while len(byWeight) & gt; limit:
# #print("Distributing weight for vertex %d" % (v.index))
# # Pop the lowest influence off and compute how much should go to the other bones.
# minInfluence = byWeight.pop()
# distributeWeight = minInfluence.weight / len(byWeight)
# minInfluence.weight = 0
# # Add this amount to the other bones
# for influence in byWeight:
# influence.weight = influence.weight + distributeWeight
# # Round off the remaining values.
# for influence in byWeight:
# influence.weight = round(influence.weight, 4)
return None
def SelectBone(self, bone_integer):
# Selects the specified bone in the Vertex Group List
self.mesh.vertex_groups.active_index = bone_integer
return None
# Probably wont bother writing this unless I really need this ability
def saveEnvelope(self):
# Saves Weight Data to an external binary file
return None
def saveEnvelopeAsASCII(self):
# Saves Weight Data to an external ASCII file
envASCII = "ver 3\n"
envASCII = "numberBones " + str(self.GetNumberBones()) + "\n"
num = 0
for b in self.armature.data.bones:
if self.mesh.vertex_groups.get(b.name):
envASCII += "[boneName] " + b.name + "\n"
envASCII += "[boneID] " + str(num) + "\n"
envASCII += " boneFlagLock 0\n"
envASCII += " boneFlagAbsolute 2\n"
envASCII += " boneFlagSpline 0\n"
envASCII += " boneFlagSplineClosed 0\n"
envASCII += " boneFlagDrawEnveloe 0\n"
envASCII += " boneFlagIsOldBone 0\n"
envASCII += " boneFlagDead 0\n"
envASCII += " boneFalloff 0\n"
envASCII += " boneStartPoint 0.000000 0.000000 0.000000\n"
envASCII += " boneEndPoint 0.000000 0.000000 0.000000\n"
envASCII += " boneCrossSectionCount 2\n"
envASCII += " boneCrossSectionInner0 3.750000\n"
envASCII += " boneCrossSectionOuter0 13.125000\n"
envASCII += " boneCrossSectionU0 0.000000\n"
envASCII += " boneCrossSectionInner1 3.750000\n"
envASCII += " boneCrossSectionOuter1 13.125000\n"
envASCII += " boneCrossSectionU1 1.000000\n"
num += 1
envASCII += "[Vertex Data]\n"
envASCII += " nodeCount 1\n"
envASCII += " [baseNodeName] " + self.mesh.name + "\n"
envASCII += " vertexCount " + str(len(self.mesh.vertices)) + "\n"
for v in self.mesh.vertices:
envASCII += " [vertex" + str(v.index) + "]\n"
envASCII += " vertexIsModified 0\n"
envASCII += " vertexIsRigid 0\n"
envASCII += " vertexIsRigidHandle 0\n"
envASCII += " vertexIsUnNormalized 0\n"
envASCII += " vertexLocalPosition 0.000000 0.000000 24.38106\n"
envASCII += " vertexWeightCount " + str(len(v.groups)) + "\n"
envASCII += " vertexWeight "
for g in v.groups:
envASCII += str(g.group) + ","
envASCII += str(g.weight) + " "
envASCII += " vertexSplineData 0.000000 0 0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 "
envASCII += " numberOfExclusinList 0\n"
return envASCII
def loadEnvelope(self):
# Imports Weight Data to an external Binary file
return None
def loadEnvelopeAsASCII(self):
# Imports Weight Data to an external ASCII file
return None
class boneSys:
armature = None
layer = None
def __init__(self, armatureName="Skeleton", layerName="", rootName="Scene Root"):
# Clear Any Object Selections
# for o in bpy.context.selected_objects: o.select = False
bpy.context.view_layer.objects.active = None
# Get Collection (Layers)
if self.layer == None:
if layerName != "":
# make collection
self.layer = bpy.data.collections.new(layerName)
bpy.context.scene.collection.children.link(self.layer)
else:
self.layer = bpy.data.collections[bpy.context.view_layer.active_layer_collection.name]
# Check for Armature
armName = armatureName
if armatureName == "": armName = "Skeleton"
self.armature = bpy.context.scene.objects.get(armName)
if self.armature == None:
# Create Root Bone
root = bpy.data.armatures.new(rootName)
root.name = rootName
# Create Armature
self.armature = bpy.data.objects.new(armName, root)
self.layer.objects.link(self.armature)
self.armature.display_type = 'WIRE'
self.armature.show_in_front = True
def editMode(self, enable=True):
#
# Data Pointers Seem to get arranged between
# Entering and Exiting EDIT Mode, which is
# Required to make changes to the bones
#
# This needs to be called beofre and after making changes
#
if enable:
# Clear Any Object Selections
bpy.context.view_layer.objects.active = None
# Set Armature As Active Selection
if bpy.context.view_layer.objects.active != self.armature:
bpy.context.view_layer.objects.active = self.armature
# Switch to Edit Mode
if bpy.context.object.mode != 'EDIT':
bpy.ops.object.mode_set(mode='EDIT', toggle=False)
else:
bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
return None
def count(self):
return len(self.armature.data.bones)
def getNodeByName(self, boneName):
# self.editMode(True)
node = None
try:
# node = self.armature.data.bones.get('boneName')
node = self.armature.data.edit_bones[boneName]
except:
pass
# self.editMode(False)
return node
def getChildren(self, boneName):
childs = []
b = self.getNodeByName(boneName)
if b != None:
for bone in self.armature.data.edit_bones:
if bone.parent == b: childs.append(bone)
return childs
def setParent(self, boneName, parentName):
b = self.getNodeByName(boneName)
p = self.getNodeByName(parentName)
if b != None and p != None:
b.parent = p
return True
return False
def getParent(self, boneName):
par = None
b = self.getNodeByName(boneName)
if b != None: par = b.parent
return par
def getPosition(self, boneName):
position = (0.0, 0.0, 0.0)
b = self.getNodeByName(boneName)
if b != None:
position = (
self.armature.location[0] + b.head[0],
self.armature.location[1] + b.head[1],
self.armature.location[2] + b.head[2],
)
return position
def setPosition(self, boneName, position):
b = self.getNodeByName(boneName)
pos = (
position[0] - self.armature.location[0],
position[1] - self.armature.location[1],
position[2] - self.armature.location[2]
)
if b != None and distance(b.tail, pos) > 0.0000001: b.head = pos
return None
def getEndPosition(self, boneName):
position = (0.0, 0.0, 0.0)
b = self.getNodeByName(boneName)
if b != None:
position = (
self.armature.location[0] + b.tail[0],
self.armature.location[1] + b.tail[1],
self.armature.location[2] + b.tail[2],
)
return position
def setEndPosition(self, boneName, position):
b = self.getNodeByName(boneName)
pos = (
position[0] - self.armature.location[0],
position[1] - self.armature.location[1],
position[2] - self.armature.location[2]
)
if b != None and distance(b.head, pos) > 0.0000001: b.tail = pos
return None
def setUserProp(self, boneName, key_string, value):
b = self.getNodeByName(boneName)
try:
if b != None: b[key_string] = value
return True
except:
return False
def getUserProp(self, boneName, key_string):
value = None
b = self.getNodeByName(boneName)
if b != None:
try:
value = b[key_string]
except:
pass
return value
def setTransform(self, boneName,
matrix=((1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0), (1.0, 0.0, 0.0, 1.0))):
b = self.getNodeByName(boneName)
if b != None:
b.matrix = matrix
return True
return False
def setVisibility(self, boneName, visSet=(
True, False, False, False, False, False, False, False, False, False, False, False, False, False, False,
False,
False, False, False, False, False, False, False, False, False, False, False, False, False, False, False,
False)):
# Assign Visible Layers
b = self.getNodeByName(boneName)
if b != None:
b.layers = visSet
return True
return False
def setBoneGroup(self, boneName, normalCol=(0.0, 0.0, 0.0), selctCol=(0.0, 0.0, 0.0), activeCol=(0.0, 0.0, 0.0)):
# Create Bone Group (custom bone colours ??)
b = self.getNodeByName(boneName)
if b != None:
# arm = bpy.data.objects.new("Armature", bpy.data.armatures.new("Skeleton"))
# layer.objects.link(arm)
# obj.parent = arm
# bgrp = self.armature.pose.bone_groups.new(name=msh.name)
# bgrp.color_set = 'CUSTOM'
# bgrp.colors.normal = normalCol
# bgrp.colors.select = selctCol
# bgrp.colors.active = activeCol
# for b in obj.vertex_groups.keys():
# self.armature.pose.bones[b].bone_group = bgrp
return True
return False
def createBone(self, boneName="", startPos=(0.0, 0.0, 0.0), endPos=(0.0, 0.0, 1.0), zAxis=(1.0, 0.0, 0.0)):
self.editMode(True)
# Check if bone exists
b = None
if boneName != "":
try:
b = self.armature.data.edit_bones[boneName]
return False
except:
pass
if b == None:
# Generate Bone Name
bName = boneName
if bName == "": bName = "Bone_" + '{:04d}'.format(len(self.armature.data.edit_bones))
# Create Bone
b = self.armature.data.edit_bones.new(bName)
#b = self.armature.data.edit_bones.new(bName.decode('utf-8', 'replace'))
b.name = bName
# Set As Deform Bone
b.use_deform = True
# Set Rotation
roll, pitch, yaw = 0.0, 0.0, 0.0
try:
roll = math.acos((dot(zAxis, (1, 0, 0))) / (
math.sqrt(((pow(zAxis[0], 2)) + (pow(zAxis[1], 2)) + (pow(zAxis[2], 2)))) * 1.0))
except:
pass
try:
pitch = math.acos((dot(zAxis, (0, 1, 0))) / (
math.sqrt(((pow(zAxis[0], 2)) + (pow(zAxis[1], 2)) + (pow(zAxis[2], 2)))) * 1.0))
except:
pass
try:
yaw = math.acos((dot(zAxis, (0, 0, 1))) / (
math.sqrt(((pow(zAxis[0], 2)) + (pow(zAxis[1], 2)) + (pow(zAxis[2], 2)))) * 1.0))
except:
pass
su = math.sin(roll)
cu = math.cos(roll)
sv = math.sin(pitch)
cv = math.cos(pitch)
sw = math.sin(yaw)
cw = math.cos(yaw)
b.matrix = (
(cv * cw, su * sv * cw - cu * sw, su * sw + cu * sv * cw, 0.0),
(cv * sw, cu * cw + su * sv * sw, cu * sv * sw - su * cw, 0.0),
(-sv, su * cv, cu * cv, 0.0),
(startPos[0], startPos[1], startPos[2], 1.0)
)
# Set Length (has to be larger then 0.1?)
b.length = 1.0
if startPos != endPos:
b.head = startPos
b.tail = endPos
# Exit Edit Mode
self.editMode(False)
return True
def rebuildEndPositions (self, mscale=1.0):
for b in self.armature.data.edit_bones:
children = self.getChildren(b.name)
if len(children) == 1: # Only One Child, Link End to the Child
self.setEndPosition(b.name, self.getPosition(children[0].name))
elif len(children) > 1: # Multiple Children, Link End to the Average Position of all Children
childPosAvg = [0.0, 0.0, 0.0]
for c in children:
childPos = self.getPosition(c.name)
childPosAvg[0] += childPos[0]
childPosAvg[1] += childPos[1]
childPosAvg[2] += childPos[2]
self.setEndPosition(b.name,
(childPosAvg[0] / len(children),
childPosAvg[1] / len(children),
childPosAvg[2] / len(children))
)
elif b.parent != None: # No Children use inverse of parent position
childPos = self.getPosition(b.name)
parPos = self.getPosition(b.parent.name)
boneLength = distance(parPos, childPos)
boneLength = 0.04 * mscale
boneNorm = normalize(
(childPos[0] - parPos[0],
childPos[1] - parPos[1],
childPos[2] - parPos[2])
)
self.setEndPosition(b.name,
(childPos[0] + boneLength * boneNorm[0],
childPos[1] + boneLength * boneNorm[1],
childPos[2] + boneLength * boneNorm[2])
)
return None
def messageBox(message="", title="Message Box", icon='INFO'):
def draw(self, context): self.layout.label(text=message)
bpy.context.window_manager.popup_menu(draw, title=title, icon=icon)
return None
def getNodeByName(nodeName):
return bpy.context.scene.objects.get(nodeName)
def classof(nodeObj):
try:
return str(nodeObj.type)
except:
return None
def makeDir(folderName):
return Path(folderName).mkdir(parents=True, exist_ok=True)
def setUserProp(node, key_string, value):