-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathio_scene_dff_2.py
1807 lines (1286 loc) · 66.9 KB
/
io_scene_dff_2.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
bl_info = {
"name": "RenderWare importer/exporter for GTA III/VC/SA (.dff)",
"author": "Ago Allikmaa (maxorator), Pedro Luis Valadés Viera (PerikiyoXD)",
"version": (0, 10, 0),
"blender": (2, 6, 3),
"location": "File > Import-Export > Renderware (.dff) ",
"description": "RenderWare importer/exporter for GTA III/VC/SA",
"category": "Import-Export"
}
import struct
import os
import time
import zlib
import base64
import bpy
import math
import mathutils
from collections import deque
from bpy.props import *
class RwTypes():
ANY = -1
STRUCT = 0x0001
STRING = 0x0002
EXTENSION = 0x0003
TEXTURE = 0x0006
MATERIAL = 0x0007
MATERIALLIST = 0x0008
FRAMELIST = 0x000E
GEOMETRY = 0x000F
CLUMP = 0x0010
ATOMIC = 0x0014
GEOMETRYLIST = 0x001A
RENDERRIGHTS = 0x001F
MORPHPLG = 0x0105
SKINPLG = 0x116
HANIMPLG = 0x11E
MATEFFECTS = 0x0120
BINMESHPLG = 0x050E
FRAMENAME = 0x253F2FE
COLLISION = 0x253F2FA
MATSPECULAR = 0x253F2F6
NIGHTCOLS = 0x253F2F9
MATREFLECTION = 0x253F2FC
MESHEXTENSION = 0x253F2FD
def decodeVersion(version):
if (version & 0xFFFF0000) == 0:
print("Version: "+str(hex(version << 8)))
return version << 8
else:
p1 = ((version >> 14) & 0x3FF00) + 0x30000
p2 = (version >> 16) & 0x3F
print("Version: "+str(hex(p1 | p2)))
return p1 | p2
class RpGeomFlag:
TRISTRIP = 0x0001
POSITIONS = 0x0002
TEXTURED = 0x0004
PRELIT = 0x0008
NORMALS = 0x0010
LIGHT = 0x0020
MODULATEMATERIALCOLOR = 0x0040
TEXTURED2 = 0x0080
class ImportRenderware:
class RwTriangle:
def __init__(self, verts, mat):
self.verts = verts
self.mat = mat
def desc(self):
return (self.verts[0], self.verts[1], self.verts[2])
class RwVertex:
def __init__(self, coords, normal):
self.coords = coords
self.normal = normal
self.uv = None
self.uv_env = None
def desc(self):
return (self.coords[0], self.coords[1], self.coords[2])
class RwFrame:
def __init__(self, loader, index, rot, pos, parent):
self.loader = loader
self.index = index
self.geometry = None
self.atomic = None
self.blobj = None
self.bldata = None
self.hanimdata = None
self.name = None
rmatrix = mathutils.Matrix.Identity(3)
rmatrix[0] = rot[0], rot[1], rot[2]
rmatrix[1] = rot[3], rot[4], rot[5]
rmatrix[2] = rot[6], rot[7], rot[8]
rmatrix.resize_4x4()
rmatrix.translation = pos[0], pos[1], pos[2]
self.matrix = rmatrix
self.parent = parent
self.loader.childrenOf[parent+1].append(self.index)
def setAtomic(self, atomic):
self.atomic = atomic
self.geometry = atomic.geometry
def build(self):
if self.name is None:
self.name = "noname_" + str(self.index);
if self.geometry:
self.bldata = self.geometry.build(self.name)
self.blobj = bpy.data.objects.new(self.name, self.bldata)
if self.parent >= 0:
self.blobj.parent = self.loader.frames[self.parent].blobj
self.blobj.matrix_local = self.matrix
bpy.context.scene.objects.link(self.blobj)
for frame in self.loader.childrenOf[self.index+1]:
self.loader.frames[frame].build()
if "_vlo" in self.name or "_dam" in self.name:
self.blobj.hide = True
self.blobj.hide_render = True
if self.loader.colhex and self.index == self.loader.childrenOf[0][0]:
textobj = bpy.data.texts.new(name = ("zrwcoll_" + self.name))
textobj.from_string(self.loader.colhex)
self.blobj.collhex = textobj.name
if self.hanimdata:
textobj = bpy.data.texts.new(name = ("zrwhanim" + str(self.index) + "_" + self.name))
textobj.from_string(self.hanimdata)
self.blobj.rw_hanimdata = textobj.name
if self.geometry and self.geometry.skindata:
textobj = bpy.data.texts.new(name = ("zrwskin_" + self.name))
textobj.from_string(self.geometry.skindata)
self.blobj.rw_skindata = textobj.name
if self.atomic and self.atomic.renderPlugin != None and self.atomic.renderExtra != None:
self.blobj.renderright = self.atomic.renderPlugin
self.blobj.renderextra = self.atomic.renderExtra
if self.atomic and self.atomic.matfxpipe:
self.blobj.matfxpipe = True
class RpGeometry:
def __init__(self, loader, index):
self.loader = loader
self.index = index
self.vertices = []
self.triangles = []
self.materials = []
self.mesh = None
self.atomic = None
self.skindata = None
self.hasEnvUV = False
self.vertCol = None
self.nightVertCol = None
self.hasNormals = False
def setAtomic(self, atomic):
self.atomic = atomic
def addMaterial(self, material):
material.setIndex(len(self.materials))
self.materials.append(material)
def addVertex(self, vertex):
self.vertices.append(vertex)
def addTriangle(self, triangle):
self.triangles.append(triangle)
def build(self, name):
self.mesh = bpy.data.meshes.new(name)
pyverts = []
pypolys = []
for vertex in self.vertices:
pyverts.append(vertex.desc())
for triangle in self.triangles:
pypolys.append(triangle.desc())
self.mesh.from_pydata(pyverts, [], pypolys)
self.mesh.update()
if self.vertCol:
vcol = self.mesh.vertex_colors.new("Normal")
self.mesh.vertex_colors.active = vcol
for i in range(len(self.vertices)):
vcol.data[i].color = (self.vertCol[i][0], self.vertCol[i][1], self.vertCol[i][2])
if self.nightVertCol:
nvcol = self.mesh.vertex_colors.new("Night")
self.mesh.vertex_colors.active = nvcol
for i in range(len(self.vertices)):
nvcol.data[i].color = (self.nightVertCol[i][0], self.nightVertCol[i][1], self.nightVertCol[i][2])
uvtexture = self.mesh.uv_textures.new()
uvtexture.name = "MainUV"
uvlayer = self.mesh.uv_layers[-1]
for i in range(len(self.triangles)):
for j in range(3):
uvlayer.data[3*i + j].uv = self.vertices[self.triangles[i].verts[j]].uv
if self.hasEnvUV:
euvtexture = self.mesh.uv_textures.new()
euvtexture.name = "EnvUV"
euvlayer = self.mesh.uv_layers[-1]
for i in range(len(self.triangles)):
for j in range(3):
euvlayer.data[3*i + j].uv = self.vertices[self.triangles[i].verts[j]].uv_env
for material in self.materials:
material.build()
for i in range(len(self.triangles)):
self.mesh.polygons[i].material_index = self.triangles[i].mat
return self.mesh
class RpMaterial:
def __init__(self, geometry, flags=None, col=None, textured=None, ambient=None, specular=None, diffuse=None):
self.index = None
self.name = "g" + str(geometry.index) + "m"
self.geometry = geometry
self.flags = flags
self.col = col
self.ambient = ambient
self.specular = specular
self.diffuse = diffuse
self.textured = textured
self.texture = None
self.blmat = None
self.envtex = None
self.readenvmap = False
self.envIntensity = 1
self.reflectColour = None
self.reflectIntensity = None
self.spectex = None
def setIndex(self, index):
self.index = index
self.name = "g" + str(self.geometry.index) + "m" + str(index)
def setTexture(self, texture):
self.texture = texture
def setEnvTexture(self, texture):
self.envtex = texture
def setSpecTexture(self, texture):
self.spectex = texture
def setReflection(self, colour, intensity):
self.reflectColour = colour
self.reflectIntensity = intensity
def build(self):
#Be careful, sometimes materials dont have textures!
#On this cases, we'll let the material generate it's name.
if (self.texture is None):
self.name = "notextured_" + str(self.col[0]) + "." + str(self.col[1]) + "." + str(self.col[2]) + "." + str(self.col[3])
else:
#We set material's name to the texture name.
self.name = self.texture.name
#First, we search for the material, to see if we already have this material imported.
lookupMaterial = bpy.data.materials.find(self.name)
if lookupMaterial != -1:
self.blmat = bpy.data.materials[lookupMaterial]
print("Material: Skipping material \""+self.name+"\"")
else:
print("Material: Building material \""+self.name+"\"")
self.blmat = bpy.data.materials.new(self.name)
self.blmat.diffuse_color = (self.col[0]/255, self.col[1]/255, self.col[2]/255)
self.blmat.diffuse_intensity = self.diffuse
self.blmat.ambient = self.ambient
self.blmat.specular_intensity = self.specular
if self.geometry.vertCol:
self.blmat.use_vertex_color_light = True
if self.col[3] < 255:
self.blmat.use_transparency = True
self.blmat.alpha = self.col[3]/255
if self.envtex:
self.envtex.build()
if self.spectex:
self.spectex.build()
if self.texture:
self.texture.build()
self.blmat.active_texture_index = 0
if self.reflectColour and self.reflectIntensity:
self.blmat.mirror_color = self.reflectColour
self.blmat.raytrace_mirror.use = True
self.blmat.raytrace_mirror.reflect_factor = self.reflectIntensity
self.geometry.mesh.materials.append(self.blmat)
class RwTexture:
def __init__(self, loader, material, name, texType, intensity=1):
self.material = material
self.bltex = None
self.bltexslot = None
self.name = name
self.loader = loader
self.texType = texType
self.intensity = intensity
def build(self):
if self.texType == 1 and self.name in self.loader.envtexpool:
self.bltex = self.loader.envtexpool[self.name]
elif self.texType != 1 and self.name in self.loader.texpool:
self.bltex = self.loader.texpool[self.name]
else:
if self.texType == 1:
self.bltex = bpy.data.textures.new(self.name, "ENVIRONMENT_MAP")
self.bltex.__class__ = bpy.types.EnvironmentMapTexture
self.bltex.environment_map.source = "IMAGE_FILE"
self.loader.envtexpool[self.name] = self.bltex
else:
self.bltex = bpy.data.textures.new(self.name, "IMAGE")
self.bltex.__class__ = bpy.types.ImageTexture
self.loader.texpool[self.name] = self.bltex
print("Texture: Searching texture for material "+self.material.name+" (\"" + os.path.normcase(os.path.dirname(self.loader.filename) + "/" + self.name + ".png") + "\")")
#print(self.loader.filename)
imgfile = os.path.normcase(os.path.dirname(self.loader.filename) + "/" + self.name + ".png")
if os.path.isfile(imgfile):
self.bltex.image = bpy.data.images.load(imgfile)
self.bltexslot = self.material.blmat.texture_slots.create(self.texType)
self.bltexslot.texture_coords = "UV"
self.bltexslot.texture = self.bltex
if (self.texType == 1 or self.texType == 2) and self.material.geometry.hasEnvUV:
self.bltexslot.uv_layer = "EnvUV"
else:
self.bltexslot.uv_layer = "MainUV"
if self.texType == 1:
self.bltexslot.diffuse_factor = self.intensity
elif self.texType == 2:
self.bltexslot.use_map_diffuse = False
self.bltexslot.use_map_color_diffuse = False
self.bltexslot.use_map_color_spec = True
self.bltexslot.specular_color_factor = self.intensity
class RpAtomic:
def __init__(self, loader, frame, geometry, flags):
self.loader = loader
self.frame = frame
self.geometry = geometry
self.flags = flags
self.renderPlugin = None
self.renderExtra = None
self.matfxpipe = False
frame.setAtomic(self)
geometry.setAtomic(self)
def setRenderRights(self, plugin, extra):
self.renderPlugin = plugin
self.renderExtra = extra
def __init__(self, filename):
print("========== ImportRenderware: importing ==========")
self.filename = filename
self.texpool = {}
self.envtexpool = {}
print("Loading filename " + self.filename)
self.colhex = None
self.childrenOf = None
self.frames = []
self.geoms = []
self.f = open(filename, "rb")
self.readSection(RwTypes.CLUMP)
self.f.close()
for frame in self.childrenOf[0]:
self.frames[frame].build()
def writeDebug(self, text):
g = open(self.filename + ".txt", "a")
g.write(text + "\n")
g.close()
def readFormat(self, format):
return struct.unpack(format, self.f.read(struct.calcsize(format)))
def readSlice(self, format, slice):
size = struct.calcsize(format)
if(len(slice) < size):
raise Exception("Failed to read slice, buffer is too small.")
return struct.unpack(format, slice[:size]), slice[size:]
def readSection(self, type, extra = None):
header = self.readFormat("III")
header = (header[0], header[1], RwTypes.decodeVersion(header[2]))
if type >= 0 and header[0] != type:
raise Exception("Expected type " + str(type) + ", found " + str(header[0]))
curPos = self.f.tell()
res = None
if header[0] == RwTypes.STRUCT: res = self.readSectionStruct(header)
elif header[0] == RwTypes.STRING: res = self.readSectionString(header)
elif header[0] == RwTypes.EXTENSION: res = self.readSectionExtension(header, extra)
elif header[0] == RwTypes.TEXTURE: res = self.readSectionTexture(header, extra)
elif header[0] == RwTypes.MATERIAL: res = self.readSectionMaterial(header, extra)
elif header[0] == RwTypes.MATERIALLIST: res = self.readSectionMaterialList(header, extra)
elif header[0] == RwTypes.FRAMELIST: res = self.readSectionFrameList(header)
elif header[0] == RwTypes.GEOMETRY: res = self.readSectionGeometry(header, extra)
elif header[0] == RwTypes.CLUMP: res = self.readSectionClump(header)
elif header[0] == RwTypes.ATOMIC: res = self.readSectionAtomic(header)
elif header[0] == RwTypes.GEOMETRYLIST: res = self.readSectionGeometryList(header)
elif header[0] == RwTypes.MORPHPLG: res = self.readSectionMorphPLG(header, extra)
elif header[0] == RwTypes.BINMESHPLG: res = self.readSectionBinMeshPLG(header, extra)
elif header[0] == RwTypes.FRAMENAME: res = self.readSectionFrameName(header, extra)
elif header[0] == RwTypes.COLLISION: res = self.readSectionCollision(header, extra)
elif header[0] == RwTypes.MATEFFECTS: res = self.readSectionMatEffects(header, extra)
elif header[0] == RwTypes.MATSPECULAR: res = self.readSectionMatSpecular(header, extra)
elif header[0] == RwTypes.MATREFLECTION: res = self.readSectionMatReflection(header, extra)
elif header[0] == RwTypes.MESHEXTENSION: res = self.readSectionMeshExtension(header, extra)
elif header[0] == RwTypes.RENDERRIGHTS: res = self.readSectionRenderRights(header, extra)
elif header[0] == RwTypes.HANIMPLG: res = self.readSectionHAnimPLG(header, extra)
elif header[0] == RwTypes.SKINPLG: res = self.readSectionSkinPLG(header, extra)
elif header[0] == RwTypes.NIGHTCOLS: res = self.readSectionNightCols(header, extra)
elif type >= 0: raise Exception("Missing read function for section type " + str(type))
else: print("Ignoring extension data of type " + hex(header[0]))
self.f.seek(curPos + header[1])
return res
def readSectionStruct(self, header):
return header, self.f.read(header[1])
def readSectionString(self, header):
byteList = b""
for i in range(header[1]):
newByte = self.f.read(1)
if newByte[0] == 0:
break
byteList += newByte
return header, byteList.decode("ascii")
def readSectionExtension(self, header, extra):
endPos = self.f.tell() + header[1]
while self.f.tell() < endPos:
self.readSection(RwTypes.ANY, extra)
return header, None
def readSectionTexture(self, header, material):
metaHeader, slice = self.readSection(RwTypes.STRUCT)
(flags, x), slice = self.readSlice("HH", slice)
x, texName = self.readSection(RwTypes.STRING)
x, alphaName = self.readSection(RwTypes.STRING)
if material.readenvmap:
texture = self.RwTexture(self, material, texName, 1, material.envIntensity)
material.setEnvTexture(texture)
else:
texture = self.RwTexture(self, material, texName, 0, 1)
material.setTexture(texture)
self.readSection(RwTypes.EXTENSION)
return header, None
def readSectionMaterial(self, header, geometry):
metaHeader, slice = self.readSection(RwTypes.STRUCT)
(flags,), slice = self.readSlice("I", slice)
col, slice = self.readSlice("BBBB", slice)
(x, textured, ambient, specular, diffuse), slice = self.readSlice("iifff", slice)
material = self.RpMaterial(geometry, flags, col, textured, ambient, specular, diffuse)
geometry.addMaterial(material)
if textured > 0:
self.readSection(RwTypes.TEXTURE, material)
self.readSection(RwTypes.EXTENSION, material)
return header, None
def readSectionMaterialList(self, header, geometry):
metaHeader, slice = self.readSection(RwTypes.STRUCT)
(matCount,), slice = self.readSlice("i", slice)
for i in range(matCount):
junk, slice = self.readSlice("i", slice)
for i in range(matCount):
self.readSection(RwTypes.MATERIAL, geometry)
return header, None
def readSectionFrameList(self, header):
metaHeader, slice = self.readSection(RwTypes.STRUCT)
(frameCount,), slice = self.readSlice("i", slice)
self.childrenOf = []
for i in range(frameCount+1):
self.childrenOf.append([])
for i in range(frameCount):
rot, slice = self.readSlice("fffffffff", slice)
pos, slice = self.readSlice("fff", slice)
(parent, flags), slice = self.readSlice("ii", slice)
self.frames.append(self.RwFrame(self, i, rot, pos, parent))
for i in range(frameCount):
self.readSection(RwTypes.EXTENSION, self.frames[i])
return header, None
def readSectionGeometry(self, header, index):
metaHeader, slice = self.readSection(RwTypes.STRUCT)
(flags, texCount, triCount, vertCount, morphCount), slice = self.readSlice("HHiii", slice)
geometry = self.RpGeometry(self, index)
self.geoms.append(geometry)
geometry.flags = flags
if metaHeader[2] < 0x34001:
(surfAmbient, surfSpecular, surfDiffuse), slice = self.readSlice("fff", slice)
for i in range(vertCount):
geometry.addVertex(self.RwVertex(None, None))
if flags & RpGeomFlag.PRELIT:
geometry.vertCol = []
for i in range(vertCount):
(vcr, vcg, vcb, vca), slice = self.readSlice("BBBB", slice)
geometry.vertCol.append((vcr / 255, vcg / 255, vcb / 255))
for i in range(vertCount):
uv, slice = self.readSlice("ff", slice)
geometry.vertices[i].uv = (uv[0], 1-uv[1])
if texCount > 1:
geometry.hasEnvUV = True
for i in range(vertCount):
uv_env, slice = self.readSlice("ff", slice)
geometry.vertices[i].uv_env = (uv_env[0], 1-uv_env[1])
if texCount > 2:
slice = slice[struct.calcsize("ff")*(texCount-2)*(vertCount):]
for i in range(triCount):
(c, b, mat, a), slice = self.readSlice("HHHH", slice)
if a >= vertCount or b >= vertCount or c >= vertCount:
raise Exception("Vertex indices out of range for triangle.")
geometry.addTriangle(self.RwTriangle((a, b, c), mat))
if morphCount is not 1:
raise Exception("Multiple frames not supported")
for i in range(morphCount):
(bx, by, bz, br, hasVerts, hasNormals), slice = self.readSlice("ffffii", slice)
if hasVerts > 0:
for j in range(vertCount):
coords, slice = self.readSlice("fff", slice)
geometry.vertices[j].coords = coords
if hasNormals > 0:
geometry.hasNormals = True
for j in range(vertCount):
normal, slice = self.readSlice("fff", slice)
geometry.vertices[j].normal = normal
self.readSection(RwTypes.MATERIALLIST, geometry)
self.readSection(RwTypes.EXTENSION, geometry)
return header, None
def readSectionClump(self, header):
metaHeader, slice = self.readSection(RwTypes.STRUCT)
(atomicCount,), slice = self.readSlice("i", slice)
print("header output: ["+str(hex(header[0]))+"]["+str(hex(header[1]))+"]["+str(hex(header[2]))+"]")
smth = str(hex(header[2]))
version = str(smth[2])+"."+str(smth[3])+"."+str(smth[4])+"."+str(smth[5])
print("Reporting RenderWare version: " + version + " ("+smth+")" )
if metaHeader[2] > 0x33000:
(lightCount, cameraCount), slice = self.readSlice("ii", slice)
self.readSection(RwTypes.FRAMELIST)
self.readSection(RwTypes.GEOMETRYLIST)
for i in range(atomicCount):
self.readSection(RwTypes.ATOMIC)
self.readSection(RwTypes.EXTENSION)
return header, None
def readSectionAtomic(self, header):
metaHeader, slice = self.readSection(RwTypes.STRUCT)
(frameIndex, geomIndex, flags, x, x, x, x), slice = self.readSlice("iiBBBBi", slice)
atomic = self.RpAtomic(self, self.frames[frameIndex], self.geoms[geomIndex], flags)
self.readSection(RwTypes.EXTENSION, atomic)
return header, None
def readSectionGeometryList(self, header):
metaHeader, slice = self.readSection(RwTypes.STRUCT)
(geomCount,), slice = self.readSlice("i", slice)
for i in range(geomCount):
self.readSection(RwTypes.GEOMETRY, i)
def readSectionMorphPLG(self, header, geometry):
return header, None
def readSectionBinMeshPLG(self, header, geometry):
slice = self.f.read(header[1])
(type, splits, total), slice = self.readSlice("iii", slice)
if type != 0 and type != 1:
print("Morph PLG section in unknown type - ignoring.")
return header, None
lookup = {}
for i in range(len(geometry.triangles)):
v = geometry.triangles[i].verts
v = list(v)
v.sort()
lookup[tuple(v)] = i
totals = 0
for i in range(splits):
(sub, mat), slice = self.readSlice("ii", slice)
if type == 0:
for j in range(sub//3):
vx, slice = self.readSlice("iii", slice)
vx = list(vx)
vx.sort()
vx = tuple(vx)
if vx in lookup:
geometry.triangles[lookup[vx]].mat = mat
else:
elems = deque()
for j in range(sub):
if len(elems) > 2:
elems.popleft()
(item,), slice = self.readSlice("i", slice)
if len(elems) > 1:
checklist = [elems[0], elems[1], item]
checklist.sort()
check = tuple(checklist)
if check in lookup:
geometry.triangles[lookup[check]].mat = mat
elems.append(item)
return header, None
def readSectionFrameName(self, header, frame):
frame.name = self.f.read(header[1]).decode("ascii")
return header, None
def readSectionCollision(self, header, geometry):
if not self.childrenOf or len(self.childrenOf[0]) is 0:
print("Collision extension - no frame to attach to.")
return header, None
binary = self.f.read(header[1])
self.colhex = base64.b64encode(zlib.compress(binary)).decode("ascii")
return header, None
def readSectionMatEffects(self, header, parent):
if parent.__class__ == self.RpMaterial:
return self.readSectionMaterialMatEffects(header, parent)
elif parent.__class__ == self.RpAtomic:
return self.readSectionAtomicMatEffects(header, parent)
return header, None
def readSectionMaterialMatEffects(self, header, material):
(flags,) = self.readFormat("I")
for i in range(2):
(effectType,) = self.readFormat("I")
if effectType == 0:
continue
elif effectType != 2:
print("Unknown material effect type.")
return header, None
(coefficient, frameBufferAlpha, textured) = self.readFormat("fii")
if textured:
material.readenvmap = True
material.envIntensity = coefficient
self.readSection(RwTypes.TEXTURE, material)
def readSectionAtomicMatEffects(self, header, atomic):
(check,) = self.readFormat("i")
if check != 0:
atomic.matfxpipe = True
return header, None
def readSectionMatSpecular(self, header, material):
slice = self.f.read(header[1])
(intensity,), slice = self.readSlice("f", slice)
specName = ""
for i in range(len(slice)):
if int(slice[i]) == 0:
break
specName += slice[i:i+1].decode("ascii")
texture = self.RwTexture(self, material, specName, 2, intensity)
material.setSpecTexture(texture)
return header, None
def readSectionMatReflection(self, header, material):
slice = self.f.read(header[1])
colour, slice = self.readSlice("fff", slice)
(x, intensity), slice = self.readSlice("ff", slice)
material.setReflection(colour, intensity)
return header, None
def readSectionMeshExtension(self, header, geometry):
slice = self.f.read(header[1])
(hasData,), slice = self.readSlice("i", slice)
if hasData:
print("Mesh extension extension actually has data. Not sure what to do with it.")
return header, None
def readSectionRenderRights(self, header, atomic):
if not hasattr(atomic, "__class__") or atomic.__class__ != self.RpAtomic:
print("Render rights extension is not in the right section, should be in atomic.")
return
slice = self.f.read(header[1])
(plugin, extra), slice = self.readSlice("ii", slice)
atomic.setRenderRights(plugin, extra)
def readSectionHAnimPLG(self, header, frame):
if not hasattr(frame, "__class__") or frame.__class__ != self.RwFrame:
print("HAnim extension is not in the right section, should be in frame.")
return
binary = self.f.read(header[1])
frame.hanimdata = base64.b64encode(zlib.compress(binary)).decode("ascii")
return header, None
def readSectionSkinPLG(self, header, geometry):
if not hasattr(geometry, "__class__") or geometry.__class__ != self.RpGeometry:
print("Skin extension is not in the right section, should be in geometry.")
return
binary = self.f.read(header[1])
geometry.skindata = base64.b64encode(zlib.compress(binary)).decode("ascii")
return header, None
def readSectionNightCols(self, header, geometry):
if not hasattr(geometry, "__class__") or geometry.__class__ != self.RpGeometry:
print("Night vertex colours extension is not in the right section, should be in geometry.")
return
slice = self.f.read(header[1])
(x,), slice = self.readSlice("I", slice)
geometry.nightVertCol = []
for i in range(len(geometry.vertices)):
(vcr, vcg, vcb, vca), slice = self.readSlice("BBBB", slice)
geometry.nightVertCol.append((vcr / 255, vcg / 255, vcb / 255))
return header, None
class ExportRenderware:
class RwChunkHeader:
def __init__(self, type, size):
self.type = type
self.size = size
def bin(self):
return struct.pack("III", self.type, self.size, ExportRenderware.targetVer)
class RwVector3:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def bin(self):
return struct.pack("fff", self.x, self.y, self.z)
class RwRotMatrix:
def __init__(self):
self.m = [1, 0, 0, 0, 1, 0, 0, 0, 1]
def bin(self):
return struct.pack("9f", *self.m)
class RwFrameList:
def __init__(self):
self.R = ExportRenderware
self.frames = []
def bin(self):
payload = struct.pack("i", len(self.frames))
for frame in self.frames:
payload += frame.binraw()
payload = self.R.RwChunkHeader(RwTypes.STRUCT, len(payload)).bin() + payload
for frame in self.frames:
payload += frame.binext()
header = self.R.RwChunkHeader(RwTypes.FRAMELIST, len(payload)).bin()
return header + payload
class RwFrame:
def __init__(self, clump, object, parentFrame):
self.R = ExportRenderware
self.clump = clump
self.object = object
self.index = len(clump.frameList.frames)
clump.frameList.frames.append(self)
self.name = self.object.name
self.parent = parentFrame
self.rotation = self.R.RwRotMatrix()
self.position = self.R.RwVector3(0, 0, 0)
if parentFrame is not None:
ux = object.matrix_local.to_3x3()
self.rotation.m = [ux[0][0], ux[0][1], ux[0][2], ux[1][0], ux[1][1], ux[1][2], ux[2][0], ux[2][1], ux[2][2]]
self.position.x = object.matrix_local.translation[0]
self.position.y = object.matrix_local.translation[1]
self.position.z = object.matrix_local.translation[2]
if str(object.type) == "MESH":
self.atomic = self.R.RpAtomic(self)
elif str(object.type) == "EMPTY":
self.atomic = None
else:
raise Exception("Unsupported object type selected: " + str(object.type))
for child in self.object.children:
if str(object.type) != "MESH" and str(object.type) != "EMPTY":
print("Ignoring object " + object.name + ", type " + object.type)
continue
self.R.RwFrame(self.clump, child, self)
if not clump.colbin:
try:
if len(object.collhex) > 0:
textf = bpy.data.texts[object.collhex].as_string()
clump.colbin = zlib.decompress(base64.b64decode(bytes(textf, "ascii")))
except:
clump.colbin = None
def binraw(self):
payload = self.rotation.bin()
payload += self.position.bin()
payload += struct.pack("ii", -1 if self.parent is None else self.parent.index, 0)
return payload
def binext_name(self):
noname = "noname_"
if self.name[:len(noname)] == noname:
return b""
writename = self.R.unmangleName(self.name)
if len(writename) > 23:
writename = writename[:23]
print("Warning, frame name '", writename , "' truncated to 23 characters.")
payload = struct.pack(str(len(writename)) + "s", bytearray(writename, "ascii"))
header = self.R.RwChunkHeader(RwTypes.FRAMENAME, len(payload)).bin()