chair_exporter.py 9.2 KB

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