Remove bl_options from menus which caused tests to fail
[blender-addons.git] / io_scene_fbx / fbx2json.py
blob487d1884d193066589169ffcf64e8da401d3f5d1
1 #!/usr/bin/env python3
2 # SPDX-FileCopyrightText: 2006-2012 assimp team
3 # SPDX-FileCopyrightText: 2013 Blender Foundation
5 # SPDX-License-Identifier: GPL-2.0-or-later
7 """
8 Usage
9 =====
11 fbx2json [FILES]...
13 This script will write a JSON file for each FBX argument given.
16 Output
17 ======
19 The JSON data is formatted into a list of nested lists of 4 items:
21 ``[id, [data, ...], "data_types", [subtree, ...]]``
23 Where each list may be empty, and the items in
24 the subtree are formatted the same way.
26 data_types is a string, aligned with data that spesifies a type
27 for each property.
29 The types are as follows:
31 * 'Z': - INT8
32 * 'Y': - INT16
33 * 'C': - BOOL
34 * 'I': - INT32
35 * 'F': - FLOAT32
36 * 'D': - FLOAT64
37 * 'L': - INT64
38 * 'R': - BYTES
39 * 'S': - STRING
40 * 'f': - FLOAT32_ARRAY
41 * 'i': - INT32_ARRAY
42 * 'd': - FLOAT64_ARRAY
43 * 'l': - INT64_ARRAY
44 * 'b': - BOOL ARRAY
45 * 'c': - BYTE ARRAY
47 Note that key:value pairs aren't used since the id's are not
48 ensured to be unique.
49 """
52 # ----------------------------------------------------------------------------
53 # FBX Binary Parser
55 from struct import unpack
56 import array
57 import zlib
59 # at the end of each nested block, there is a NUL record to indicate
60 # that the sub-scope exists (i.e. to distinguish between P: and P : {})
61 _BLOCK_SENTINEL_LENGTH = ...
62 _BLOCK_SENTINEL_DATA = ...
63 read_fbx_elem_uint = ...
64 _IS_BIG_ENDIAN = (__import__("sys").byteorder != 'little')
65 _HEAD_MAGIC = b'Kaydara FBX Binary\x20\x20\x00\x1a\x00'
66 from collections import namedtuple
67 FBXElem = namedtuple("FBXElem", ("id", "props", "props_type", "elems"))
68 del namedtuple
71 def read_uint(read):
72 return unpack(b'<I', read(4))[0]
75 def read_uint64(read):
76 return unpack(b'<Q', read(8))[0]
79 def read_ubyte(read):
80 return unpack(b'B', read(1))[0]
83 def read_string_ubyte(read):
84 size = read_ubyte(read)
85 data = read(size)
86 return data
89 def unpack_array(read, array_type, array_stride, array_byteswap):
90 length = read_uint(read)
91 encoding = read_uint(read)
92 comp_len = read_uint(read)
94 data = read(comp_len)
96 if encoding == 0:
97 pass
98 elif encoding == 1:
99 data = zlib.decompress(data)
101 assert(length * array_stride == len(data))
103 data_array = array.array(array_type, data)
104 if array_byteswap and _IS_BIG_ENDIAN:
105 data_array.byteswap()
106 return data_array
109 read_data_dict = {
110 b'Z'[0]: lambda read: unpack(b'<b', read(1))[0], # 8 bit int
111 b'Y'[0]: lambda read: unpack(b'<h', read(2))[0], # 16 bit int
112 b'C'[0]: lambda read: unpack(b'?', read(1))[0], # 1 bit bool (yes/no)
113 b'I'[0]: lambda read: unpack(b'<i', read(4))[0], # 32 bit int
114 b'F'[0]: lambda read: unpack(b'<f', read(4))[0], # 32 bit float
115 b'D'[0]: lambda read: unpack(b'<d', read(8))[0], # 64 bit float
116 b'L'[0]: lambda read: unpack(b'<q', read(8))[0], # 64 bit int
117 b'R'[0]: lambda read: read(read_uint(read)), # binary data
118 b'S'[0]: lambda read: read(read_uint(read)), # string data
119 b'f'[0]: lambda read: unpack_array(read, 'f', 4, False), # array (float)
120 b'i'[0]: lambda read: unpack_array(read, 'i', 4, True), # array (int)
121 b'd'[0]: lambda read: unpack_array(read, 'd', 8, False), # array (double)
122 b'l'[0]: lambda read: unpack_array(read, 'q', 8, True), # array (long)
123 b'b'[0]: lambda read: unpack_array(read, 'b', 1, False), # array (bool)
124 b'c'[0]: lambda read: unpack_array(read, 'B', 1, False), # array (ubyte)
128 # FBX 7500 (aka FBX2016) introduces incompatible changes at binary level:
129 # * The NULL block marking end of nested stuff switches from 13 bytes long to 25 bytes long.
130 # * The FBX element metadata (end_offset, prop_count and prop_length) switch from uint32 to uint64.
131 def init_version(fbx_version):
132 global _BLOCK_SENTINEL_LENGTH, _BLOCK_SENTINEL_DATA, read_fbx_elem_uint
134 assert(_BLOCK_SENTINEL_LENGTH == ...)
135 assert(_BLOCK_SENTINEL_DATA == ...)
137 if fbx_version < 7500:
138 _BLOCK_SENTINEL_LENGTH = 13
139 read_fbx_elem_uint = read_uint
140 else:
141 _BLOCK_SENTINEL_LENGTH = 25
142 read_fbx_elem_uint = read_uint64
143 _BLOCK_SENTINEL_DATA = (b'\0' * _BLOCK_SENTINEL_LENGTH)
146 def read_elem(read, tell, use_namedtuple):
147 # [0] the offset at which this block ends
148 # [1] the number of properties in the scope
149 # [2] the length of the property list
150 end_offset = read_fbx_elem_uint(read)
151 if end_offset == 0:
152 return None
154 prop_count = read_fbx_elem_uint(read)
155 prop_length = read_fbx_elem_uint(read)
157 elem_id = read_string_ubyte(read) # elem name of the scope/key
158 elem_props_type = bytearray(prop_count) # elem property types
159 elem_props_data = [None] * prop_count # elem properties (if any)
160 elem_subtree = [] # elem children (if any)
162 for i in range(prop_count):
163 data_type = read(1)[0]
164 elem_props_data[i] = read_data_dict[data_type](read)
165 elem_props_type[i] = data_type
167 if tell() < end_offset:
168 while tell() < (end_offset - _BLOCK_SENTINEL_LENGTH):
169 elem_subtree.append(read_elem(read, tell, use_namedtuple))
171 if read(_BLOCK_SENTINEL_LENGTH) != _BLOCK_SENTINEL_DATA:
172 raise IOError("failed to read nested block sentinel, "
173 "expected all bytes to be 0")
175 if tell() != end_offset:
176 raise IOError("scope length not reached, something is wrong")
178 args = (elem_id, elem_props_data, elem_props_type, elem_subtree)
179 return FBXElem(*args) if use_namedtuple else args
182 def parse_version(fn):
184 Return the FBX version,
185 if the file isn't a binary FBX return zero.
187 with open(fn, 'rb') as f:
188 read = f.read
190 if read(len(_HEAD_MAGIC)) != _HEAD_MAGIC:
191 return 0
193 return read_uint(read)
196 def parse(fn, use_namedtuple=True):
197 root_elems = []
199 with open(fn, 'rb') as f:
200 read = f.read
201 tell = f.tell
203 if read(len(_HEAD_MAGIC)) != _HEAD_MAGIC:
204 raise IOError("Invalid header")
206 fbx_version = read_uint(read)
207 init_version(fbx_version)
209 while True:
210 elem = read_elem(read, tell, use_namedtuple)
211 if elem is None:
212 break
213 root_elems.append(elem)
215 args = (b'', [], bytearray(0), root_elems)
216 return FBXElem(*args) if use_namedtuple else args, fbx_version
219 # ----------------------------------------------------------------------------
220 # Inline Modules
222 # pyfbx.data_types
223 data_types = type(array)("data_types")
224 data_types.__dict__.update(
225 dict(
226 INT8 = b'Z'[0],
227 INT16 = b'Y'[0],
228 BOOL = b'C'[0],
229 INT32 = b'I'[0],
230 FLOAT32 = b'F'[0],
231 FLOAT64 = b'D'[0],
232 INT64 = b'L'[0],
233 BYTES = b'R'[0],
234 STRING = b'S'[0],
235 FLOAT32_ARRAY = b'f'[0],
236 INT32_ARRAY = b'i'[0],
237 FLOAT64_ARRAY = b'd'[0],
238 INT64_ARRAY = b'l'[0],
239 BOOL_ARRAY = b'b'[0],
240 BYTE_ARRAY = b'c'[0],
243 # pyfbx.parse_bin
244 parse_bin = type(array)("parse_bin")
245 parse_bin.__dict__.update(
246 dict(
247 parse = parse
251 # ----------------------------------------------------------------------------
252 # JSON Converter
253 # from pyfbx import parse_bin, data_types
254 import json
255 import array
258 def fbx2json_property_as_string(prop, prop_type):
259 if prop_type == data_types.STRING:
260 prop_str = prop.decode('utf-8')
261 prop_str = prop_str.replace('\x00\x01', '::')
262 return json.dumps(prop_str)
263 else:
264 prop_py_type = type(prop)
265 if prop_py_type == bytes:
266 return json.dumps(repr(prop)[2:-1])
267 elif prop_py_type == bool:
268 return json.dumps(prop)
269 elif prop_py_type == array.array:
270 return repr(list(prop))
272 return repr(prop)
275 def fbx2json_properties_as_string(fbx_elem):
276 return ", ".join(fbx2json_property_as_string(*prop_item)
277 for prop_item in zip(fbx_elem.props,
278 fbx_elem.props_type))
281 def fbx2json_recurse(fw, fbx_elem, ident, is_last):
282 fbx_elem_id = fbx_elem.id.decode('utf-8')
283 fw('%s["%s", ' % (ident, fbx_elem_id))
284 fw('[%s], ' % fbx2json_properties_as_string(fbx_elem))
285 fw('"%s", ' % (fbx_elem.props_type.decode('ascii')))
287 fw('[')
288 if fbx_elem.elems:
289 fw('\n')
290 ident_sub = ident + " "
291 for fbx_elem_sub in fbx_elem.elems:
292 fbx2json_recurse(fw, fbx_elem_sub, ident_sub,
293 fbx_elem_sub is fbx_elem.elems[-1])
294 fw(']')
296 fw(']%s' % ('' if is_last else ',\n'))
299 def fbx2json(fn):
300 import os
302 fn_json = "%s.json" % os.path.splitext(fn)[0]
303 print("Writing: %r " % fn_json, end="")
304 fbx_root_elem, fbx_version = parse(fn, use_namedtuple=True)
305 print("(Version %d) ..." % fbx_version)
307 with open(fn_json, 'w', encoding="ascii", errors='xmlcharrefreplace') as f:
308 fw = f.write
309 fw('[\n')
310 ident_sub = " "
311 for fbx_elem_sub in fbx_root_elem.elems:
312 fbx2json_recurse(f.write, fbx_elem_sub, ident_sub,
313 fbx_elem_sub is fbx_root_elem.elems[-1])
314 fw(']\n')
317 # ----------------------------------------------------------------------------
318 # Command Line
320 def main():
321 import sys
323 if "--help" in sys.argv:
324 print(__doc__)
325 return
327 for arg in sys.argv[1:]:
328 try:
329 fbx2json(arg)
330 except:
331 print("Failed to convert %r, error:" % arg)
333 import traceback
334 traceback.print_exc()
337 if __name__ == "__main__":
338 main()