chair_exporter.py 7.9 KB

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