forked from soupday/CCiC-Blender-Pipeline-Plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1953 lines (1525 loc) · 78.5 KB
/
main.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
# Copyright (C) 2021 Victor Soupday
# This file is part of CC4-Blender-Tools-Plugin <https://github.com/soupday/CC4-Blender-Tools-Plugin>
#
# CC4-Blender-Tools-Plugin 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.
#
# CC4-Blender-Tools-Plugin 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 CC4-Blender-Tools-Plugin. If not, see <https://www.gnu.org/licenses/>.
import RLPy
import json
import os
import time
import shutil
import random
import PySide2
from PySide2 import *
from shiboken2 import wrapInstance
from enum import IntEnum
VERSION = "1.1.3"
rl_plugin_info = {"ap": "CC4", "ap_version": "4.0"}
class TextureChannel(IntEnum):
METALLIC = 0
DIFFUSE = 1
SPECULAR = 2
SHININESS = 3
GLOW = 4
DISPLACEMENT = 5
OPACITY = 6
DIFFUSE_BLEND = 7
BUMP = 8
REFLECTION = 9
REFRACTION = 10
CUBE = 11
AMBIENT = 12
NORMAL = 13
VECTOR_DISPLACEMENT = 14
SHADER_MAPS = { # { "Json_shader_name" : "CC3_shader_name", }
"Tra": "Traditional",
"Pbr": "PBR",
"RLEyeTearline": "Digital_Human Tear Line",
"RLHair": "Digital_Human Hair",
"RLTeethGum": "Digital_Human Teeth Gums",
"RLEye": "Digital_Human Eye",
"RLHead": "Digital_Human Head",
"RLSkin": "Digital_Human Skin",
"RLEyeOcclusion": "Digital_Human Eye Occlusion",
"RLTongue": "Digital_Human Tongue",
"RLSSS": "SSS",
}
TEXTURE_MAPS = { # { "json_channel_name": [RL_Texture_Channel, is_Substance_Painter_Channel?, substance_channel_postfix], }
"Metallic": [RLPy.EMaterialTextureChannel_Metallic, True, "metallic"],
"Base Color": [RLPy.EMaterialTextureChannel_Diffuse, True, "diffuse"],
"Specular": [RLPy.EMaterialTextureChannel_Specular, True, "specular"],
"Roughness": [RLPy.EMaterialTextureChannel_Shininess, True, "roughness"],
"Glow": [RLPy.EMaterialTextureChannel_Glow, True, "glow"],
"Displacement": [RLPy.EMaterialTextureChannel_Displacement, True, "displacement"],
"Opacity": [RLPy.EMaterialTextureChannel_Opacity, True, "opacity"],
"Blend": [RLPy.EMaterialTextureChannel_DiffuseBlend, False, ""],
"Reflection": [RLPy.EMaterialTextureChannel_Reflection, False, ""],
"Refraction": [RLPy.EMaterialTextureChannel_Refraction, False, ""],
"Cube": [RLPy.EMaterialTextureChannel_Cube, False, ""],
"AO": [RLPy.EMaterialTextureChannel_AmbientOcclusion, True, "ao"],
"Bump": [RLPy.EMaterialTextureChannel_Bump, True, "bump"],
"Normal": [RLPy.EMaterialTextureChannel_Normal, True, "normal"],
}
AVATAR_TYPES = {
RLPy.EAvatarType__None: "None",
RLPy.EAvatarType_Standard: "Standard",
RLPy.EAvatarType_NonHuman: "NonHuman",
RLPy.EAvatarType_NonStandard: "NonStandard",
RLPy.EAvatarType_StandardSeries: "StandardSeries",
RLPy.EAvatarType_All: "All",
}
FACIAL_PROFILES = {
RLPy.EFacialProfile__None: "None",
RLPy.EFacialProfile_CC4Extended: "CC4Extended",
RLPy.EFacialProfile_CC4Standard: "CC4Standard",
RLPy.EFacialProfile_Traditional: "Traditional",
}
NUM_SUBSTANCE_MAPS = 10
PLUGIN_MENU = None
MENU_IMPORT = None
MENU_EXPORT = None
FBX_IMPORTER = None
FBX_EXPORTER = None
def initialize_plugin():
global PLUGIN_MENU
global MENU_IMPORT
global MENU_EXPORT
# Add menu
PLUGIN_MENU = wrapInstance(int(RLPy.RUi.AddMenu("Blender Pipeline", RLPy.EMenu_Plugins)), PySide2.QtWidgets.QMenu)
MENU_EXPORT = PLUGIN_MENU.addAction("Export Character to Blender")
MENU_EXPORT.triggered.connect(menu_export)
PLUGIN_MENU.addSeparator()
MENU_IMPORT = PLUGIN_MENU.addAction("Import Character from Blender")
MENU_IMPORT.triggered.connect(menu_import)
def menu_import():
global FBX_IMPORTER
FBX_IMPORTER = None
file_path = RLPy.RUi.OpenFileDialog("Fbx Files(*.fbx)")
if file_path and file_path != "":
FBX_IMPORTER = Importer(file_path)
def menu_export():
global FBX_EXPORTER
FBX_EXPORTER = None
avatar_list = RLPy.RScene.GetAvatars()
if len(avatar_list) > 0:
FBX_EXPORTER = Exporter()
def clean_up_globals():
global FBX_IMPORTER
global FBX_EXPORTER
FBX_IMPORTER = None
FBX_EXPORTER = None
def do_events():
PySide2.QtWidgets.QApplication.processEvents()
def log(message):
print(message)
do_events()
#
# Class: Importer
#
class Importer:
path = "C:/folder/dummy.fbx"
folder = "C:/folder"
file = "dummy.fbx"
key = "C:/folder/dummy.fbxkey"
name = "dummy"
json_path = "C:/folder/dummy.json"
hik_path = "C:/folder/dummy.3dxProfile"
profile_path = "C:/folder/dummy.ccFacialProfile"
json_data = None
avatar = None
window_options = None
window_progress = None
progress_1 = None
progress_2 = None
check_mesh = None
check_textures = None
check_parameters = None
check_import_hik = None
check_import_profile = None
check_import_expressions = None
num_pbr = 0
num_custom = 0
count_pbr = 0
count_custom = 0
mat_duplicates = {}
substance_import_success = False
option_mesh = True
option_textures = True
option_parameters = True
option_import_hik = False
option_import_profile = False
option_import_expressions = None
character_type = None
generation = None
def __init__(self, file_path):
log("================================================================")
log("New character import, Fbx: " + file_path)
self.path = file_path
self.file = os.path.basename(self.path)
self.folder = os.path.dirname(self.path)
self.name = os.path.splitext(self.file)[0]
self.key = os.path.join(self.folder, self.name + ".fbxkey")
self.json_path = os.path.join(self.folder, self.name + ".json")
self.json_data = read_json(self.json_path)
self.hik_path = os.path.join(self.folder, self.name + ".3dxProfile")
self.profile_path = os.path.join(self.folder, self.name + ".ccFacialProfile")
self.generation = get_character_generation_json(self.json_data, self.name, self.name)
self.character_type = "STANDARD"
if self.generation == "Humanoid" or self.generation == "" or self.generation == "Unknown":
self.character_type = "HUMANOID"
elif self.generation == "Creature":
self.character_type = "CREATURE"
elif self.generation == "Prop":
self.character_type = "PROP"
error = False
if not self.json_data:
message_box("There is no JSON data with this character!\n\nThe plugin will be unable to set-up any materials.\n\nPlease use the standard character importer instead (File Menu > Import).")
error = True
if self.character_type == "STANDARD":
if not os.path.exists(self.key):
message_box("There is no Fbx Key with this character!\n\nCC3/4 Standard characters cannot be imported back into Character Creator without a corresponding Fbx Key.\nThe Fbx Key will be generated when the character is exported as Mesh only, or in Calibration Pose, and with no hidden faces.")
error = True
self.option_mesh = True
self.option_textures = True
self.option_parameters = True
self.option_import_hik = False
self.option_import_profile = False
self.option_import_expressions = False
if self.json_data:
if self.name in self.json_data.keys():
if "HIK" in self.json_data[self.name].keys():
if "Profile_Path" in self.json_data[self.name]["HIK"].keys():
self.hik_path = os.path.join(self.folder, self.json_data[self.name]["HIK"]["Profile_Path"])
self.option_import_hik = True
if "Facial_Profile" in self.json_data[self.name].keys():
if "Profile_Path" in self.json_data[self.name]["Facial_Profile"].keys():
self.profile_path = os.path.join(self.folder, self.json_data[self.name]["Facial_Profile"]["Profile_Path"])
self.option_import_profile = True
if "Categories" in self.json_data[self.name]["Facial_Profile"].keys():
self.option_import_expressions = False
if not error:
self.create_options_window()
def fetch_options(self):
if self.check_mesh: self.option_mesh = self.check_mesh.isChecked()
if self.check_textures: self.option_textures = self.check_textures.isChecked()
if self.check_parameters: self.option_parameters = self.check_parameters.isChecked()
if self.check_import_expressions: self.option_import_expressions = self.check_import_expressions.isChecked()
if self.check_import_hik: self.option_import_hik = self.check_import_hik.isChecked()
if self.check_import_profile: self.option_import_profile = self.check_import_profile.isChecked()
def close_options_window(self):
if self.window_options:
self.window_options.Close()
self.window_options = None
self.check_mesh = None
self.check_textures = None
self.check_parameters = None
self.check_import_expressions = None
self.check_import_hik = None
self.check_import_profile = None
def close_progress_window(self):
self.close_options_window()
if self.window_progress:
self.window_progress.Close()
self.path = "C:/folder/dummy.fbx"
self.folder = "C:/folder"
self.file = "dummy.fbx"
self.name = "dummy"
self.json_path = "C:/folder/dummy.json"
self.json_data = None
self.avatar = None
self.window_progress = None
self.progress_1 = None
self.progress_2 = None
self.num_pbr = 0
self.num_custom = 0
self.count_pbr = 0
self.count_custom = 0
self.mat_duplicates = {}
self.substance_import_success = False
clean_up_globals()
def create_options_window(self):
self.window_options = RLPy.RUi.CreateRDockWidget()
self.window_options.SetWindowTitle(f"Blender Auto-setup Character Import ({VERSION}) - Options")
dock = wrapInstance(int(self.window_options.GetWindow()), PySide2.QtWidgets.QDockWidget)
dock.setFixedWidth(500)
widget = PySide2.QtWidgets.QWidget()
dock.setWidget(widget)
layout = PySide2.QtWidgets.QVBoxLayout()
widget.setLayout(layout)
label_1 = PySide2.QtWidgets.QLabel()
label_1.setText(f"Character Name: {self.name}")
label_1.setStyleSheet("color: white; font: bold")
layout.addWidget(label_1)
label_2 = PySide2.QtWidgets.QLabel()
label_2.setText(f"Character Path: {self.path}")
label_2.setStyleSheet("color: white; font: bold")
layout.addWidget(label_2)
label_3 = PySide2.QtWidgets.QLabel()
label_3.setText(f"Type: {self.character_type}")
label_3.setStyleSheet("color: white; font: bold")
layout.addWidget(label_3)
layout.addSpacing(10)
row = PySide2.QtWidgets.QHBoxLayout()
layout.addLayout(row)
col_1 = PySide2.QtWidgets.QVBoxLayout()
col_2 = PySide2.QtWidgets.QVBoxLayout()
row.addLayout(col_1)
row.addLayout(col_2)
self.check_mesh = PySide2.QtWidgets.QCheckBox()
self.check_mesh.setText("Import Mesh")
self.check_mesh.setChecked(self.option_mesh)
col_1.addWidget(self.check_mesh)
self.check_textures = PySide2.QtWidgets.QCheckBox()
self.check_textures.setText("Import Textures")
self.check_textures.setChecked(self.option_textures)
col_1.addWidget(self.check_textures)
self.check_parameters = PySide2.QtWidgets.QCheckBox()
self.check_parameters.setText("Import Parameters")
self.check_parameters.setChecked(self.option_parameters)
col_1.addWidget(self.check_parameters)
self.check_import_hik = PySide2.QtWidgets.QCheckBox()
self.check_import_hik.setText("Import HIK Profile")
self.check_import_hik.setChecked(self.option_import_hik)
col_2.addWidget(self.check_import_hik)
self.check_import_profile = PySide2.QtWidgets.QCheckBox()
self.check_import_profile.setText("Import Facial Profile")
self.check_import_profile.setChecked(self.option_import_profile)
col_2.addWidget(self.check_import_profile)
self.check_import_expressions = PySide2.QtWidgets.QCheckBox()
self.check_import_expressions.setText("Import Facial Expressions")
self.check_import_expressions.setChecked(self.option_import_expressions)
col_2.addWidget(self.check_import_expressions)
layout.addSpacing(10)
start_button = PySide2.QtWidgets.QPushButton("Import Character", minimumHeight=32)
start_button.clicked.connect(self.import_fbx)
layout.addWidget(start_button)
cancel_button = PySide2.QtWidgets.QPushButton("Cancel", minimumHeight=32)
cancel_button.clicked.connect(self.close_progress_window)
layout.addWidget(cancel_button)
#self.window_options.RegisterEventCallback(self.dialog_callback)
self.window_options.Show()
def create_progress_window(self):
self.window_progress = RLPy.RUi.CreateRDockWidget()
self.window_progress.SetWindowTitle("Blender Auto-setup Character Import - Progress")
dock = wrapInstance(int(self.window_progress.GetWindow()), PySide2.QtWidgets.QDockWidget)
dock.setFixedWidth(500)
widget = PySide2.QtWidgets.QWidget()
dock.setWidget(widget)
layout = PySide2.QtWidgets.QVBoxLayout()
widget.setLayout(layout)
label_1 = PySide2.QtWidgets.QLabel()
label_1.setText(f"Character Name: {self.name}")
layout.addWidget(label_1)
label_2 = PySide2.QtWidgets.QLabel()
label_2.setText(f"Character Path: {self.path}")
layout.addWidget(label_2)
layout.addSpacing(10)
label_progress_1 = PySide2.QtWidgets.QLabel()
label_progress_1.setText("First Pass: (Pbr Textures)")
layout.addWidget(label_progress_1)
self.progress_1 = PySide2.QtWidgets.QProgressBar()
self.progress_1.setRange(0, 100)
self.progress_1.setValue(0)
self.progress_1.setFormat("Calculating...")
layout.addWidget(self.progress_1)
layout.addSpacing(10)
label_progress_2 = PySide2.QtWidgets.QLabel()
label_progress_2.setText("Second Pass: (Custom Shader Textures and Parameters)")
layout.addWidget(label_progress_2)
self.progress_2 = PySide2.QtWidgets.QProgressBar()
self.progress_2.setRange(0, 100)
self.progress_2.setValue(0)
self.progress_2.setFormat("Waiting...")
layout.addWidget(self.progress_2)
#self.window_progress.RegisterEventCallback(self.dialog_callback)
self.window_progress.Show()
def update_pbr_progress(self, stage, text = ""):
if stage == 0:
self.progress_1.setValue(0)
self.progress_1.setFormat("Calculating...")
if stage == 1:
self.progress_1.setFormat("Cleaning up temp files...")
elif stage == 2:
self.count_pbr += 1
self.progress_1.setValue(self.count_pbr)
self.progress_1.setFormat(f"Collecting textures ({text}) {round(50.0 * self.count_pbr / self.num_pbr)}%")
elif stage == 3:
self.progress_1.setValue(self.count_pbr)
self.progress_1.setFormat("Loading all PBR textures... (Please Wait)")
elif stage > 3:
self.progress_1.setValue(self.num_pbr * 2)
self.progress_1.setFormat("Done PBR Textures!")
do_events()
def update_custom_progress(self, stage, text = ""):
if stage == 0:
self.progress_2.setValue(0)
self.progress_2.setFormat("Waiting...")
elif stage == 1:
self.count_custom += 1
self.progress_2.setValue(self.count_custom)
self.progress_2.setFormat(f"Processing ({text}): {round(50.0 * self.count_custom/self.num_custom)}%")
elif stage > 1:
self.progress_2.setValue(self.num_custom)
self.progress_2.setFormat("Done Custom Shader Textures and Settings!")
do_events()
def import_fbx(self):
"""Import the character into CC3 and read in the json data.
"""
self.fetch_options()
self.close_options_window()
if self.json_data:
# importing changes the selection so store it first.
selected_objects = RLPy.RScene.GetSelectedObjects()
objects = []
if self.option_mesh:
args = RLPy.EImportFbxOption__None
if self.character_type == "STANDARD":
args = args | RLPy.EImportFbxOption_StandardHumanCharacter
elif self.character_type == "HUMANOID":
args = args | RLPy.EImportFbxOption_Humanoid
elif self.character_type == "CREATURE":
args = args | RLPy.EImportFbxOption_Creature
elif self.character_type == "PROP":
args = args | RLPy.EImportFbxOption_Prop
# to determine which prop(s) was imported, store a list of all current props
if self.character_type == "PROP":
stored_props = RLPy.RScene.GetProps()
RLPy.RFileIO.LoadFbxFile(self.path, args)
# any prop not in the stored list is newly imported.
if self.character_type == "PROP":
all_props = RLPy.RScene.GetProps()
for prop in all_props:
if prop not in stored_props:
objects.append(prop)
else:
if self.character_type == "PROP":
objects = selected_objects
# if not importing a prop, use the current avatar
if self.character_type != "PROP":
avatars = RLPy.RScene.GetAvatars(RLPy.EAvatarType_All)
objects = [avatars[0]]
if len(objects) > 0:
for obj in objects:
self.avatar = obj
self.rebuild_materials()
RLPy.RScene.SelectObject(obj)
def rebuild_materials(self):
"""Material reconstruction process.
"""
avatar = self.avatar
start_timer()
if self.option_textures or self.option_parameters:
self.create_progress_window()
material_component = avatar.GetMaterialComponent()
mesh_names = avatar.GetMeshNames()
obj_name_map = None
if not self.option_mesh:
obj_name_map = get_json_mesh_name_map(avatar)
json_data = self.json_data
char_json = get_character_json(json_data, self.name, self.name)
log("Rebuilding character materials and texures:")
self.count(char_json, material_component, mesh_names, obj_name_map)
# only need to import all the textures when importing a new mesh
if self.character_type != "PROP":
if self.option_textures:
self.import_substance_textures(char_json, material_component, mesh_names, obj_name_map)
self.import_custom_textures(char_json, material_component, mesh_names, obj_name_map)
self.import_physics(char_json, obj_name_map)
if self.character_type == "HUMANOID":
self.import_hik_profile()
if self.character_type == "STANDARD" or self.character_type == "HUMANOID":
self.window_progress.Close()
self.import_facial_profile()
time.sleep(1)
self.close_progress_window()
RLPy.RGlobal.ObjectModified(avatar, RLPy.EObjectModifiedType_Material)
log_timer("Import complete! Materials applied in: ")
def import_custom_textures(self, char_json, material_component, mesh_names, obj_name_map):
"""Process all mesh objects and materials in the avatar, apply material settings,
texture settings, custom shader textures and parameters from the json data.
"""
global TEXTURE_MAPS
key_zero = RLPy.RKey()
key_zero.SetTime(RLPy.RTime.FromValue(0))
log(" - Beginning custom shader import...")
for mesh_name in mesh_names:
mesh_name = fix_blender_name(mesh_name, self.option_mesh)
obj_json = get_object_json(char_json, mesh_name, obj_name_map)
if obj_json:
mat_names = material_component.GetMaterialNames(mesh_name)
for mat_name in mat_names:
mat_name = fix_blender_name(mat_name, self.option_mesh)
mat_json = get_material_json(obj_json, mat_name, obj_name_map)
if mat_json:
pid = mesh_name + " / " + mat_name
shader = material_component.GetShader(mesh_name, mat_name)
if self.option_parameters:
# Material parameters
diffuse_value = get_material_var(mat_json, "Diffuse Color")
diffuse_color = RLPy.RRgb(diffuse_value[0], diffuse_value[1], diffuse_value[2])
ambient_value = get_material_var(mat_json, "Ambient Color")
ambient_color = RLPy.RRgb(ambient_value[0], ambient_value[1], ambient_value[2])
specular_value = get_material_var(mat_json, "Specular Color")
specular_color = RLPy.RRgb(specular_value[0], specular_value[1], specular_value[2])
glow_strength = mat_json["Self Illumination"] * 100.0
opacity_strength = mat_json["Opacity"] * 100.0
material_component.AddDiffuseKey(key_zero, mesh_name, mat_name, diffuse_color)
material_component.AddAmbientKey(key_zero, mesh_name, mat_name, ambient_color)
material_component.AddSpecularKey(key_zero, mesh_name, mat_name, 0.0)
material_component.AddSelfIlluminationKey(key_zero, mesh_name, mat_name, glow_strength)
material_component.AddOpacityKey(key_zero, mesh_name, mat_name, opacity_strength)
# Custom shader parameters
shader_params = material_component.GetShaderParameterNames(mesh_name, mat_name)
for param in shader_params:
json_value = None
if param.startswith("SSS "):
json_value = get_sss_var(mat_json, param[4:])
else:
json_value = get_shader_var(mat_json, param)
if json_value is not None:
material_component.SetShaderParameter(mesh_name, mat_name, param, json_value)
self.update_custom_progress(1, pid)
if self.option_textures and "Textures" in mat_json.keys():
# Custom shader textures
shader_textures = material_component.GetShaderTextureNames(mesh_name, mat_name)
if shader_textures:
for shader_texture in shader_textures:
tex_info = get_shader_texture_info(mat_json, shader_texture)
tex_path = convert_texture_path(tex_info, "Texture Path", self.folder)
if tex_path and os.path.exists(tex_path) and os.path.isfile(tex_path):
material_component.LoadShaderTexture(mesh_name, mat_name, shader_texture, tex_path)
self.update_custom_progress(1, pid)
# Pbr Textures
png_base_color = False
has_opacity_map = "Opacity" in mat_json["Textures"].keys()
for tex_id in TEXTURE_MAPS.keys():
tex_channel = TEXTURE_MAPS[tex_id][0]
is_substance = TEXTURE_MAPS[tex_id][1]
load_texture = not is_substance
# fully process textures for materials with duplicates,
# as the substance texture import can't really deal with them.
if self.mat_duplicates[mat_name]:
load_texture = True
# or if the substance texture import method failed, import all textures individually
if not self.substance_import_success:
load_texture = True
# prop objects don't work with substance texture import currently
if self.character_type == "PROP":
load_texture = True
tex_info = get_pbr_texture_info(mat_json, tex_id)
tex_path = convert_texture_path(tex_info, "Texture Path", self.folder)
if tex_path:
# PNG diffuse maps with alpha channels don't fill in opacity correctly with substance import method
if tex_id == "Base Color" and not has_opacity_map and os.path.splitext(tex_path)[-1].lower() == ".png":
png_base_color = True
load_texture = True
elif tex_id == "Opacity" and png_base_color:
load_texture = True
strength = float(tex_info["Strength"]) / 100.0
offset = tex_info["Offset"]
offset_vector = RLPy.RVector2(float(offset[0]), float(offset[1]))
tiling = tex_info["Tiling"]
tiling_vector = RLPy.RVector2(float(tiling[0]), float(tiling[1]))
if offset_vector.x != 0.0 or offset_vector.y != 0.0:
if tiling_vector.x != 1.0 or tiling_vector.y != 1.0:
load_texture = True
# Note: rotation doesn't seem to be exported to the Json?
rotation = float(0.0)
if "Rotation" in tex_info.keys():
rotation = float(tex_info["Rotation"])
# set textures
if os.path.exists(tex_path) and os.path.isfile(tex_path):
if load_texture:
material_component.LoadImageToTexture(mesh_name, mat_name, tex_channel, tex_path)
# this function is broken, it does not take negative tiling values
# also UV settings are disabled for Accessories...
material_component.AddUvDataKey(key_zero, mesh_name, mat_name, tex_channel, offset_vector, tiling_vector, rotation)
material_component.AddTextureWeightKey(key_zero, mesh_name, mat_name, tex_channel, strength)
#twl = material_component.GetTextureWeights(mesh_name, mat_name)
if tex_id == "Displacement":
level = 0
multiplier = 0
threshold = 50
if "Tessellation Level" in tex_info:
level = tex_info["Tessellation Level"]
if "Multiplier" in tex_info:
multiplier = tex_info["Multiplier"]
if "Gray-scale Base Value" in tex_info:
threshold = tex_info["Gray-scale Base Value"] * 100
material_component.SetAttributeValue(mesh_name, mat_name, "TessellationLevel", level)
material_component.SetAttributeValue(mesh_name, mat_name, "TessellationMultiplier", multiplier)
material_component.SetAttributeValue(mesh_name, mat_name, "TessellationThreshold", threshold)
self.update_custom_progress(1, pid)
self.update_custom_progress(2)
log(" - Custom shader import complete!")
def import_substance_textures(self, char_json, material_component, mesh_names, obj_name_map):
"""Cache all PBR textures in a temporary location to load in all at once with:
RLPy.RFileIO.LoadSubstancePainterTextures()
This is *much* faster than loading these textures individually,
but requires a particular directory and file naming structure.
"""
global TEXTURE_MAPS, NUM_SUBSTANCE_MAPS
log(" - Beginning substance texture import...")
self.update_pbr_progress(1)
self.substance_import_success = False
# create temp folder for substance import (use the temporary files location from the RGlobal.GetPath)
res = RLPy.RGlobal.GetPath(RLPy.EPathType_Temp, "")
temp_path = res[1]
# safest not to write temporary files in random locations...
if not os.path.exists(temp_path):
log(" - Unable to determine temporary file location, skipping substance import!")
return
temp_folder = os.path.join(temp_path, "CC3_BTP_Temp_" + random_string(8))
log(" - Using temp folder: " + temp_folder)
# delete if exists
if os.path.exists(temp_folder):
shutil.rmtree(temp_folder)
# make a new temporary folder
if not os.path.exists(temp_folder):
os.mkdir(temp_folder)
for mesh_name in mesh_names:
mesh_name = fix_blender_name(mesh_name, self.option_mesh)
obj_json = get_object_json(char_json, mesh_name, obj_name_map)
if obj_json:
mat_names = material_component.GetMaterialNames(mesh_name)
if mesh_name.startswith("CC_Base_Body"):
# body is a special case, everything is stored in the first material name with incremental indicees
# create folder with first matertial name in each mesh
first_mat_in_mesh = mat_names[0]
mesh_folder = os.path.join(temp_folder, first_mat_in_mesh)
if not os.path.exists(mesh_folder):
os.mkdir(mesh_folder)
mat_index = 1001
for mat_name in mat_names:
mat_name = fix_blender_name(mat_name, self.option_mesh)
mat_json = get_material_json(obj_json, mat_name, obj_name_map)
if mat_json:
pid = mesh_name + " / " + mat_name
# for each texture channel that can be imported with the substance texture method:
for tex_id in TEXTURE_MAPS.keys():
is_substance = TEXTURE_MAPS[tex_id][1]
if is_substance:
tex_channel = TEXTURE_MAPS[tex_id][0]
substance_postfix = TEXTURE_MAPS[tex_id][2]
tex_info = get_pbr_texture_info(mat_json, tex_id)
tex_path = convert_texture_path(tex_info, "Texture Path", self.folder)
if tex_path:
tex_dir, tex_file = os.path.split(tex_path)
tex_name, tex_type = os.path.splitext(tex_file)
# copy valid texture files to the temporary texture cache
if tex_name and os.path.exists(tex_path) and os.path.isfile(tex_path):
substance_name = first_mat_in_mesh + "_" + str(mat_index) + "_" + substance_postfix + tex_type
substance_path = os.path.normpath(os.path.join(mesh_folder, substance_name))
shutil.copyfile("\\\\?\\" + tex_path, "\\\\?\\" + substance_path)
self.update_pbr_progress(2, pid)
mat_index += 1
else:
for mat_name in mat_names:
pid = mesh_name + " / " + mat_name
has_duplicates = False
if mat_name in self.mat_duplicates.keys() and self.mat_duplicates[mat_name]:
has_duplicates = True
# only process those materials here that don't have duplicates
# substance texture import doesn't deal with duplicates well...
if not has_duplicates:
mat_name = fix_blender_name(mat_name, self.option_mesh)
mat_json = get_material_json(obj_json, mat_name, obj_name_map)
if mat_json:
# create folder with the matertial name
mesh_folder = os.path.join(temp_folder, mat_name)
if not os.path.exists(mesh_folder):
os.mkdir(mesh_folder)
mat_index = 1001
# for each texture channel that can be imported with the substance texture method:
for tex_id in TEXTURE_MAPS.keys():
is_substance = TEXTURE_MAPS[tex_id][1]
if is_substance:
tex_channel = TEXTURE_MAPS[tex_id][0]
substance_postfix = TEXTURE_MAPS[tex_id][2]
tex_info = get_pbr_texture_info(mat_json, tex_id)
tex_path = convert_texture_path(tex_info, "Texture Path", self.folder)
if tex_path:
tex_dir, tex_file = os.path.split(tex_path)
tex_name, tex_type = os.path.splitext(tex_file)
# copy valid texture files to the temporary texture cache
if tex_name and os.path.exists(tex_path) and os.path.isfile(tex_path):
substance_name = mat_name + "_" + str(mat_index) + "_" + substance_postfix + tex_type
substance_path = os.path.normpath(os.path.join(mesh_folder, substance_name))
shutil.copyfile("\\\\?\\" + tex_path, "\\\\?\\" + substance_path)
self.update_pbr_progress(2, pid)
else:
self.count_pbr += (NUM_SUBSTANCE_MAPS - 1)
self.update_pbr_progress(2, pid)
self.update_pbr_progress(3)
avatar = self.avatar
# load all pbr textures in one go from the texture cache
RLPy.RFileIO.LoadSubstancePainterTextures(avatar, temp_folder)
self.substance_import_success = True
log (" - Substance texture import successful!")
log (" - Cleaning up temp folder: " + temp_folder)
# delete temp folder
if os.path.exists(temp_folder):
shutil.rmtree(temp_folder)
self.update_pbr_progress(4)
def count(self, char_json, material_component, mesh_names, obj_name_map):
"""Precalculate the number of materials, textures and parameters that need to be processed,
to initialise progress bars.
Also determine which materials may have duplicate names as these need to be treated differently.
"""
global TEXTURE_MAPS, NUM_SUBSTANCE_MAPS
num_materials = 0
num_params = 0
num_textures = 0
num_custom = 0
num_pbr = 0
self.mat_duplicates = {}
for mesh_name in mesh_names:
mesh_name = fix_blender_name(mesh_name, self.option_mesh)
obj_json = get_object_json(char_json, mesh_name, obj_name_map)
if obj_json:
mat_names = material_component.GetMaterialNames(mesh_name)
for mat_name in mat_names:
mat_name = fix_blender_name(mat_name, self.option_mesh)
mat_json = get_material_json(obj_json, mat_name, obj_name_map)
if mat_json:
# determine material duplicates
if mat_name in self.mat_duplicates.keys():
self.mat_duplicates[mat_name] = True
else:
self.mat_duplicates[mat_name] = False
# ensure the shader is correct:
imported_shader = material_component.GetShader(mesh_name, mat_name)
wanted_shader = SHADER_MAPS[mat_json["Material Type"]]
if "Custom Shader" in mat_json.keys():
wanted_shader = SHADER_MAPS[mat_json["Custom Shader"]["Shader Name"]]
if imported_shader != wanted_shader:
#material_component.SetShader(mesh_name, mat_name, "PBR")
material_component.SetShader(mesh_name, mat_name, wanted_shader)
# Calculate stats
num_pbr += NUM_SUBSTANCE_MAPS
num_materials += 1
# Custom shader parameters
if self.option_parameters:
shader_params = material_component.GetShaderParameterNames(mesh_name, mat_name)
num_params += len(shader_params)
# Custom shader textures
if self.option_textures:
shader_textures = material_component.GetShaderTextureNames(mesh_name, mat_name)
num_textures += len(shader_textures)
# Pbr Textures
num_textures += len(TEXTURE_MAPS)
self.num_pbr = num_pbr
self.num_custom = num_params + num_textures
self.progress_1.setRange(0, self.num_pbr * 2)
self.progress_2.setRange(0, self.num_custom)
self.count_pbr = 0
self.count_custom = 0
self.update_pbr_progress(0)
self.update_custom_progress(0)
do_events()
def import_physics(self, char_json, obj_name_map):
avatars = RLPy.RScene.GetAvatars()
if avatars is None or len(avatars) == 0:
return
avatar = avatars[0]
done = []
physics_components = []
log(f"Import Physics")
# get physics components of all child objects
child_objects = RLPy.RScene.FindChildObjects(avatar, RLPy.EObjectType_Avatar)
for obj in child_objects:
obj_physics_component = obj.GetPhysicsComponent()
if obj_physics_component and obj_physics_component not in physics_components:
physics_components.append(obj_physics_component)
# get physics components of all accessory_objects
accessories = avatar.GetAccessories()
for obj in accessories:
obj_physics_component = obj.GetPhysicsComponent()
if obj_physics_component and obj_physics_component not in physics_components:
physics_components.append(obj_physics_component)
# get physics components of all hair meshes
hairs = avatar.GetHairs()
for hair in hairs:
hair_physics_component = hair.GetPhysicsComponent()
if hair_physics_component and hair_physics_component not in physics_components:
physics_components.append(hair_physics_component)
# process each physics component and reconstruct from the JSON data
for physics_component in physics_components:
mesh_names = physics_component.GetSoftPhysicsMeshNameList()
for mesh_name in mesh_names:
if mesh_name not in done:
done.append(mesh_name)
physics_object_json = get_physics_object_json(char_json, mesh_name, obj_name_map)
if physics_object_json:
material_names = physics_component.GetSoftPhysicsMaterialNameList(mesh_name)
for mat_name in material_names:
physics_material_json = get_physics_material_json(physics_object_json, mat_name, obj_name_map)
if physics_material_json:
log(f"Object: {obj.GetName()}, Mesh: {mesh_name}, Material: {mat_name}")
mass = None
for json_param_name in physics_material_json.keys():
phys_param_name = json_param_name.replace(' ', '').replace('_', '')
param_value = get_physics_var(physics_material_json, json_param_name)
#log(f" Param: {phys_param_name} = {param_value}")
if json_param_name == "Activate Physics": # activate physics
physics_component.SetActivatePhysicsEnable(param_value)
elif json_param_name == "Use Global Gravity": # global gravity
physics_component.SetObjectGravityEnable(mesh_name, mat_name, param_value)
elif json_param_name == "Weight Map Path": # weight map
tex_path = convert_texture_path(physics_material_json, json_param_name, self.folder)
if tex_path:
physics_component.SetPhysicsSoftColthWeightMap(mesh_name, mat_name, tex_path)
elif json_param_name == "Soft Vs Rigid Collision" or json_param_name == "Self Collision":
physics_component.SetSoftPhysXCollisionEnable(mesh_name, mat_name, phys_param_name, param_value)
elif json_param_name == "Soft Vs Rigid Collision_Margin" or json_param_name == "Self Collision Margin":