forked from animate1978/MB-Lab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
humanoid.py
executable file
·1274 lines (1031 loc) · 48 KB
/
humanoid.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
# MB-Lab
#
# MB-Lab fork website : https://github.com/animate1978/MB-Lab
#
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
#
# ManuelbastioniLAB - Copyright (C) 2015-2018 Manuel Bastioni
import logging
import bpy
# TODO pathlib might replace the current import os
# from pathlib import Path
import os
import time
import json
import operator
from . import morphengine, skeletonengine, algorithms, proxyengine, materialengine, utils, file_ops, object_ops
logger = logging.getLogger(__name__)
class HumanModifier:
"""
A modifier is a group of related properties.
"""
def __init__(self, name, obj_name):
self.name = name
#Teto
self.short_name = name.split("_")[1] #can change after when added to a category
#End Teto
self.obj_name = obj_name
self.properties = []
def get_object(self):
"""
Get the blender object. It can't be stored because
Blender's undo and redo change the memory locations
"""
if self.obj_name in bpy.data.objects:
return bpy.data.objects[self.obj_name]
return None
def add(self, prop):
self.properties.append(prop)
def __contains__(self, prop):
for propx in self.properties:
if propx == prop:
return True
return False
def get_properties(self):
"""
Return the properties contained in the
modifier. Important: keep unsorted!
"""
return self.properties
def get_property(self, prop):
"""
Return the property by name.
"""
for propx in self.properties:
if propx == prop:
return propx
return None
def is_changed(self, char_data):
"""
If a prop is changed, the whole modifier is considered changed
"""
obj = self.get_object()
for prop in self.properties:
current_val = getattr(obj, prop, 0.5)
if char_data[prop] != current_val:
return True
return False
def sync_modifier_data_to_obj_prop(self, char_data):
obj = self.get_object()
for prop in self.properties:
if hasattr(obj, prop):
current_val = getattr(obj, prop, 0.5)
char_data[prop] = current_val
def __lt__(self, other):
return self.name < other.name
def __repr__(self):
return "Modifier <{0}> with {1} properties: {2}".format(
self.name,
len(self.properties),
self.properties)
class HumanCategory:
"""
A category is a group of related modifiers
"""
def __init__(self, name):
self.name = name
self.modifiers = []
def add(self, modifier):
self.modifiers.append(modifier)
def get_modifiers(self):
return self.modifiers
def get_modifier(self, name):
for modifier in self.modifiers:
if modifier.name == name:
return modifier
return None
#Teto
def get_modifier_short_name(self, name):
modif = self.get_modifier(name)
if modif == None:
return ""
return modif.short_name
def get_modifier_tiny_name(self, sub_categories=[], exclude_in_others=[]):
# Return the short name minus the beginning
# of its name corresponding to sub_category
# The key is subcategory name.
# The value is [tiny, short, full]
# Method used only for expressions editor for now
# exclude_in_others means that the modifiers' name that are in this
# list can't be put in "other" category
if len(sub_categories) > 0:
tiny = {'other': []}
triple = []
done = False
false_others = False
sub_categories = sorted(sub_categories, reverse = True)
for modif in self.modifiers:
for sub in sub_categories:
if not sub in tiny:
tiny[sub] = []
if modif.short_name.startswith(sub):
triple = [modif.short_name.lstrip(sub), modif.short_name, modif.name]
tiny[sub].append(triple)
done = True
break
if done:
done = False
else:
for fo in exclude_in_others:
if modif.short_name.startswith(fo) or modif.short_name.startswith("ID"):
false_others = True
if false_others:
false_others = False
else:
tiny['other'].append([modif.short_name, modif.short_name, modif.name])
return tiny
return {}
#End Teto
def get_all_properties(self):
"""
Return all properties involved in the category,
sorted and without double entries.
"""
properties = []
for modifier in self.modifiers:
for prop in modifier.properties:
if prop not in properties:
properties.append(prop)
properties.sort()
return properties
def __contains__(self, mdf):
for modifier in self.modifiers:
if mdf.name == modifier.name:
return True
return False
def __lt__(self, other):
return self.name < other.name
def __repr__(self):
return "Category {0} with {1} modifiers".format(
self.name,
len(self.modifiers))
class Humanoid:
"""
The humanoid is a container for categories of modifiers.
"""
def __init__(self, lab_version):
self.lab_vers = list(lab_version)
self.has_data = False
self.obj_name = ""
self.characters_config = file_ops.get_configuration()
self.data_path = file_ops.get_data_path()
self.lib_filepath = file_ops.get_blendlibrary_path()
if self.characters_config:
self.humanoid_types = self.build_items_list("character_list")
self.template_types = self.build_items_list("templates_list")
self.data_directory = file_ops.get_data_path()
def is_muscle_rig_available(self, character_identifier):
if self.characters_config[character_identifier]["vertexgroup_muscle_file"] != "":
return True
return False
def is_ik_rig_available(self, character_identifier):
if self.characters_config[character_identifier]["joints_offset_file"] != "":
return True
return False
def build_items_list(self, main_key):
item_list = []
if self.characters_config:
for char_id in self.characters_config[main_key]:
if char_id in self.characters_config:
lbl = self.characters_config[char_id]["label"]
dsc = self.characters_config[char_id]["description"]
item_list.append((char_id, lbl, dsc))
return item_list
def init_database(self, obj, character_identifier, rigging_type):
scn = bpy.context.scene
self.has_data = False
self.obj_name = obj.name
logger.info("Found the humanoid: {0}".format(character_identifier))
logger.info("Init the database...")
self.no_categories = "BasisAsymTest"
self.categories = {}
self.bodydata_realtime_activated = True
self.sk_engine = skeletonengine.SkeletonEngine(obj, self.characters_config[character_identifier], rigging_type)
self.character_template_name = self.characters_config[character_identifier]["template_model"]
self.transformation_filename = self.characters_config[character_identifier]["transformations_file"]
self.phenotype_data_folder = self.characters_config[character_identifier]["name"]+"_ptypes"
self.presets_data_folder = self.characters_config[character_identifier]["presets_folder"]
self.phenotypes_path = os.path.join(self.data_path, "phenotypes", self.phenotype_data_folder)
self.presets_path = os.path.join(self.data_path, "presets", self.presets_data_folder)
self.restposes_path = os.path.join(self.data_path, "poses", "rest_poses")
self.transformations_data_path = os.path.join(self.data_path, "transformations", self.transformation_filename)
self.exists_rest_poses_data = file_ops.exists_database(self.restposes_path)
self.exists_preset_data = file_ops.exists_database(self.presets_path)
self.exists_phenotype_data = file_ops.exists_database(self.phenotypes_path)
self.exists_transform_data = os.path.isfile(self.transformations_data_path)
self.corrective_modifier_name = "mbastlab_corrective_modifier"
self.morph_engine = morphengine.MorphingEngine(self.obj_name, self.characters_config[character_identifier])
self.mat_engine = materialengine.MaterialEngine(self.obj_name, self.characters_config[character_identifier])
self.character_data = {}
self.character_metaproperties = {"last_character_age": 0.0,
"character_age": 0.0,
"last_character_mass": 0.0,
"character_mass": 0.0,
"last_character_tone": 0.0,
"character_tone": 0.0}
self.character_material_properties = self.mat_engine.get_material_parameters()
self.metadata_realtime_activated = True
self.material_realtime_activated = True
self.transformations_data = {}
for morph in self.morph_engine.morph_data.keys():
self.init_character_data(morph)
logger.info("Loaded {0} categories from morph database".format(
len(self.categories)))
bpy.context.view_layer.objects.active = obj
self.measures = self.morph_engine.measures
self.delta_measures = {}
self.init_delta_measures()
self.load_transformation_database()
self.add_corrective_smooth_modifier()
self.add_subdivision_modifier()
self.add_displacement_modifier()
self.has_data = True
def add_subdivision_modifier(self):
obj = self.get_object()
parameters = {"levels": 2, "render_levels": 3, "show_viewport": True, "show_in_editmode": False}
object_ops.new_modifier(obj, self.mat_engine.subdivision_modifier_name, 'SUBSURF', parameters)
def add_displacement_modifier(self):
obj = self.get_object()
disp_img = file_ops.get_image(self.mat_engine.image_file_names["body_displ"])
if disp_img:
disp_tex = file_ops.new_texture(self.mat_engine.generated_disp_modifier_ID, disp_img)
parameters = {"texture_coords":'UV', "strength": 0.01, "show_viewport": False, "texture": disp_tex}
displacement_modifier = object_ops.new_modifier(obj, self.mat_engine.generated_disp_modifier_ID, 'DISPLACE', parameters)
def get_data_directory(self):
return self.data_directory
def rename_obj(self, prefix):
obj = self.get_object()
if prefix != "":
obj.name = prefix +"_body"
else:
obj.name = "MBlab_bd"+str(time.time())
def rename_armature(self, prefix):
armat = self.get_armature()
if prefix != "":
armat.name = prefix +"_armature"
else:
armat.name = "MBlab_sk"+str(time.time())
def rename_materials(self, prefix):
self.mat_engine.rename_skin_shaders(prefix)
def get_object(self):
if self.obj_name in bpy.data.objects:
return bpy.data.objects[self.obj_name]
return None
def get_armature(self):
return self.sk_engine.get_armature()
def load_transformation_database(self):
self.transformations_data = file_ops.load_json_data(self.transformations_data_path, "Transformations database")
def get_categories(self, exlude_names=[]):
if exlude_names == []:
categories = self.categories.values()
return sorted(categories)
categories = []
for key, value in self.categories.items():
if key not in exlude_names:
categories.append(value)
return sorted(categories)
def get_root_model_name(self):
if len(self.data_directory) > 0 and self.data_directory != "data":
return self.data_directory
if len(self.obj_name) < 1:
return ""
# Legacy... lines below are just for anime and human models...
for name in self.get_category("Expressions").get_all_properties():
if name.startswith("Expressions_ID"):
rmn = name.split("_")[1]
rmn = rmn[2:]
self.root_model_name = rmn.lower()
if self.root_model_name == "humans": # Dirty trick...
self.root_model_name = "human"
return self.root_model_name
def get_category(self, name):
if name in self.categories:
return self.categories[name]
def get_properties_in_category(self, name):
return self.categories[name].get_all_properties()
def init_character_data(self, morph_name):
"""
Creates categories and properties from shapekey name
"""
components = morph_name.split("_")
if components[0][:4] not in self.no_categories:
if len(components) == 3: #Is that really necessary ?
category_name = components[0]
# Expressions and regular morphs are mixed
# Both are considered as morphs (that is true)
if category_name not in self.categories:
# if category doesn't exist yet
category = HumanCategory(category_name)
self.categories[category_name] = category
else:
category = self.categories[category_name]
# The modifier is used to store properties
modifier_name = components[0]+"_"+components[1]
modifier = category.get_modifier(modifier_name)
if not modifier: # Create a new property to the modifier
modifier = HumanModifier(modifier_name, self.obj_name)
category.add(modifier)
for element in components[1].split("-"):
# Now add property
prop = components[0]+"_" + element
if prop not in modifier:
modifier.add(prop)
self.character_data[prop] = 0.5
else:
logger.warning("Wrong name for morph: {0}".format(morph_name))
def reset_category(self, categ):
time1 = time.time()
obj = self.get_object()
category = self.get_category(categ)
for prop in category.get_all_properties():
self.character_data[prop] = 0.5
self.update_character(category_name=category.name, mode="update_all")
logger.info("Category resetted in {0} secs".format(time.time()-time1))
def exists_measure_database(self):
return self.morph_engine.measures_database_exist
def exists_dermal_texture(self):
return self.mat_engine.texture_dermal_exist
def exists_displace_texture(self):
return self.mat_engine.texture_displace_exist
def exists_rest_poses_database(self):
return self.exists_rest_poses_data
def exists_expression_database(self):
return self.exists_expression_data
def exists_preset_database(self):
return self.exists_preset_data
def exists_phenotype_database(self):
return self.exists_phenotype_data
def exists_transform_database(self):
return self.exists_transform_data
def automodelling(self, use_measures_from_GUI=False, use_measures_from_dict=None, use_measures_from_current_obj=False, mix=False):
if self.morph_engine.measures_database_exist:
time2 = time.time()
obj = self.get_object()
n_samples = 3
if use_measures_from_GUI:
convert_to_inch = getattr(obj, "mblab_use_inch", False)
if convert_to_inch:
conversion_factor = 39.37001
else:
conversion_factor = 100
wished_measures = {}
for measure_name in self.morph_engine.measures.keys():
if measure_name != "body_height_Z":
wished_measures[measure_name] = getattr(obj, measure_name, 0.5)/conversion_factor
total_height_Z = 0
for measure_name in self.morph_engine.body_height_Z_parts:
total_height_Z += wished_measures[measure_name]
wished_measures["body_height_Z"] = total_height_Z
if use_measures_from_current_obj:
current_shape_verts = []
for vert in obj.data.vertices:
current_shape_verts.append(vert.co.copy())
wished_measures = self.morph_engine.calculate_measures(vert_coords=current_shape_verts)
if use_measures_from_dict:
wished_measures = use_measures_from_dict
self.morph_engine.calculate_proportions(wished_measures)
similar_characters_data = self.morph_engine.compare_data_proportions()
best_character = similar_characters_data[0]
filepath = best_character[1]
self.load_character(filepath)
if mix:
for char_data in similar_characters_data[1:n_samples]:
filepath = char_data[1]
self.load_character(filepath, mix=True)
self.measure_fitting(wished_measures, mix)
self.update_character(mode="update_directly_verts")
algorithms.select_and_change_mode(obj, 'OBJECT')
logger.info("Human fitting in {0} secs".format(time.time()-time2))
def clean_verts_to_process(self):
self.morph_engine.verts_to_update.clear()
def update_displacement(self):
obj = self.get_object()
age_factor = obj.character_age
tone_factor = obj.character_tone
mass_factor = obj.character_mass
self.mat_engine.calculate_displacement_texture(age_factor, tone_factor, mass_factor)
def remove_modifiers(self):
obj = self.get_object()
for modf in obj.modifiers:
if "mbastlab" in modf.name:
if "armature" not in modf.name:
obj.modifiers.remove(modf)
def save_body_displacement_texture(self, filepath):
self.mat_engine.save_texture(filepath, "body_displ")
def save_body_dermal_texture(self, filepath):
self.mat_engine.save_texture(filepath, "body_derm")
def save_all_textures(self, filepath):
targets = ["body_derm", "body_displ", "teeth_albedo", "eyes_albedo", "tongue_albedo", "freckle_mask", "blush", "sebum", "thickness","melanin", "lipmap", "iris_color", "iris_bump", "sclera_color", "translucent_mask", "sclera_mask", "body_bump"]
for target in targets:
dir_path = os.path.dirname(filepath)
filename = os.path.basename(filepath)
filename_root = os.path.splitext(filename)[0]
filename_ext = os.path.splitext(filename)[1]
new_filename = filename_root +"_"+ target+ filename_ext
new_filepath = os.path.join(dir_path, new_filename)
self.mat_engine.save_texture(new_filepath, target)
def save_backup_character(self, filepath):
dir_path = os.path.dirname(filepath)
filename = os.path.basename(filepath)
filename_root = os.path.splitext(filename)[0]
new_filename = filename_root + 'backup.json'
new_filepath = os.path.join(dir_path, new_filename)
logger.info("Saving backup character {0}".format(file_ops.simple_path(new_filepath)))
self.save_character(new_filepath, export_proportions=False, export_materials=True, export_metadata=True)
def get_subd_visibility(self):
obj = self.get_object()
modfr = algorithms.get_modifier(obj, self.mat_engine.subdivision_modifier_name)
return algorithms.get_modifier_viewport(modfr)
def set_subd_visibility(self, value):
obj = self.get_object()
modfr = algorithms.get_modifier(obj, self.mat_engine.subdivision_modifier_name)
algorithms.set_modifier_viewport(modfr, value)
def set_smooth_visibility(self, value):
obj = self.get_object()
modfr = algorithms.get_modifier(obj, self.corrective_modifier_name)
algorithms.set_modifier_viewport(modfr, value)
def get_smooth_visibility(self):
obj = self.get_object()
modfr = algorithms.get_modifier(obj, self.corrective_modifier_name)
return algorithms.get_modifier_viewport(modfr)
def get_disp_visibility(self):
obj = self.get_object()
modfr = algorithms.get_modifier(obj, self.mat_engine.generated_disp_modifier_ID)
return algorithms.get_modifier_viewport(modfr)
def set_disp_visibility(self, value):
obj = self.get_object()
modfr = algorithms.get_modifier(obj, self.mat_engine.generated_disp_modifier_ID)
algorithms.set_modifier_viewport(modfr, value)
def sync_obj_props_to_character_materials(self):
self.material_realtime_activated = False
obj = self.get_object()
for material_data_prop, value in self.character_material_properties.items():
if hasattr(obj, material_data_prop):
setattr(obj, material_data_prop, value)
else:
logger.warning("material {0} not found".format(material_data_prop))
self.material_realtime_activated = True
def update_materials(self, update_textures_nodes=True):
obj = self.get_object()
for prop in self.character_material_properties.keys():
if hasattr(obj, prop):
self.character_material_properties[prop] = getattr(obj, prop)
self.mat_engine.update_shaders(self.character_material_properties, update_textures_nodes)
def correct_expressions(self, correct_all=False):
"""
Correct all the expression morphing that are different from 0
"""
time1 = time.time()
expressions_to_correct = []
for prop in self.categories["Expressions"].get_all_properties():
if not correct_all:
if self.character_data[prop] != 0.5:
expressions_to_correct.append(prop)
else:
expressions_to_correct.append(prop)
self.morph_engine.correct_morphs(expressions_to_correct)
#if finish_it:
#self.morph_engine.apply_finishing_morph()
logger.info("Expression corrected in {0} secs".format(time.time()-time1))
def reset_character(self):
time1 = time.time()
obj = self.get_object()
self.reset_metadata()
for category in self.get_categories():
for modifier in category.get_modifiers():
for prop in modifier.get_properties():
self.character_data[prop] = 0.5
self.update_character(mode="update_all")
logger.info("Character reset in {0} secs".format(time.time()-time1))
def reset_metadata(self):
obj = self.get_object()
for meta_data_prop in self.character_metaproperties.keys():
self.character_metaproperties[meta_data_prop] = 0.0
def reset_mesh(self):
self.morph_engine.reset()
def store_mesh_in_cache(self):
self.morph_engine.copy_in_cache()
def restore_mesh_from_cache(self):
self.morph_engine.copy_from_cache()
self.morph_engine.update(update_all_verts=True)
self.morph_engine.clean_the_cache()
def sync_obj_props_to_character_metadata(self):
self.metadata_realtime_activated = False
obj = self.get_object()
for meta_data_prop, value in self.character_metaproperties.items():
if hasattr(obj, meta_data_prop):
setattr(obj, meta_data_prop, value)
else:
if "last" not in meta_data_prop:
logger.error("metadata {0}.{1} not found".format(obj.name, meta_data_prop))
self.metadata_realtime_activated = True
def delete_all_properties(self):
time1 = time.time() # TODO: usare obj.keys per lavorare solo sui valory applicati
logger.info("Deleting custom properties")
obj = self.get_object()
props_to_delete = set(["manuellab_vers", "mblab_use_inch", "manuellab_rig"])
for category in self.get_categories():
for modifier in category.get_modifiers():
for prop in modifier.get_properties():
if hasattr(obj, prop):
props_to_delete.add(prop)
for measure in self.morph_engine.measures.keys():
if hasattr(obj, measure):
props_to_delete.add(measure)
for metaproperty in self.character_metaproperties.keys():
if hasattr(obj, metaproperty):
props_to_delete.add(metaproperty)
obj = self.get_object()
for material_prop in self.character_material_properties.keys():
if hasattr(obj, material_prop):
props_to_delete.add(material_prop)
for prop in props_to_delete:
try:
del obj[prop]
except:
logger.info("Property {0} was not used by this character".format(prop))
armat = self.sk_engine.get_armature()
logger.info("Properties deleted in {0} secs".format(time.time()-time1))
def recover_prop_values_from_obj_attr(self):
obj = self.get_object()
char_data = {"structural":{}, "metaproperties":{}, "materialproperties":{}}
for prop in self.character_data.keys():
if prop in obj.keys():
char_data["structural"][prop] = obj[prop]
for prop in self.character_metaproperties.keys():
if prop in obj.keys():
char_data["metaproperties"][prop] = obj[prop]
char_data["metaproperties"]["last_"+prop] = obj[prop]
for prop in self.character_material_properties.keys():
if prop in obj.keys():
char_data["materialproperties"][prop] = obj[prop]
self.load_character(char_data)
def sync_obj_props_to_character_data(self):
obj = self.get_object()
self.bodydata_realtime_activated = False
for prop, value in self.character_data.items():
setattr(obj, prop, value)
def sync_character_data_to_obj_props(self):
obj = self.get_object()
self.bodydata_realtime_activated = False
for prop in obj.keys():
if prop in self.character_data:
self.character_data[prop] = getattr(obj, prop)
def sync_internal_data_with_mesh(self):
self.morph_engine.init_final_form()
def sync_gui_according_measures(self):
obj = self.get_object()
measures = self.morph_engine.calculate_measures()
convert_to_inch = getattr(obj, "mblab_use_inch", False)
if convert_to_inch:
conversion_factor = 39.37001
else:
conversion_factor = 100
for measure_name, measure_val in measures.items():
if hasattr(obj, measure_name):
setattr(obj, measure_name, measure_val*conversion_factor)
def update_bendy_muscles(self):
armat = self.get_armature()
algorithms.update_bendy_bones(armat)
def update_character(self, category_name=None, mode="update_all"):
time1 = time.time()
obj = self.get_object()
self.clean_verts_to_process()
subdivision_value = self.get_subd_visibility()
self.set_subd_visibility(False)
if mode == "update_all":
update_directly_verts = False
update_geometry_all = True
update_geometry_selective = False
update_armature = True
update_normals = True
update_proxy = False
update_measures = True
sync_morphdata = False
sync_GUI = True
sync_GUI_metadata = True
sync_GUI_materials = True
if mode == "update_metadata":
update_directly_verts = False
update_geometry_all = True
update_geometry_selective = False
update_armature = True
update_normals = True
update_proxy = False
update_measures = True
sync_morphdata = False
sync_GUI = True
sync_GUI_metadata = False
sync_GUI_materials = False
if mode == "update_directly_verts":
update_directly_verts = True
update_geometry_all = False
update_geometry_selective = False
update_armature = True
update_normals = True
update_proxy = False
update_measures = True
sync_morphdata = False
sync_GUI = True
sync_GUI_metadata = False
sync_GUI_materials = False
if mode == "update_only_morphdata":
update_directly_verts = False
update_geometry_all = False
update_geometry_selective = False
update_armature = False
update_normals = False
update_proxy = False
update_measures = False
sync_morphdata = False
sync_GUI = False
sync_GUI_metadata = False
sync_GUI_materials = False
if mode == "update_realtime":
update_directly_verts = False
update_geometry_all = False
update_geometry_selective = True
update_armature = True
update_normals = False
update_proxy = False
update_measures = False
sync_morphdata = True
sync_GUI = False
sync_GUI_metadata = False
sync_GUI_materials = False
if update_directly_verts:
self.morph_engine.update(update_all_verts=True)
else:
if category_name:
category = self.categories[category_name]
modified_modifiers = []
for modifier in category.get_modifiers():
if modifier.is_changed(self.character_data):
modified_modifiers.append(modifier)
for modifier in modified_modifiers:
if sync_morphdata:
modifier.sync_modifier_data_to_obj_prop(self.character_data)
self.combine_morphings(modifier)
else:
for category in self.get_categories():
for modifier in category.get_modifiers():
self.combine_morphings(modifier, add_vertices_to_update=True)
if update_geometry_all:
self.morph_engine.update(update_all_verts=True)
if update_geometry_selective:
self.morph_engine.update(update_all_verts=False)
if sync_GUI:
self.sync_obj_props_to_character_data()
if sync_GUI_materials:
self.sync_obj_props_to_character_materials()
self.update_materials()
if sync_GUI_metadata:
self.sync_obj_props_to_character_metadata()
if update_measures:
self.sync_gui_according_measures()
if update_armature:
self.sk_engine.fit_joints()
# BUG - causes error in console
#if update_normals:
# obj.data.normal_update()
#if update_proxy:
# self.fit_proxy()
self.set_subd_visibility(subdivision_value)
logger.error("Character updated in {0} secs".format(time.time()-time1))
def generate_character(self, random_value, prv_face, prv_body, prv_mass, prv_tone, prv_height, prv_phenotype, set_tone_and_mass, body_mass, body_tone, prv_fantasy):
logger.info("Generating character...")
all_props = [x for x in self.character_data.keys()]
props_to_process = all_props.copy()
face_keys = ["Eye", "Eyelid", "Nose", "Mouth", "Ear", "Head", "Forehead", "Cheek", "Jaw"]
body_keys = ["Armpit", "Elbows", "Chest", "Body", "Arms", "Feet", "Wrists", "Waist", "Torso", "Stomach", "Shoulders", "Pelvis", "Neck", "Legs", "Hands"]
height_keys = ["Length", "Body_Size"]
mass_keys = ["Mass"]
tone_keys = ["Tone"]
expression_keys = ["Expressions"]
for prop in all_props:
remove_it = False
for k in expression_keys:
if k in prop:
remove_it = True
break
if prv_face:
for k in face_keys:
if k in prop:
remove_it = True
break
if prv_fantasy:
if "Fantasy" in prop:
remove_it = True
if prv_body:
for k in body_keys:
if k in prop:
remove_it = True
break
if prv_mass:
for k in mass_keys:
if k in prop:
remove_it = True
break
if prv_tone:
for k in tone_keys:
if k in prop:
remove_it = True
break
if prv_height:
for k in height_keys:
if k in prop:
remove_it = True
break
if remove_it:
if prop in props_to_process:
props_to_process.remove(prop)
for prop in props_to_process:
new_val = algorithms.generate_parameter(
self.character_data[prop],
random_value,
prv_phenotype)
if set_tone_and_mass:
if "Mass" in prop:
new_val = body_mass
if "Tone" in prop:
new_val = body_tone
self.character_data[prop] = new_val
self.update_character(mode="update_all")
def calculate_transformation(self, tr_type):
obj = self.get_object()
# TODO use getattr directly with dictionary
if tr_type == "AGE":
current_tr_factor = obj.character_age
previous_tr_factor = self.character_metaproperties["last_character_age"]
transformation_id = "age_data"
if tr_type == "FAT":
current_tr_factor = obj.character_mass
previous_tr_factor = self.character_metaproperties["last_character_mass"]
transformation_id = "fat_data"
if tr_type == "MUSCLE":
current_tr_factor = obj.character_tone
previous_tr_factor = self.character_metaproperties["last_character_tone"]
transformation_id = "muscle_data"
if current_tr_factor >= 0:
transformation_2 = current_tr_factor
transformation_1 = 0
else:
transformation_2 = 0
transformation_1 = -current_tr_factor
if previous_tr_factor >= 0:
last_transformation_2 = previous_tr_factor
last_transformation_1 = 0
else:
last_transformation_2 = 0
last_transformation_1 = -previous_tr_factor
if transformation_id in self.transformations_data:
tr_data = self.transformations_data[transformation_id]
for prop in self.character_data:
for tr_parameter in tr_data:
if tr_parameter[0] in prop:
linear_factor = tr_parameter[1]*transformation_1 + tr_parameter[2]*transformation_2 - tr_parameter[1]*last_transformation_1 - tr_parameter[2]*last_transformation_2
self.character_data[prop] = self.character_data[prop] + linear_factor
if tr_type == "AGE":
self.character_metaproperties['character_age'] = current_tr_factor
self.character_metaproperties['last_character_age'] = current_tr_factor
if tr_type == "FAT":
self.character_metaproperties['character_mass'] = current_tr_factor
self.character_metaproperties['last_character_mass'] = current_tr_factor
if tr_type == "MUSCLE":
self.character_metaproperties['character_tone'] = current_tr_factor
self.character_metaproperties['last_character_tone'] = current_tr_factor
self.update_character(mode="update_metadata")
else:
logger.warning("{0} data not present".format(transformation_id))
def init_delta_measures(self):
obj = self.get_object()