chair_exporter.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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, 4),
  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. # TODO: find texture used by this object
  81. vertices = []
  82. vertex_ids = {}
  83. matrix = obj.matrix_world.copy()
  84. for face in me.loop_triangles:
  85. face_to_tris(store_colours, store_normals, store_uvs, face, me, matrix, vertices, vertex_ids, colours, colour_ids, indices)
  86. min_pos = [
  87. min(vertices, key=lambda v: v[0][0])[0][0],
  88. min(vertices, key=lambda v: v[0][1])[0][1],
  89. min(vertices, key=lambda v: v[0][2])[0][2]
  90. ]
  91. max_pos = [
  92. max(vertices, key=lambda v: v[0][0])[0][0],
  93. max(vertices, key=lambda v: v[0][1])[0][1],
  94. max(vertices, key=lambda v: v[0][2])[0][2]
  95. ]
  96. scale = [
  97. max_pos[0] - min_pos[0],
  98. max_pos[1] - min_pos[1],
  99. max_pos[2] - min_pos[2]
  100. ]
  101. objects.append((vertices, scale, min_pos))
  102. # Remove meshes that are created solely for exporting
  103. if is_tmp_mesh:
  104. obj.to_mesh_clear()
  105. return colours, objects, indices
  106. def index_size(vertices):
  107. if vertices < 256:
  108. return 1
  109. if vertices < 65536:
  110. return 2
  111. return 4
  112. def write_vec2_float(f, v):
  113. f.write(bytes(struct.pack("<f", v[0])))
  114. f.write(bytes(struct.pack("<f", 1.0 - v[1])))
  115. def write_vec2_byte(f, v):
  116. x = v[0]
  117. y = v[1]
  118. while x < 0.0:
  119. x += 1.0
  120. while y < 0.0:
  121. y += 1.0
  122. while x > 1.0:
  123. x -= 1.0
  124. while y > 1.0:
  125. y -= 1.0
  126. x = int(x * 128)
  127. # flip y axis
  128. y = 128 - int(y * 128)
  129. f.write(bytes([x, y]))
  130. def write_vec3_float(f, v):
  131. # <f = little-endian float
  132. f.write(bytes(struct.pack("<f", v[0])))
  133. # Y = up in chair/wgpu, Z = up in blender so swap them
  134. f.write(bytes(struct.pack("<f", v[2])))
  135. f.write(bytes(struct.pack("<f", v[1])))
  136. def write_vec3_byte(f, v, scale, offset):
  137. # use range 0-128 to allow for even divisions
  138. x = 128 * (v[0] - offset[0]) / scale[0]
  139. # Y = up in chair/wgpu, Z = up in blender so swap them
  140. y = 128 * (v[2] - offset[2]) / scale[2]
  141. z = 128 * (v[1] - offset[1]) / scale[1]
  142. f.write(bytes([int(x), int(y), int(z)]))
  143. def index_normal(n):
  144. # asin fairly slow but this is pyton so doesnt matter
  145. return 128 + int(math.asin(n) * 255 / math.pi)
  146. def write_vec3_sin(f, v):
  147. x = index_normal(v[0])
  148. # Y = up in chair/wgpu, Z = up in blender so swap them
  149. y = index_normal(v[2])
  150. z = index_normal(v[1])
  151. f.write(bytes([x, y, z]))
  152. def write_model(path, colours, objects, indices, export_colours, export_normals, export_uvs, export_skeleton, short_pos, short_normals, short_uvs, short_weights):
  153. f = open(path, "wb")
  154. # Chair file header
  155. f.write(bytes("CHAIR", "ascii"))
  156. # Format version
  157. f.write(bytes([0]))
  158. # MeshFeatures
  159. features = 0
  160. if export_colours:
  161. features |= 0b0001
  162. if export_normals:
  163. features |= 0b0010
  164. if export_uvs:
  165. features |= 0b0100
  166. if export_skeleton:
  167. features |= 0b1000
  168. if short_pos:
  169. features |= 0b00010000
  170. if short_normals:
  171. features |= 0b00100000
  172. if short_uvs:
  173. features |= 0b01000000
  174. if short_weights:
  175. features |= 0b10000000
  176. f.write(bytes([features]))
  177. if export_colours:
  178. f.write((len(colours)).to_bytes(2, "little"))
  179. for col in colours:
  180. for chan in col:
  181. f.write(bytes([int(chan * 255)]))
  182. if len(colours) > 255:
  183. colour_size = 2
  184. else:
  185. colour_size = 1
  186. # TODO: export texture names
  187. if export_uvs:
  188. f.write(bytes([1, 5]))
  189. f.write(bytes("chair", "ascii"))
  190. # TODO: export skeleton
  191. f.write(bytes([len(objects)]))
  192. for obj in objects:
  193. # Vertices count for this object
  194. f.write(len(obj[0]).to_bytes(4, "little"))
  195. scale = obj[1]
  196. offset = obj[2]
  197. if short_pos:
  198. write_vec3_float(f, scale)
  199. write_vec3_float(f, offset)
  200. write_pos = lambda f, v: write_vec3_byte(f, v, scale, offset)
  201. else:
  202. write_pos = write_vec3_float
  203. if short_normals:
  204. write_normals = write_vec3_sin
  205. else:
  206. write_normals = write_vec3_float
  207. if export_uvs:
  208. f.write(bytes([0]))
  209. if short_uvs:
  210. write_uvs = write_vec2_byte
  211. else:
  212. write_uvs = write_vec2_float
  213. # Write data
  214. for v in obj[0]:
  215. write_pos(f, v[0])
  216. if export_colours:
  217. f.write(v[1].to_bytes(colour_size, "little"))
  218. if export_normals:
  219. write_normals(f, v[2])
  220. if export_uvs:
  221. write_uvs(f, v[3])
  222. # TODO: bone weights
  223. # Indices
  224. f.write(len(indices).to_bytes(4, "little"))
  225. indsize = index_size(sum([len(obj[0]) for obj in objects]))
  226. for i in indices:
  227. f.write(i.to_bytes(indsize, "little"))
  228. f.close()
  229. return
  230. import bpy
  231. from bpy_extras.io_utils import ExportHelper
  232. from bpy.props import StringProperty, BoolProperty
  233. from bpy.types import Operator
  234. class ModelExporter(Operator, ExportHelper):
  235. """Export geometry to chair mesh format (lib.rs/chair)"""
  236. bl_idname = "export.chair"
  237. bl_label = "Export Chair Mesh"
  238. filename_ext = ".chr"
  239. filter_glob: StringProperty(
  240. default = "*.chr",
  241. options = {"HIDDEN"}
  242. )
  243. apply_modifiers: BoolProperty(
  244. name = "Apply Modifiers",
  245. description = "Use transformed mesh data from each object",
  246. default = True
  247. )
  248. export_colours: BoolProperty(
  249. name = "Export Colours",
  250. description = "Save vertex colours in the exported mesh",
  251. default = False
  252. )
  253. export_normals: BoolProperty(
  254. name = "Export Normals",
  255. description = "Save vertex normals in the exported mesh",
  256. default = True
  257. )
  258. export_uvs: BoolProperty(
  259. name = "Export UVs",
  260. description = "Save vertex texture coordinates (and texture names) in the exported mesh",
  261. default = True
  262. )
  263. export_skeleton: BoolProperty(
  264. name = "Export Skeleton",
  265. description = "Save skeleton and vertex bones/weights in the exported mesh",
  266. default = False
  267. )
  268. short_pos: BoolProperty(
  269. name = "Short Positions",
  270. description = "Use bytes -64 to +64 instead of floats to lossily encode vertex positions.\nAlso stores scale + offset of objects",
  271. default = False
  272. )
  273. short_normals: BoolProperty(
  274. name = "Short Normals",
  275. description = "Use a byte sin lookup table instead of floats to lossily encode vertex normals",
  276. default = False
  277. )
  278. short_uvs: BoolProperty(
  279. name = "Short UVs",
  280. description = "Use bytes 0 to 128 instead of floats to lossily encode vertex texture coordinates",
  281. default = False
  282. )
  283. short_weights: BoolProperty(
  284. name = "Short Weights",
  285. description = "Use bytes -64 to +64 instead of floats to lossily encode vertex weights",
  286. default = False
  287. )
  288. def execute(self, context):
  289. colours, objects, indices = process_scene(context, self.apply_modifiers, self.export_colours, self.export_normals, self.export_uvs)
  290. write_model(self.filepath, colours, objects, indices, self.export_colours, self.export_normals, self.export_uvs, self.export_skeleton,
  291. self.short_pos, self.short_normals, self.short_uvs, self.short_weights)
  292. return {"FINISHED"}
  293. def menu_export(self, context):
  294. self.layout.operator(ModelExporter.bl_idname, text = "Chair Mesh (.chr)")
  295. def register():
  296. bpy.utils.register_class(ModelExporter)
  297. bpy.types.TOPBAR_MT_file_export.append(menu_export)
  298. def unregister():
  299. bpy.utils.unregister_class(ModelExporter)
  300. bpy.types.TOPBAR_MT_file_export.remove(menu_export)
  301. if __name__ == "__main__":
  302. register()