chair_exporter.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. # Same as the crate version
  9. "version": (0.1, 0),
  10. "category": "Import-Export"
  11. }
  12. # For normal lookup
  13. import math
  14. # For writing floats
  15. import struct
  16. def face_to_tris(face, mesh, matrix, vertices, vertex_ids, indices):
  17. i = len(vertices)
  18. for verti in face.vertices:
  19. vert = mesh.vertices[verti]
  20. v = [(matrix @ vert.co)[:], (vert.normal)[:]]
  21. key = str(v)
  22. if key in vertex_ids:
  23. i = vertex_ids[key]
  24. else:
  25. # new vertex, push to list
  26. vertices.append(v)
  27. vertex_ids[key] = i
  28. # TODO: general form for n-gons
  29. # Single triangle
  30. indices.append(i)
  31. indices.append(i + 1)
  32. indices.append(i + 2)
  33. if len(face.vertices) == 4:
  34. # Second triangle of quad
  35. indices.append(i)
  36. indices.append(i + 2)
  37. indices.append(i + 3)
  38. def process_scene(context, apply_modifiers):
  39. objects = []
  40. indices = []
  41. scene = context.scene
  42. for obj in context.selected_objects:
  43. me = None
  44. if apply_modifiers or obj.type != "MESH":
  45. try:
  46. me = obj.to_mesh()
  47. except:
  48. me = None
  49. is_tmp_mesh = True
  50. else:
  51. me = obj.data
  52. is_tmp_mesh = False
  53. if me is None:
  54. continue
  55. if not me.loop_triangles and me.polygons:
  56. me.calc_loop_triangles()
  57. # TODO: texture used by this object
  58. vertices = []
  59. vertex_ids = {}
  60. matrix = obj.matrix_world.copy()
  61. for face in me.loop_triangles:
  62. face_to_tris(face, me, matrix, vertices, vertex_ids, indices)
  63. min_pos = [
  64. min(vertices, key=lambda v: v[0][0])[0][0],
  65. min(vertices, key=lambda v: v[0][1])[0][1],
  66. min(vertices, key=lambda v: v[0][2])[0][2]
  67. ]
  68. max_pos = [
  69. max(vertices, key=lambda v: v[0][0])[0][0],
  70. max(vertices, key=lambda v: v[0][1])[0][1],
  71. max(vertices, key=lambda v: v[0][2])[0][2]
  72. ]
  73. scale = [
  74. max_pos[0] - min_pos[0],
  75. max_pos[1] - min_pos[1],
  76. max_pos[2] - min_pos[2]
  77. ]
  78. objects.append((vertices, scale, min_pos))
  79. # Remove meshes that are created solely for exporting
  80. if is_tmp_mesh:
  81. obj.to_mesh_clear()
  82. return objects, indices
  83. def index_size(vertices):
  84. if vertices < 256:
  85. return 1
  86. if vertices < 65536:
  87. return 2
  88. return 4
  89. def write_vec3_float(f, v):
  90. # <f = little-endian float
  91. f.write(bytes(struct.pack("<f", v[0])))
  92. # Y = up in chair/wgpu, Z = up in blender so swap them
  93. f.write(bytes(struct.pack("<f", v[2])))
  94. f.write(bytes(struct.pack("<f", v[1])))
  95. def write_vec3_byte(f, v, scale, offset):
  96. # use range 0-128 to allow for even divisions
  97. x = 128 * (v[0] - offset[0]) / scale[0]
  98. # Y = up in chair/wgpu, Z = up in blender so swap them
  99. y = 128 * (v[2] - offset[2]) / scale[2]
  100. z = 128 * (v[1] - offset[1]) / scale[1]
  101. print("writing float " + str(x) + ", " + str(y) + ", " + str(z))
  102. f.write(bytes([int(x), int(y), int(z)]))
  103. def index_normal(n):
  104. # asin fairly slow but this is pyton so doesnt matter
  105. return 128 + int(math.asin(n) * 255 / math.pi)
  106. def write_vec3_sin(f, v):
  107. x = index_normal(v[0])
  108. # Y = up in chair/wgpu, Z = up in blender so swap them
  109. y = index_normal(v[2])
  110. z = index_normal(v[1])
  111. f.write(bytes([x, y, z]))
  112. def write_model(path, objects, indices, export_colours, export_normals, export_uvs, export_skeleton, short_pos, short_normals, short_uvs, short_weights):
  113. f = open(path, "wb")
  114. # Chair file header
  115. f.write(bytes("CHAIR", "ascii"))
  116. # Format version
  117. f.write(bytes([0]))
  118. # MeshFeatures
  119. features = 0
  120. if export_colours:
  121. features |= 0b0001
  122. if export_normals:
  123. features |= 0b0010
  124. if export_uvs:
  125. features |= 0b0100
  126. if export_skeleton:
  127. features |= 0b1000
  128. if short_pos:
  129. features |= 0b00010000
  130. if short_normals:
  131. features |= 0b00100000
  132. if short_uvs:
  133. features |= 0b01000000
  134. if short_weights:
  135. features |= 0b10000000
  136. f.write(bytes([features]))
  137. # TODO: export unique vertex colours from objects
  138. if export_colours:
  139. f.write((1).to_bytes(2, "little"))
  140. f.write(bytes([255, 255, 255, 255]))
  141. # TODO: export texture names
  142. if export_uvs:
  143. f.write(bytes([1, 5]))
  144. f.write(bytes("error", "ascii"))
  145. # TODO: export skeleton
  146. f.write(bytes([len(objects)]))
  147. for obj in objects:
  148. # Vertices count for this object
  149. f.write(len(obj[0]).to_bytes(4, "little"))
  150. scale = obj[1]
  151. offset = obj[2]
  152. if short_pos:
  153. write_vec3_float(f, scale)
  154. write_vec3_float(f, offset)
  155. write_pos = lambda f, v: write_vec3_byte(f, v, scale, offset)
  156. else:
  157. write_pos = write_vec3_float
  158. if short_normals:
  159. write_normals = write_vec3_sin
  160. else:
  161. write_normals = write_vec3_float
  162. # TODO: texture name index
  163. # Write data
  164. for v in obj[0]:
  165. write_pos(f, v[0])
  166. if export_colours:
  167. # TODO: colour index
  168. f.write(bytes([0]))
  169. if export_normals:
  170. write_normals(f, v[1])
  171. if export_uvs:
  172. # TODO uvs, short uvs
  173. f.write(struct.pack("<f", 0))
  174. f.write(struct.pack("<f", 0))
  175. # TODO: bone weights
  176. # Indices
  177. f.write(len(indices).to_bytes(4, "little"))
  178. indsize = index_size(sum([len(obj[0]) for obj in objects]))
  179. for i in indices:
  180. f.write(i.to_bytes(indsize, "little"))
  181. f.close()
  182. return
  183. import bpy
  184. from bpy_extras.io_utils import ExportHelper
  185. from bpy.props import StringProperty, BoolProperty
  186. from bpy.types import Operator
  187. class ModelExporter(Operator, ExportHelper):
  188. """Export geometry to chair mesh format (lib.rs/chair)"""
  189. bl_idname = "export.chair"
  190. bl_label = "Export Chair Mesh"
  191. filename_ext = ".chr"
  192. filter_glob: StringProperty(
  193. default = "*.chr",
  194. options = {"HIDDEN"}
  195. )
  196. apply_modifiers: BoolProperty(
  197. name = "Apply Modifiers",
  198. description = "Use transformed mesh data from each object",
  199. default = True
  200. )
  201. export_colours: BoolProperty(
  202. name = "Export Colours",
  203. description = "Save vertex colours in the exported mesh",
  204. default = True
  205. )
  206. export_normals: BoolProperty(
  207. name = "Export Normals",
  208. description = "Save vertex normals in the exported mesh",
  209. default = True
  210. )
  211. export_uvs: BoolProperty(
  212. name = "Export UVs",
  213. description = "Save vertex texture coordinates (and texture names) in the exported mesh",
  214. default = False
  215. )
  216. export_skeleton: BoolProperty(
  217. name = "Export Skeleton",
  218. description = "Save skeleton and vertex bones/weights in the exported mesh",
  219. default = False
  220. )
  221. short_pos: BoolProperty(
  222. name = "Short Positions",
  223. description = "Use bytes -64 to +64 instead of floats to lossily encode vertex positions.\nAlso stores scale + offset of objects",
  224. default = False
  225. )
  226. short_normals: BoolProperty(
  227. name = "Short Normals",
  228. description = "Use a byte sin lookup table instead of floats to lossily encode vertex normals",
  229. default = False
  230. )
  231. short_uvs: BoolProperty(
  232. name = "Short UVs",
  233. description = "Use bytes 0 to 128 instead of floats to lossily encode vertex texture coordinates",
  234. default = False
  235. )
  236. short_weights: BoolProperty(
  237. name = "Short Weights",
  238. description = "Use bytes -64 to +64 instead of floats to lossily encode vertex weights",
  239. default = False
  240. )
  241. def execute(self, context):
  242. objects, indices = process_scene(context, self.apply_modifiers)
  243. write_model(self.filepath, objects, indices, self.export_colours, self.export_normals, self.export_uvs, self.export_skeleton,
  244. self.short_pos, self.short_normals, self.short_uvs, self.short_weights)
  245. return {"FINISHED"}
  246. def menu_export(self, context):
  247. self.layout.operator(ModelExporter.bl_idname, text = "Chair Mesh (.chr)")
  248. def register():
  249. bpy.utils.register_class(ModelExporter)
  250. bpy.types.TOPBAR_MT_file_export.append(menu_export)
  251. def unregister():
  252. bpy.utils.unregister_class(ModelExporter)
  253. bpy.types.TOPBAR_MT_file_export.remove(menu_export)
  254. if __name__ == "__main__":
  255. register()