chair_exporter.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. # Blender addon to export an object as a lib.rs/chair mesh file
  2. # To use, select object(s) and export with settings.
  3. # Texture name in the file will be either:
  4. # 1. custom "chair_texture" property on material
  5. # 2. the material's name
  6. # Based on the Raw mesh exporter distributed with blender
  7. bl_info = {
  8. "name": "Chair Mesh Exporter",
  9. "author": "deltanedas",
  10. "blender": (3, 0, 0),
  11. "location": "File > Export > Chair Mesh (.chr)",
  12. # Crate verion 0.2.3
  13. "version": (0, 2, 7),
  14. "category": "Import-Export"
  15. }
  16. # For normal lookup
  17. import math
  18. # For writing floats
  19. import struct
  20. def face_to_tris(cfg, face, mesh, matrix, vertices, vertex_ids, colours, colour_ids, indices):
  21. if cfg.export_uvs:
  22. uvs = mesh.uv_layers.active.data
  23. if cfg.export_colours:
  24. cols = mesh.vertex_colors.active.data
  25. for n in range(3):
  26. verti = face.vertices[n]
  27. loopi = face.loops[n]
  28. vert = mesh.vertices[verti]
  29. loop = mesh.loops[loopi]
  30. if cfg.export_colours:
  31. col = (cols[loopi].color)[:]
  32. # really inefficient but this is pyton so
  33. colkey = str(col)
  34. if colkey in colour_ids:
  35. coli = colour_ids[colkey]
  36. else:
  37. # new colour, push to list
  38. coli = len(colours)
  39. colours.append(col)
  40. colour_ids[colkey] = coli
  41. else:
  42. coli = None
  43. if cfg.export_normals:
  44. normals = (loop.normal)[:]
  45. else:
  46. normals = None
  47. if cfg.export_uvs:
  48. uv = (uvs[loopi].uv)[:]
  49. else:
  50. uv = None
  51. v = [(matrix @ vert.co)[:], coli, normals, uv]
  52. # really inefficient but this is pyton so
  53. key = str(v)
  54. if key in vertex_ids:
  55. i = vertex_ids[key]
  56. else:
  57. # new vertex, push to list
  58. i = len(vertices)
  59. vertices.append(v)
  60. vertex_ids[key] = i
  61. indices.append(i)
  62. def process_scene(cfg, context):
  63. colours = []
  64. colour_ids = {}
  65. textures = []
  66. texture_ids = {}
  67. objects = []
  68. indices = []
  69. scene = context.scene
  70. for obj in context.selected_objects:
  71. me = None
  72. if cfg.apply_modifiers or obj.type != "MESH":
  73. try:
  74. me = obj.to_mesh()
  75. except:
  76. me = None
  77. is_tmp_mesh = True
  78. else:
  79. me = obj.data
  80. is_tmp_mesh = False
  81. if me is None:
  82. continue
  83. if not me.loop_triangles and me.polygons:
  84. me.calc_loop_triangles()
  85. if cfg.export_normals:
  86. me.calc_normals_split()
  87. # TODO: vertex groups split object into its own thing
  88. if cfg.export_uvs:
  89. # get texture name from custom property or use the material name
  90. mat = obj.active_material
  91. if "chair_texutre" in mat:
  92. texture = mat["chair_texture"]
  93. else:
  94. texture = mat.name
  95. if texture in texture_ids:
  96. texturei = texture_ids[texture]
  97. else:
  98. texturei = len(textures)
  99. textures.append(texture)
  100. texture_ids[texture] = texturei
  101. else:
  102. texturei = None
  103. vertices = []
  104. vertex_ids = {}
  105. matrix = obj.matrix_world.copy()
  106. for face in me.loop_triangles:
  107. face_to_tris(cfg, face, me, matrix, vertices, vertex_ids, colours, colour_ids, indices)
  108. min_pos = [
  109. min(vertices, key=lambda v: v[0][0])[0][0],
  110. min(vertices, key=lambda v: v[0][1])[0][1],
  111. min(vertices, key=lambda v: v[0][2])[0][2]
  112. ]
  113. max_pos = [
  114. max(vertices, key=lambda v: v[0][0])[0][0],
  115. max(vertices, key=lambda v: v[0][1])[0][1],
  116. max(vertices, key=lambda v: v[0][2])[0][2]
  117. ]
  118. scale = [
  119. max_pos[0] - min_pos[0],
  120. max_pos[1] - min_pos[1],
  121. max_pos[2] - min_pos[2]
  122. ]
  123. objects.append((vertices, scale, min_pos, texturei))
  124. # Remove meshes that are created solely for exporting
  125. if is_tmp_mesh:
  126. obj.to_mesh_clear()
  127. return colours, textures, objects, indices
  128. def index_size(vertices):
  129. if vertices < 256:
  130. return 1
  131. if vertices < 65536:
  132. return 2
  133. return 4
  134. def write_vec2_float(f, v):
  135. f.write(bytes(struct.pack("<f", v[0])))
  136. f.write(bytes(struct.pack("<f", 1.0 - v[1])))
  137. def write_vec2_byte(f, v):
  138. x = v[0]
  139. y = v[1]
  140. while x < 0.0:
  141. x += 1.0
  142. while y < 0.0:
  143. y += 1.0
  144. while x > 1.0:
  145. x -= 1.0
  146. while y > 1.0:
  147. y -= 1.0
  148. x = int(x * 128)
  149. # flip y axis
  150. y = 128 - int(y * 128)
  151. f.write(bytes([x, y]))
  152. def write_vec3_float(f, v):
  153. # <f = little-endian float
  154. f.write(bytes(struct.pack("<f", v[0])))
  155. # Y = up in chair/wgpu, Z = up in blender so swap them
  156. f.write(bytes(struct.pack("<f", v[2])))
  157. f.write(bytes(struct.pack("<f", v[1])))
  158. def write_vec3_byte(f, v, scale, offset):
  159. # use range 0-128 to allow for even divisions
  160. x = 128 * (v[0] - offset[0]) / scale[0]
  161. # Y = up in chair/wgpu, Z = up in blender so swap them
  162. y = 128 * (v[2] - offset[2]) / scale[2]
  163. z = 128 * (v[1] - offset[1]) / scale[1]
  164. f.write(bytes([int(x), int(y), int(z)]))
  165. tau = math.pi * 2
  166. def index_normal(n):
  167. if n == 0:
  168. # exact mapping of 0 to 0.0 with no error
  169. return 0
  170. # asin fairly slow but this is pyton so doesnt matter
  171. return 128 - int(math.asin(n) * 255 / tau)
  172. def write_vec3_sin(f, v):
  173. x = index_normal(v[0])
  174. # Y = up in chair/wgpu, Z = up in blender so swap them
  175. y = index_normal(v[2])
  176. z = index_normal(v[1])
  177. f.write(bytes([x, y, z]))
  178. def write_model(cfg, colours, textures, objects, indices):
  179. f = open(cfg.filepath, "wb")
  180. # Chair file header
  181. f.write(b"CHAIR")
  182. # Format version
  183. f.write(bytes([0]))
  184. # MeshFeatures
  185. features = 0
  186. if cfg.export_colours:
  187. features |= 0b0001
  188. if cfg.export_normals:
  189. features |= 0b0010
  190. if cfg.export_uvs:
  191. features |= 0b0100
  192. if cfg.export_skeleton:
  193. features |= 0b1000
  194. if cfg.short_pos:
  195. features |= 0b00010000
  196. if cfg.short_normals:
  197. features |= 0b00100000
  198. if cfg.short_uvs:
  199. features |= 0b01000000
  200. if cfg.short_weights:
  201. features |= 0b10000000
  202. f.write(bytes([features]))
  203. if cfg.export_colours:
  204. f.write((len(colours)).to_bytes(2, "little"))
  205. for col in colours:
  206. for chan in col:
  207. f.write(bytes([int(chan * 255)]))
  208. if len(colours) > 255:
  209. colour_size = 2
  210. else:
  211. colour_size = 1
  212. if cfg.export_uvs:
  213. if len(textures) > 255:
  214. raise "Too many textures"
  215. f.write(bytes([len(textures)]))
  216. for texture in textures:
  217. name = texture.encode("utf-8")
  218. count = len(name)
  219. if count > 255:
  220. raise "Texture name " + texture + " is too long"
  221. f.write(bytes([count]))
  222. f.write(name)
  223. # TODO: export skeleton
  224. f.write(bytes([len(objects)]))
  225. for obj in objects:
  226. # Vertices count for this object
  227. f.write(len(obj[0]).to_bytes(4, "little"))
  228. scale = obj[1]
  229. offset = obj[2]
  230. if cfg.short_pos:
  231. write_vec3_float(f, scale)
  232. write_vec3_float(f, offset)
  233. write_pos = lambda f, v: write_vec3_byte(f, v, scale, offset)
  234. else:
  235. write_pos = write_vec3_float
  236. if cfg.short_normals:
  237. write_normals = write_vec3_sin
  238. else:
  239. write_normals = write_vec3_float
  240. if cfg.export_uvs:
  241. texture = obj[3]
  242. f.write(bytes([texture]))
  243. if cfg.short_uvs:
  244. write_uvs = write_vec2_byte
  245. else:
  246. write_uvs = write_vec2_float
  247. # Write data
  248. for v in obj[0]:
  249. write_pos(f, v[0])
  250. if cfg.export_colours:
  251. f.write(v[1].to_bytes(colour_size, "little"))
  252. if cfg.export_normals:
  253. write_normals(f, v[2])
  254. if cfg.export_uvs:
  255. write_uvs(f, v[3])
  256. # TODO: bone weights
  257. # Indices
  258. f.write(len(indices).to_bytes(4, "little"))
  259. indsize = index_size(sum([len(obj[0]) for obj in objects]))
  260. if cfg.flip_winding:
  261. for i in range(0, int(len(indices) / 3)):
  262. n = i * 3
  263. f.write(indices[n + 1].to_bytes(indsize, "little"))
  264. f.write(indices[n].to_bytes(indsize, "little"))
  265. f.write(indices[n + 2].to_bytes(indsize, "little"))
  266. else:
  267. for i in indices:
  268. f.write(i.to_bytes(indsize, "little"))
  269. f.close()
  270. return
  271. import bpy
  272. from bpy_extras.io_utils import ExportHelper
  273. from bpy.props import StringProperty, BoolProperty
  274. from bpy.types import Operator
  275. class ModelExporter(Operator, ExportHelper):
  276. """Export geometry to chair mesh format (lib.rs/chair)"""
  277. bl_idname = "export.chair"
  278. bl_label = "Export Chair Mesh"
  279. filename_ext = ".chr"
  280. filter_glob: StringProperty(
  281. default = "*.chr",
  282. options = {"HIDDEN"}
  283. )
  284. apply_modifiers: BoolProperty(
  285. name = "Apply Modifiers",
  286. description = "Use transformed mesh data from each object",
  287. default = True
  288. )
  289. export_colours: BoolProperty(
  290. name = "Export Colours",
  291. description = "Save vertex colours in the exported mesh",
  292. default = False
  293. )
  294. export_normals: BoolProperty(
  295. name = "Export Normals",
  296. description = "Save vertex normals in the exported mesh",
  297. default = True
  298. )
  299. export_uvs: BoolProperty(
  300. name = "Export UVs",
  301. description = "Save vertex texture coordinates (and texture names) in the exported mesh",
  302. default = True
  303. )
  304. export_skeleton: BoolProperty(
  305. name = "Export Skeleton",
  306. description = "Save skeleton and vertex bones/weights in the exported mesh",
  307. default = False
  308. )
  309. short_pos: BoolProperty(
  310. name = "Short Positions",
  311. description = "Use bytes -64 to +64 instead of floats to lossily encode vertex positions.\nAlso stores scale + offset of objects",
  312. default = False
  313. )
  314. short_normals: BoolProperty(
  315. name = "Short Normals",
  316. description = "Use a byte sin lookup table instead of floats to lossily encode vertex normals",
  317. default = False
  318. )
  319. short_uvs: BoolProperty(
  320. name = "Short UVs",
  321. description = "Use bytes 0 to 128 instead of floats to lossily encode vertex texture coordinates",
  322. default = False
  323. )
  324. short_weights: BoolProperty(
  325. name = "Short Weights",
  326. description = "Use bytes -64 to +64 instead of floats to lossily encode vertex weights",
  327. default = False
  328. )
  329. flip_winding: BoolProperty(
  330. name = "Flip Winding",
  331. description = "Flip vertex winding from CCW to CW",
  332. default = False
  333. )
  334. def execute(self, context):
  335. colours, textures, objects, indices = process_scene(self, context)
  336. write_model(self, colours, textures, objects, indices)
  337. return {"FINISHED"}
  338. def menu_export(self, context):
  339. self.layout.operator(ModelExporter.bl_idname, text = "Chair Mesh (.chr)")
  340. def register():
  341. bpy.utils.register_class(ModelExporter)
  342. bpy.types.TOPBAR_MT_file_export.append(menu_export)
  343. def unregister():
  344. bpy.utils.unregister_class(ModelExporter)
  345. bpy.types.TOPBAR_MT_file_export.remove(menu_export)
  346. if __name__ == "__main__":
  347. register()