-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlib_gzrs2.py
2337 lines (1744 loc) · 84.3 KB
/
lib_gzrs2.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
import bpy, os, math, ctypes, shutil
from ctypes import *
from contextlib import redirect_stdout
from mathutils import Vector, Matrix, Euler
from .constants_gzrs2 import *
from .classes_gzrs2 import *
from .io_gzrs2 import *
def getOrNone(list, i):
try: return list[i]
except: return None
def indexOrNone(list, i):
try: return list.index(i)
except: return None
def dataOrFirst(list, i, o):
try: return list[i][o]
except: return list[0][o]
def enumTagToIndex(self, tag, items):
for i, item in enumerate(items):
if item[0] == tag:
return i
print(f"GZRS2: Failed to get index for enum tag: { tag }")
return 0
def enumIndexToTag(index, items):
return items[index][0]
def ensureWorld(context):
scene = context.scene
world = scene.world
if world is None:
if len(bpy.data.worlds) > 0: bpy.data.worlds[0]
else: bpy.data.worlds.new()
scene.world = world
return world
def vecArrayMinMax(vectors, size):
minLen2 = float('inf')
maxLen2 = float('-inf')
minVector = tuple(minLen2 for _ in range(size))
maxVector = tuple(maxLen2 for _ in range(size))
for vector in vectors:
len2 = sum(vector[s] ** 2 for s in range(size))
if len2 < minLen2:
minLen2 = len2
minVector = vector
if len2 > maxLen2:
maxLen2 = len2
maxVector = vector
return *minVector, *maxVector
def pathExists(path):
if os.path.exists(path): return path
elif path == '': return False
elif os.name != 'nt':
path = os.path.normpath(path.lower())
targets = iter(path[1:].split(os.sep))
current = os.sep + next(targets)
target = next(targets)
while target is not None:
_, dirnames, filenames = next(os.walk(current))
if os.path.splitext(target)[1] == '':
found = False
for dirname in dirnames:
if dirname.lower() == target:
current = os.path.join(current, dirname)
found = True
break
if found: target = next(targets)
else: return False
else:
for filename in filenames:
if filename.lower() == target:
current = os.path.join(current, filename)
return current
return False
return current
def isValidTexBase(texBase):
if texBase.endswith(os.sep): return False
elif os.path.splitext(texBase)[1] == '': return False
return True
def texMatchDownward(root, texBase, ddsBase):
matchBases = [texBase.lower(), ddsBase.lower()]
for dirpath, _, filenames in os.walk(root):
for filename in filenames:
if filename.lower() in matchBases:
return os.path.join(dirpath, filename)
def matchRSDataDirectory(self, dirpath, dirbase, isRS3, state):
if dirpath == '' or not os.path.exists(dirpath) or not os.path.isdir(dirpath):
return False
if dirbase == '':
return False
_, dirnames, _ = next(os.walk(dirpath))
for token in RS3_VALID_DATA_SUBDIRS if isRS3 else RS2_VALID_DATA_SUBDIRS:
if token.lower() == dirbase.lower():
state.rs2DataDir = os.path.dirname(dirpath)
return True
for dirname in dirnames:
if token.lower() == dirname.lower():
state.rs2DataDir = dirpath
return True
return False
def ensureRS3DataDict(self, state):
if len(state.rs3DataDict) > 0: return
for dirpath, _, filenames in os.walk(state.rs3DataDir):
for filename in filenames:
splitname = filename.split(os.extsep)
if splitname[-1].lower() in RS3_DATA_DICT_EXTENSIONS:
resourcepath = pathExists(os.path.join(dirpath, filename))
if not resourcepath:
self.report({ 'ERROR' }, f"GZRS2: Resource found but pathExists() failed, potential case sensitivity issue: { filename }")
return
state.rs3DataDict[filename.lower()] = resourcepath
def ensureRS3DataDirectory(self, state):
if state.rs3DataDir: return
currentDir = state.directory
for _ in range(RES_UPWARD_SEARCH_LIMIT):
_, dirnames, _ = next(os.walk(currentDir))
for dirname in dirnames:
if dirname.lower() in RS3_VALID_DATA_SUBDIRS_LOWER:
state.rs3DataDir = os.path.join(currentDir, dirname)
break
currentDir = os.path.dirname(currentDir)
if not state.rs3DataDir:
self.report({ 'ERROR' }, f"GZRS2: Failed to find RS3 data directory!")
return
ensureRS3DataDict(self, state)
def textureSearch(self, texBase, texDir, isRS3, state):
if texBase == None:
self.report({ 'WARNING' }, f"GZRS2: Texture search attempted with no texture name: { texBase }")
return
if texBase == '':
self.report({ 'WARNING' }, f"GZRS2: Texture search attempted with an empty texture name: { texBase }")
return
if not isValidTexBase(texBase):
self.report({ 'WARNING' }, f"GZRS2: Texture search attempted with an invalid texture name: { texBase }")
return
ddsBase = f"{ texBase }{ os.extsep }dds".replace(os.extsep + 'dds' + os.extsep + 'dds', os.extsep + 'dds')
if isRS3:
ensureRS3DataDict(self, state)
result = state.rs3DataDict.get(texBase.lower())
if result: return result
result = state.rs3DataDict.get(ddsBase.lower())
if result: return result
self.report({ 'WARNING' }, f"GZRS2: Texture search failed, no entry in data dictionary: { texBase }")
if texDir != '':
# Check the local folder
result = pathExists(os.path.join(state.directory, texBase))
if result: return result
result = pathExists(os.path.join(state.directory, ddsBase))
if result: return result
# Check a specific sub-folder relative to the local one
result = pathExists(os.path.join(state.directory, texDir, texBase))
if result: return result
result = pathExists(os.path.join(state.directory, texDir, ddsBase))
if result: return result
if self.texSearchMode == 'PATH':
dataDir = state.rs3DataDir if isRS3 else state.rs2DataDir
# Check a specific sub-folder relative to the data folder
result = pathExists(os.path.join(dataDir, texDir, texBase))
if result: return result
result = pathExists(os.path.join(dataDir, texDir, ddsBase))
if result: return result
elif self.texSearchMode == 'BRUTE':
parentDir = os.path.dirname(state.directory)
targetname = texDir.split(os.sep)[0]
# This isn't too bad, it only checks directory names
for _ in range(TEX_UPWARD_SEARCH_LIMIT):
_, dirnames, _ = next(os.walk(parentDir))
for dirname in dirnames:
if dirname.lower() == targetname.lower():
# Check a specific sub-folder relative to the parent folder
result = pathExists(os.path.join(parentDir, texDir, texBase))
if result: return result
result = pathExists(os.path.join(parentDir, texDir, ddsBase))
if result: return result
parentDir = os.path.dirname(parentDir)
self.report({ 'WARNING' }, f"GZRS2: Texture search failed, no upward directory match: { texDir }, { texBase }")
else:
# Check the local folder and all sub-folders
result = texMatchDownward(state.directory, texBase, ddsBase)
if result: return result
if self.texSearchMode == 'PATH':
# Check the data folder and all sub-folders
result = texMatchDownward(state.rs3DataDir if isRS3 else state.rs2DataDir, texBase, ddsBase)
if result: return result
elif self.texSearchMode == 'BRUTE':
parentDir = os.path.dirname(state.directory)
# This is incredibly inefficient, it checks ALL directories and ALL files
# We could improve this with downward search caching and early exits for known system folders
# Both of those depend on the operating system so screw it
for _ in range(TEX_UPWARD_SEARCH_LIMIT):
# Check the parent folder and all sub-folders
result = texMatchDownward(parentDir, texBase, ddsBase)
if result: return result
parentDir = os.path.dirname(parentDir)
self.report({ 'WARNING' }, f"GZRS2: Texture search failed, no upward file match: { texBase }")
def textureSearchLoadFake(self, texBase, texDir, isRS3, state):
if state.texSearchMode == 'SKIP':
return True, texBase, True
texpath = textureSearch(self, texBase, texDir, isRS3, state)
if texpath is None:
return False, texBase, True
texpath = bpy.path.abspath(texpath)
return True, texpath, False
def resourceSearch(self, resourcename, state):
result = pathExists(os.path.join(state.directory, resourcename))
if result: return result
ensureRS3DataDirectory(self, state)
result = state.rs3DataDict.get(resourcename.lower())
if result: return result
splitname = resourcename.split(os.extsep)
if splitname[-1].lower() == 'xml' and splitname[-2].lower() in ('scene', 'prop'):
eluname = f"{ splitname[0] }{ os.extsep }elu"
result = state.rs3DataDict.get(eluname.lower())
if result:
self.report({ 'WARNING' }, f"GZRS2: Resource found after missing scene.xml or prop.xml: { resourcename }, { eluname }")
return result
self.report({ 'ERROR' }, f"GZRS2: Resource search failed: { resourcename }")
def lcFindRoot(lc, collection):
if lc.collection is collection: return lc
elif len(lc.children) == 0: return
for child in lc.children:
next = lcFindRoot(child, collection)
if next is not None:
return next
def getTexImage(bpy, texpath, alphamode, state):
texImages = state.blTexImages.setdefault(texpath, {})
if alphamode not in texImages:
image = bpy.data.images.load(texpath)
image.alpha_mode = alphamode
texImages[alphamode] = image
return texImages[alphamode]
def getShaderNodeByID(nodes, id, *, blacklist = ()):
for node in nodes:
if node.bl_idname == id and node not in blacklist:
return node
def getRelevantShaderNodes(nodes):
group = ensureLmMixGroup()
shader = getShaderNodeByID(nodes, 'ShaderNodeBsdfPrincipled')
output = getShaderNodeByID(nodes, 'ShaderNodeOutputMaterial')
info = getShaderNodeByID(nodes, 'ShaderNodeObjectInfo')
transparent = getShaderNodeByID(nodes, 'ShaderNodeBsdfTransparent')
mix = getShaderNodeByID(nodes, 'ShaderNodeMixShader')
clip = getShaderNodeByID(nodes, 'ShaderNodeMath')
add = getShaderNodeByID(nodes, 'ShaderNodeAddShader')
lightmix = getShaderNodeByID(nodes, 'ShaderNodeGroup')
for node in nodes:
if node.bl_idname == 'ShaderNodeMath' and node.operation == 'GREATER_THAN':
clip = node
elif node.bl_idname == 'ShaderNodeGroup' and node.node_tree == group:
lightmix = node
return shader, output, info, transparent, mix, clip, add, lightmix
def checkShaderNodeValidity(shader, output, info, transparent, mix, clip, add, lightmix, links):
shaderValid = False if shader and mix else None
infoValid = False if info and mix else None
transparentValid = False if transparent and mix else None
mixValid = False if mix and output else None
clipValid = False if clip and shader else None
addValid = False if add and shader and transparent and mix else None
addValid1 = False if add and shader else None
addValid2 = False if add and transparent else None
addValid3 = False if add and mix else None
lightmixValid = False if lightmix and shader else None
for link in links:
if link.is_hidden or not link.is_valid:
continue
if shaderValid == False and link.from_socket == shader.outputs[0] and link.to_socket == mix.inputs[2]: shaderValid = True
elif infoValid == False and link.from_socket == info.outputs[2] and link.to_socket == mix.inputs[0]: infoValid = True
elif transparentValid == False and link.from_socket == transparent.outputs[0] and link.to_socket == mix.inputs[1]: transparentValid = True
elif mixValid == False and link.from_socket == mix.outputs[0] and link.to_socket == output.inputs[0]: mixValid = True
elif clipValid == False and link.from_socket == clip.outputs[0] and link.to_socket == shader.inputs[4]: clipValid = True
elif addValid1 == False and link.from_socket == shader.outputs[0] and link.to_socket == add.inputs[0]: addValid1 = True
elif addValid2 == False and link.from_socket == transparent.outputs[0] and link.to_socket == add.inputs[1]: addValid2 = True
elif addValid3 == False and link.from_socket == add.outputs[0] and link.to_socket == mix.inputs[2]: addValid3 = True
elif lightmixValid == False and link.from_socket == lightmix.outputs[0] and link.to_socket == shader.inputs[0]: lightmixValid = True
if clipValid and clip.operation != 'GREATER_THAN':
clipValid = False
if addValid == False and addValid1 == True and addValid2 == True and addValid3 == True:
addValid = True
for link in links:
if link.is_hidden or not link.is_valid:
continue
if addValid and link.from_socket == add.outputs[0] and link.to_socket == mix.inputs[2]: shaderValid = True
return shaderValid, infoValid, transparentValid, mixValid, clipValid, addValid, lightmixValid
def getLinkedImageNodes(shader, shaderValid, links, clip, clipValid, lightmix, lightmixValid, *, validOnly = True):
texture = None
emission = None
alpha = None
lightmap = None
for link in links:
node = link.from_node
if node.bl_idname != 'ShaderNodeTexImage': continue
if validOnly and not isValidEluImageNode(node): continue
if link.is_hidden or not link.is_valid: continue
if shaderValid and link.to_node == shader:
if link.from_socket == node.outputs[0] and link.to_socket == shader.inputs[0]: texture = node
if link.from_socket == node.outputs[0] and link.to_socket == shader.inputs[26]: emission = node
if link.from_socket == node.outputs[1] and link.to_socket == shader.inputs[4]: alpha = node
elif clipValid and link.to_node == clip:
if link.from_socket == node.outputs[1] and link.to_socket == clip.inputs[0]: alpha = node
elif lightmixValid and link.to_node == lightmix:
if link.from_socket == node.outputs[0] and link.to_socket == lightmix.inputs[0]: texture = node
if link.from_socket == node.outputs[0] and link.to_socket == lightmix.inputs[1]: lightmap = node
return texture, emission, alpha, lightmap
def getModifierByType(self, modifiers, type):
for modifier in modifiers:
if modifier.type == type:
return modifier
def getValidArmature(self, object, state):
if object is None:
return None, None
modifier = getModifierByType(self, object.modifiers, 'ARMATURE')
if modifier is None:
return None, None
modObj = modifier.object
if modObj is None or modObj.type != 'ARMATURE':
return None, None
return modObj, modObj.data
def getEluExportConstants():
version = ELU_5007
maxPathLength = ELU_NAME_LENGTH if version <= ELU_5005 else ELU_PATH_LENGTH
return version, maxPathLength
def getMatTreeLinksNodes(blMat):
tree = blMat.node_tree
links = tree.links
nodes = tree.nodes
return tree, links, nodes
def getMatImageTextureNode(bpy, blMat, nodes, texpath, alphamode, x, y, loadFake, state):
if texpath is None or loadFake:
texture = nodes.new('ShaderNodeTexImage')
if loadFake:
texture.image = bpy.data.images.new(texpath, 0, 0)
texture.image.filepath = texture.image.filepath_raw = '//' + texpath
texture.image.source = 'FILE'
texture.image.alpha_mode = alphamode
texture.location = (x, y)
texture.select = False
return texture
matNodes = state.blMatNodes.setdefault(blMat, {})
haveTexture = texpath in matNodes
haveAlphaMode = haveTexture and alphamode in matNodes[texpath]
if not haveTexture or not haveAlphaMode:
texture = nodes.new('ShaderNodeTexImage')
texture.image = getTexImage(bpy, texpath, alphamode, state)
texture.location = (x, y)
texture.select = False
if not haveTexture:
matNodes[texpath] = { alphamode: texture }
elif not haveAlphaMode:
matNodes[texpath][alphamode] = texture
return matNodes[texpath][alphamode]
def getMatFlagsRender(blMat, clip, addValid, clipValid, emission, alpha):
twosided = not blMat.use_backface_culling
additive = blMat.surface_render_method == 'BLENDED' and addValid and emission is not None
alphatest = int(min(max(0, clip.inputs[1].default_value), 1) * 255) if clipValid else 0 # Threshold
usealphatest = alphatest > 0
useopacity = alpha is not None
return twosided, additive, alphatest, usealphatest, useopacity
def decomposePath(path):
if not path:
return None, None, None, None
basename = bpy.path.basename(path)
filename, extension = os.path.splitext(basename)
directory = os.path.dirname(path)
return basename, filename, extension, directory
def checkIsAniTex(texName):
return False if texName is None else texName.lower().startswith('txa')
def isChildProp(blMeshObj):
if blMeshObj.parent is None: return False
elif blMeshObj.parent.type != 'MESH': return False
elif blMeshObj.parent.data is None: return False
elif blMeshObj.parent.data.gzrs2.meshType == 'PROP': return True
return isChildProp(blMeshObj.parent)
def processAniTexParameters(isAniTex, texName, *, silent = False):
if not isAniTex:
return True, None, None, None
# texNameStart = texName[-2:]
texNameShort = texName[:-2]
texParams = texNameShort.replace('_', ' ').split(' ')
if len(texParams) < 4:
if not silent:
self.report({ 'ERROR' }, f"GZRS2: Unable to split animated texture name! { texNameShort }, { texParams } ")
return False, None, None, None
try:
frameCount, frameSpeed = int(texParams[1]), int(texParams[2])
except ValueError:
if not silent:
self.report({ 'ERROR' }, f"GZRS2: Animated texture name must use integers for frame count and speed! { texNameShort } ")
return False, None, None, None
else:
frameGap = frameSpeed / frameCount
return True, frameCount, frameSpeed, frameGap
def setMatFlagsTransparency(blMat, transparent, *, twosided = False):
blMat.use_transparent_shadow = True # Settings
blMat.use_transparency_overlap = True # Viewport Display
# Viewport Display
if transparent:
blMat.use_backface_culling = False
blMat.use_backface_culling_shadow = False
blMat.use_backface_culling_lightprobe_volume = False
else:
blMat.use_backface_culling = not twosided
blMat.use_backface_culling_shadow = not twosided
blMat.use_backface_culling_lightprobe_volume = not twosided
def setupMatBase(name, *, blMat = None, shader = None, output = None, info = None, transparent = None, mix = None):
blMat = blMat or bpy.data.materials.new(name)
blMat.use_nodes = True
blMat.surface_render_method = 'DITHERED'
tree, links, nodes = getMatTreeLinksNodes(blMat)
shader = shader or getShaderNodeByID(nodes, 'ShaderNodeBsdfPrincipled') or nodes.new('ShaderNodeBsdfPrincipled')
shader.location = (20, 300)
shader.select = False
shader.inputs[12].default_value = 0.0 # Specular IOR Level
shader.inputs[27].default_value = 0.0 # Emission Strength
output = output or getShaderNodeByID(nodes, 'ShaderNodeOutputMaterial') or nodes.new('ShaderNodeOutputMaterial')
output.location = (300, 300)
output.select = False
setMatFlagsTransparency(blMat, False)
info = info or nodes.new('ShaderNodeObjectInfo')
info.location = (120, 480)
info.select = False
transparent = transparent or nodes.new('ShaderNodeBsdfTransparent')
transparent.location = (120, -40)
transparent.select = False
mix = mix or nodes.new('ShaderNodeMixShader')
mix.location = (300, 140)
mix.select = False
mix.inputs[0].default_value = 1.0 # Factor
links.new(info.outputs[2], mix.inputs[0])
links.new(transparent.outputs[0], mix.inputs[1])
links.new(shader.outputs[0], mix.inputs[2])
links.new(mix.outputs[0], output.inputs[0])
return blMat, tree, links, nodes, shader, output, info, transparent, mix
def setupMatNodesLightmap(blMat, tree, links, nodes, shader, *, lightmap = None, uvmap = None, lightmix = None, image = None):
lightmap = lightmap or nodes.new('ShaderNodeTexImage')
uvmap = uvmap or getShaderNodeByID(nodes, 'ShaderNodeUVMap') or nodes.new('ShaderNodeUVMap')
lightmix = lightmix or nodes.new('ShaderNodeGroup')
lightmap.image = image or lightmap.image
uvmap.uv_map = 'UVMap.001'
lightmix.node_tree = ensureLmMixGroup()
lightmap.location = (-440, -20)
uvmap.location = (-640, -20)
lightmix.location = (-160, 300)
lightmap.select = False
uvmap.select = False
lightmix.select = False
links.new(lightmap.outputs[0], lightmix.inputs[1])
links.new(uvmap.outputs[0], lightmap.inputs[0])
links.new(lightmix.outputs[0], shader.inputs[0]) # Base Color
return lightmap, uvmap, lightmix, lightmap.image
def setupMatNodesTransparency(blMat, tree, links, nodes, alphatest, usealphatest, useopacity, source, destination, *, clip = False):
if usealphatest:
blMat.surface_render_method = 'DITHERED'
clip = clip or nodes.new('ShaderNodeMath')
clip.operation = 'GREATER_THAN'
clip.location = (-160, 160)
clip.select = False
links.new(source.outputs[1], clip.inputs[0])
links.new(clip.outputs[0], destination.inputs[4]) # Alpha
clip.inputs[1].default_value = alphatest / 255.0
return clip
elif useopacity:
blMat.surface_render_method = 'DITHERED'
links.new(source.outputs[1], destination.inputs[4]) # Alpha
def setupMatNodesAdditive(blMat, tree, links, nodes, additive, source, destination, transparent, mix, *, add = None):
if not additive:
return
blMat.surface_render_method = 'BLENDED'
add = add or nodes.new('ShaderNodeAddShader')
add.location = (300, 0)
add.select = False
if source:
links.new(source.outputs[0], destination.inputs[26]) # Emission Color
destination.inputs[27].default_value = 1.0 # Emission Strength
links.new(destination.outputs[0], add.inputs[0])
links.new(transparent.outputs[0], add.inputs[1])
links.new(add.outputs[0], mix.inputs[2])
return add
def processRS2Texlayer(self, blMat, xmlRsMat, tree, links, nodes, shader, transparent, mix, state):
texpath = xmlRsMat.get('DIFFUSEMAP')
texBase, _, _, texDir = decomposePath(texpath)
# TODO: Don't return on failure, continue with color preset
if texBase == None:
# self.report({ 'WARNING' }, f"GZRS2: .rs.xml material with no texture name: { texBase }")
return
if texBase == '':
self.report({ 'WARNING' }, f"GZRS2: .rs.xml material with an empty texture name: { texBase }")
return
if not isValidTexBase(texBase):
self.report({ 'WARNING' }, f"GZRS2: .rs.xml material with an invalid texture name: { blMat.name }, { texBase }")
return
success, texpath, loadFake = textureSearchLoadFake(self, texBase, texDir, False, state)
if not success:
self.report({ 'WARNING' }, f"GZRS2: Texture not found for .rs.xml material: { blMat.name }, { texBase }")
texture = getMatImageTextureNode(bpy, blMat, nodes, texpath, 'STRAIGHT', -440, 300, loadFake, state)
props = blMat.gzrs2
props.overrideTexpath = texDir != ''
props.writeDirectory = texDir != ''
props.texBase = texBase
props.texDir = texDir
if state.doLightmap:
_, _, lightmix, _ = setupMatNodesLightmap(blMat, tree, links, nodes, shader, image = state.blLmImage)
links.new(texture.outputs[0], lightmix.inputs[0])
else:
links.new(texture.outputs[0], shader.inputs[0]) # Base Color
usealphatest = xmlRsMat['USEALPHATEST']
alphatest = xmlRsMat['ALPHATESTVALUE']
useopacity = xmlRsMat['USEOPACITY']
additive = xmlRsMat['ADDITIVE']
twosided = xmlRsMat['TWOSIDED']
# _, texName, _, _ = decomposePath(texpath)
# isAniTex = checkIsAniTex(texName)
# success, frameCount, frameSpeed, frameGap = processAniTexParameters(isAniTex, texName)
source = lightmix if state.doLightmap else texture
setupMatNodesTransparency(blMat, tree, links, nodes, alphatest, usealphatest, useopacity, texture, shader)
setupMatNodesAdditive(blMat, tree, links, nodes, additive, source, shader, transparent, mix)
setMatFlagsTransparency(blMat, usealphatest or useopacity or additive, twosided = twosided)
def processRS3TexLayer(self, texlayer, blMat, tree, links, nodes, shader, emission, alphatest, usealphatest, state):
texType = texlayer['type']
texBase = texlayer['name']
useopacity = texType == 'OPACITYMAP'
if texType not in XMLELU_TEXTYPES:
self.report({ 'ERROR' }, f"GZRS2: Unsupported texture type for .elu.xml material: { texBase }, { texType }")
return useopacity
if texBase == None:
self.report({ 'ERROR' }, f"GZRS2: .elu.xml material with no texture name: { texBase }, { texType }")
return useopacity
if texBase == '':
self.report({ 'ERROR' }, f"GZRS2: .elu.xml material with an empty texture name: { texBase }, { texType }")
return useopacity
if not isValidTexBase(texBase):
self.report({ 'ERROR' }, f"GZRS2: .elu.xml material with an invalid texture name: { texBase }, { texType }")
return useopacity
success, texpath, loadFake = textureSearchLoadFake(self, texBase, '', True, state)
if not success:
self.report({ 'WARNING' }, f"GZRS2: Texture not found for .elu.xml material: { texBase }, { texType }")
if texType == 'DIFFUSEMAP':
texture = getMatImageTextureNode(bpy, blMat, nodes, texpath, 'CHANNEL_PACKED', -540, 300, loadFake, state)
texture.select = False
links.new(texture.outputs[0], shader.inputs[0]) # Base Color
elif texType == 'SPECULARMAP':
texture = getMatImageTextureNode(bpy, blMat, nodes, texpath, 'CHANNEL_PACKED', -540, 0, loadFake, state)
texture.select = False
invert = nodes.new('ShaderNodeInvert')
invert.location = (texture.location.x + 280, texture.location.y)
invert.select = False
# TODO: specular data is sometimes found in the alpha channel of the diffuse or normal maps
links.new(texture.outputs[0], invert.inputs[1])
links.new(invert.outputs[0], shader.inputs[2]) # Roughness
elif texType == 'SELFILLUMINATIONMAP':
texture = getMatImageTextureNode(bpy, blMat, nodes, texpath, 'CHANNEL_PACKED', -540, -300, loadFake, state)
texture.select = False
links.new(texture.outputs[0], shader.inputs[26]) # Emission Color
shader.inputs[27].default_value = emission # Emission Strength
elif texType == 'OPACITYMAP':
texture = getMatImageTextureNode(bpy, blMat, nodes, texpath, 'CHANNEL_PACKED', -540, 300, loadFake, state)
texture.select = False
setupMatNodesTransparency(blMat, tree, links, nodes, alphatest, usealphatest, useopacity, texture, shader)
elif texType == 'NORMALMAP':
texture = getMatImageTextureNode(bpy, blMat, nodes, texpath, 'NONE', -540, -600, loadFake, state)
texture.image.colorspace_settings.name = 'Non-Color'
texture.select = False
normal = nodes.new('ShaderNodeNormalMap')
normal.location = (-260, -600)
normal.select = False
links.new(texture.outputs[0], normal.inputs[1])
links.new(normal.outputs[0], shader.inputs[5]) # Normal
return useopacity
def setupDebugMat(name, color):
blDebugMat = bpy.data.materials.new(name)
blDebugMat.use_nodes = True
blDebugMat.diffuse_color = color
blDebugMat.roughness = 1.0
blDebugMat.surface_render_method = 'BLENDED'
setMatFlagsTransparency(blDebugMat, True)
if color[3] < 1.0:
tree, links, nodes = getMatTreeLinksNodes(blDebugMat)
nodes.remove(getShaderNodeByID(nodes, 'ShaderNodeBsdfPrincipled'))
output = getShaderNodeByID(nodes, 'ShaderNodeOutputMaterial')
transparent = nodes.new('ShaderNodeBsdfTransparent')
transparent.location = (120, 300)
links.new(transparent.outputs[0], output.inputs[0])
return blDebugMat
def setObjFlagsDebug(blObj):
# Visibility
blObj.visible_camera = False
blObj.visible_diffuse = False
blObj.visible_glossy = False
blObj.visible_volume_scatter = False
blObj.visible_transmission = False
blObj.visible_shadow = False
# Viewport Display
blObj.show_wire = True
blObj.display.show_shadows = False
def getErrorMat(state):
blErrorMat = state.blErrorMat
if blErrorMat is not None:
return blErrorMat
errName = f"{ state.filename }_Error"
blErrorMat = bpy.data.materials.get(errName)
if blErrorMat is not None:
return blErrorMat
blErrorMat = setupDebugMat(errName, (1.0, 0.0, 1.0, 1.0))
state.blErrorMat = blErrorMat
return blErrorMat
def setupColMesh(name, collection, context, extension, state):
blColMat = setupDebugMat(name, (1.0, 0.0, 1.0, 0.25))
blColMesh = bpy.data.meshes.new(name)
blColObj = bpy.data.objects.new(name, blColMesh)
blColMesh.gzrs2.meshType = 'RAW'
colFaces = tuple(tuple(range(i, i + 3)) for i in range(0, len(state.colVerts), 3))
blColMesh.from_pydata(state.colVerts, (), colFaces)
blColMesh.validate()
blColMesh.update()
setObjFlagsDebug(blColObj)
state.blColMat = blColMat
state.blColMesh = blColMesh
state.blColObj = blColObj
blColObj.data.materials.append(blColMat)
collection.objects.link(blColObj)
for viewLayer in context.scene.view_layers:
blColObj.hide_set(False, view_layer = viewLayer)
viewLayer.objects.active = blColObj
if state.doCleanup and state.logCleanup:
print()
print("=== Col Mesh Cleanup ===")
print()
if state.doCleanup:
counts = countInfoReports(context)
bpy.ops.object.select_all(action = 'DESELECT')
blColObj.select_set(True)
bpy.ops.object.select_all(action = 'DESELECT')
bpy.ops.object.mode_set(mode = 'EDIT')
bpy.ops.mesh.select_mode(type = 'VERT')
bpy.ops.mesh.select_all(action = 'SELECT')
deleteInfoReports(context, counts)
def subCleanup():
for _ in range(10):
bpy.ops.mesh.dissolve_degenerate()
bpy.ops.mesh.delete_loose()
bpy.ops.mesh.select_all(action = 'SELECT')
bpy.ops.mesh.remove_doubles(threshold = 0.0001)
def cleanupFunc():
counts = countInfoReports(context)
if extension == 'col':
bpy.ops.mesh.intersect(mode = 'SELECT', separate_mode = 'ALL', threshold = 0.0001, solver = 'FAST')
bpy.ops.mesh.select_all(action = 'SELECT')
subCleanup()
bpy.ops.mesh.intersect(mode = 'SELECT', separate_mode = 'ALL')
bpy.ops.mesh.select_all(action = 'SELECT')
subCleanup()
for _ in range(10):
bpy.ops.mesh.fill_holes(sides = 0)
bpy.ops.mesh.tris_convert_to_quads(face_threshold = 0.0174533, shape_threshold = 0.0174533)
subCleanup()
bpy.ops.mesh.vert_connect_nonplanar(angle_limit = 0.0174533)
subCleanup()
elif extension == 'cl2':
bpy.ops.mesh.remove_doubles(threshold = 0.0001, use_sharp_edge_from_normals = True)
bpy.ops.mesh.tris_convert_to_quads(face_threshold = 0.0174533, shape_threshold = 0.0174533)
bpy.ops.mesh.dissolve_limited(angle_limit = 0.0174533)
bpy.ops.mesh.delete_loose(use_faces = True)
bpy.ops.mesh.select_all(action = 'SELECT')
bpy.ops.mesh.normals_make_consistent(inside = True)
bpy.ops.mesh.select_all(action = 'DESELECT')
bpy.ops.object.mode_set(mode = 'OBJECT')
deleteInfoReports(context, counts)
if state.logCleanup:
print(name)
cleanupFunc()
print()
else:
with redirect_stdout(state.silentIO):
cleanupFunc()
blColMesh.gzrs2.meshType = 'COLLISION'
counts = countInfoReports(context)
bpy.ops.object.select_all(action = 'DESELECT')
deleteInfoReports(context, counts)
return blColObj
def setupNavMesh(state):
facesName = f"{ state.filename }_Navmesh"
linksName = f"{ state.filename }_Navlinks"
blNavMat = setupDebugMat(facesName, (0.0, 1.0, 0.0, 0.25))
blNavFaces = bpy.data.meshes.new(facesName)
blNavLinks = bpy.data.meshes.new(linksName)
blNavFacesObj = bpy.data.objects.new(facesName, blNavFaces)
blNavLinksObj = bpy.data.objects.new(linksName, blNavLinks)
blNavFaces.gzrs2.meshType = 'NAVIGATION'
blNavFaces.from_pydata(state.navVerts, (), state.navFaces)
blNavFaces.validate()
blNavFaces.update()
linksVerts = tuple((state.navVerts[face[0]] + state.navVerts[face[1]] + state.navVerts[face[2]]) / 3.0 for face in state.navFaces)
linksEdges = tuple((l, link[i]) for i in range(3) for l, link in enumerate(state.navLinks) if link[i] >= 0)
blNavLinks.from_pydata(linksVerts, linksEdges, ())
blNavLinks.validate()
blNavLinks.update()
setObjFlagsDebug(blNavFacesObj)
setObjFlagsDebug(blNavLinksObj)
state.blNavMat = blNavMat
state.blNavFaces = blNavFaces
state.blNavLinks = blNavLinks
state.blNavFacesObj = blNavFacesObj
state.blNavLinksObj = blNavLinksObj
blNavFacesObj.data.materials.append(blNavMat)
return blNavFacesObj, blNavLinksObj
def setupEluMat(self, m, eluMat, state):
elupath = eluMat.elupath
matID = eluMat.matID
subMatID = eluMat.subMatID
subMatCount = eluMat.subMatCount
ambient = eluMat.ambient
diffuse = eluMat.diffuse
specular = eluMat.specular
exponent = eluMat.exponent
alphatest = eluMat.alphatest
useopacity = eluMat.useopacity
additive = eluMat.additive
twosided = eluMat.twosided
texName = eluMat.texName
texBase = eluMat.texBase
texDir = eluMat.texDir
for eluMat2, blMat2 in state.blEluMatPairs:
if subMatID != eluMat2.subMatID: continue
if subMatCount != eluMat2.subMatCount: continue
if not compareColors(ambient, eluMat2.ambient): continue
if not compareColors(diffuse, eluMat2.diffuse): continue
if not compareColors(specular, eluMat2.specular): continue
if not math.isclose(exponent, eluMat2.exponent, abs_tol = ELU_VALUE_THRESHOLD): continue
if not math.isclose(alphatest, eluMat2.alphatest, abs_tol = ELU_VALUE_THRESHOLD): continue
if useopacity != eluMat2.useopacity: continue
if additive != eluMat2.additive: continue
if twosided != eluMat2.twosided: continue
if eluMat.texpath != eluMat2.texpath: continue