-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSPKToOBJ.py
More file actions
174 lines (142 loc) · 5.78 KB
/
SPKToOBJ.py
File metadata and controls
174 lines (142 loc) · 5.78 KB
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
import struct, os, sys, math
# Helper for binary reading
def readpack(f, fmt):
return struct.unpack("<" + fmt, f.read(struct.calcsize("<" + fmt)))
# Chunk Class
class Chunk:
def __init__(self):
self.tag = b"No:("
self.haschildren = False
self.hasmultidata = False
self.children = []
self.file = None
self.offset = 0
self.size = 0
self.string = ""
def FindSubchunk(self, tagtofind):
for c in self.children:
if c.tag == tagtofind:
return c
return None
def Read(self):
self.file.seek(self.offset + 8, os.SEEK_SET)
return self.file.read(self.size - 8)
# Recursive function for reading chunks
def EnumChunk(f, chk):
o = f.tell()
chktype, chkinfo = readpack(f, "4sI")
chksize = chkinfo & 0x3FFFFFFF
hassub = (chkinfo & 0x80000000) != 0
hasmultidata = (chkinfo & 0x40000000) != 0
chk.tag = chktype
chk.offset = o
chk.size = chksize
chk.haschildren = hassub
chk.hasmultidata = hasmultidata
chk.children = []
chk.file = f
if hassub:
siz2, nchunks = readpack(f, "II")
if hasmultidata:
ndatas, = readpack(f, "I")
f.seek(4 * ndatas, os.SEEK_CUR)
for _ in range(nchunks):
c = Chunk()
EnumChunk(f, c)
chk.children.append(c)
elif chktype == b"PEXC":
while f.tell() < (o + chksize):
c = Chunk()
EnumChunk(f, c)
chk.children.append(c)
f.seek(o + chksize, os.SEEK_SET)
# Function to save an object as .OBJ
def save_obj(name, vertices, faces, output_folder):
filename = os.path.join(output_folder, f"{name}.obj")
with open(filename, "w", encoding="utf-8") as out:
out.write(f"# Exported from SPK\n")
for v in vertices:
out.write(f"v {v[0]} {v[1]} {v[2]}\n")
for face_indices in faces:
# Faces in OBJ start at index 1
out.write(f"f {' '.join(str(i + 1) for i in face_indices)}\n")
print(f"Saved: {filename}")
# Main parsing and export function
def parse_spk(filename, output_folder="exported_objs"):
os.makedirs(output_folder, exist_ok=True)
try:
with open(filename, "rb") as spkfile:
root = Chunk()
EnumChunk(spkfile, root)
prot = root.FindSubchunk(b"PROT")
pclp = root.FindSubchunk(b"PCLP")
if not prot or not pclp:
print("SPK file does not contain PROT/PCLP chunks.")
return
def readchunk(tag):
c = root.FindSubchunk(tag)
return c.Read() if c else b""
phea = readchunk(b"PHEA")
pnam = readchunk(b"PNAM")
ppos = readchunk(b"PPOS")
pver = readchunk(b"PVER")
pfac = readchunk(b"PFAC")
# pmtx is unused but kept for completeness based on original logic
pmtx = readchunk(b"PMTX")
mshdict = {}
def EnumProt(p, parent_name=None):
heado, = struct.unpack("<I", p.tag)
heado &= 0xFFFFFF
nameo, = struct.unpack("<I", phea[(heado + 8):(heado + 12)])
# Reads the object name
s = ""
o = nameo
while o < len(pnam) and pnam[o] != 0:
s += chr(pnam[o])
o += 1
o = heado
objtype, objflags = struct.unpack("<HH", phea[o + 20:o + 24])
mtxo, po, = struct.unpack("<II", phea[o + 12:o + 20])
# position is unused in export but kept for reference
position = struct.unpack("<fff", ppos[po:po + 12])
# If it has geometry (mesh)
if objflags & 0x0020:
vertstart, quadstart, tristart, ftxo, numverts, numquads, numtris = struct.unpack("<7I", phea[o + 0x18:o + 0x34])
if (numverts > 0) and (numquads > 0 or numtris > 0):
key = (vertstart, quadstart, tristart, numverts)
if key in mshdict:
vertices, faces = mshdict[key]
else:
vertices = []
faces = []
for i in range(numverts):
a = vertstart * 4 + i * 12
u = struct.unpack("<fff", pver[a:a + 12])
vertices.append((u[0], u[2], u[1])) # reorders axes (X, Z, Y -> X, Y, Z for standard Z-up)
# Read Quad faces
for i in range(numquads):
a = (quadstart + i * 4) * 2
faces.append([x // 2 for x in struct.unpack("<4H", pfac[a:a + 8])])
# Read Tri faces
for i in range(numtris):
a = (tristart + i * 3) * 2
faces.append([x // 2 for x in struct.unpack("<3H", pfac[a:a + 6])])
mshdict[key] = (vertices, faces)
save_obj(s, vertices, faces, output_folder)
for c in p.children:
EnumProt(c, s)
# Export everything
for p in (prot, pclp):
for c in p.children:
EnumProt(c)
print("Conversion complete!")
except FileNotFoundError:
print(f"Error: File not found at '{filename}'.")
except Exception as e:
print(f"An unexpected error occurred during parsing: {e}")
# Execution from terminal
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python SPKToOBJ.py <file.SPK>")
sys.exit(1)
parse_spk(sys.argv[1])