chair_exporter.py 8.5 KB

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