io_export_babylon.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  1. bl_info = {
  2. "name": "Babylon.js",
  3. "author": "David Catuhe",
  4. "version": (1, 1),
  5. "blender": (2, 67, 0),
  6. "location": "File > Export > Babylon.js (.babylon)",
  7. "description": "Export Babylon.js scenes (.babylon)",
  8. "warning": "",
  9. "wiki_url": "",
  10. "tracker_url": "",
  11. "category": "Import-Export"}
  12. import math
  13. import os
  14. import bpy
  15. import string
  16. import bpy_extras.io_utils
  17. from bpy.props import *
  18. import mathutils, math
  19. import struct
  20. import shutil
  21. from os import remove
  22. from bpy_extras.io_utils import (ExportHelper, axis_conversion)
  23. from bpy.props import (BoolProperty, FloatProperty, StringProperty, EnumProperty, FloatVectorProperty)
  24. from math import radians
  25. from mathutils import *
  26. MAX_VERTICES = 65535
  27. class SubMesh:
  28. materialIndex = 0
  29. verticesStart = 0
  30. verticesCount = 0
  31. indexStart = 0
  32. indexCount = 0
  33. class MultiMaterial:
  34. name = ""
  35. materials = []
  36. class Export_babylon(bpy.types.Operator, ExportHelper):
  37. """Export Babylon.js scene (.babylon)"""
  38. bl_idname = "scene.babylon"
  39. bl_label = "Export Babylon.js scene"
  40. filename_ext = ".babylon"
  41. filepath = ""
  42. # global_scale = FloatProperty(name="Scale", min=0.01, max=1000.0, default=1.0)
  43. def execute(self, context):
  44. return Export_babylon.save(self, context, **self.as_keywords(ignore=("check_existing", "filter_glob", "global_scale")))
  45. def mesh_triangulate(mesh):
  46. try:
  47. import bmesh
  48. bm = bmesh.new()
  49. bm.from_mesh(mesh)
  50. bmesh.ops.triangulate(bm, faces=bm.faces)
  51. bm.to_mesh(mesh)
  52. mesh.calc_tessface()
  53. bm.free()
  54. except:
  55. pass
  56. def write_matrix4(file_handler, name, matrix):
  57. file_handler.write(",\""+name+"\":[")
  58. tempMatrix = matrix.copy()
  59. tempMatrix.transpose()
  60. first = True
  61. for vect in tempMatrix:
  62. if (first != True):
  63. file_handler.write(",")
  64. first = False;
  65. file_handler.write("%.4f,%.4f,%.4f,%.4f"%(vect[0],vect[1], vect[2], vect[3]))
  66. file_handler.write("]")
  67. def write_array3(file_handler, name, array):
  68. file_handler.write(",\""+name+"\":[" + "%.4f,%.4f,%.4f"%(array[0],array[1],array[2]) + "]")
  69. def write_color(file_handler, name, color):
  70. file_handler.write(",\""+name+"\":[" + "%.4f,%.4f,%.4f"%(color.r,color.g,color.b) + "]")
  71. def write_vector(file_handler, name, vector):
  72. file_handler.write(",\""+name+"\":[" + "%.4f,%.4f,%.4f"%(vector.x,vector.z,vector.y) + "]")
  73. def write_quaternion(file_handler, name, quaternion):
  74. file_handler.write(",\""+name+"\":[" + "%.4f,%.4f,%.4f,%.4f"%(quaternion.x,quaternion.z,quaternion.y, -quaternion.w) + "]")
  75. def write_vectorScaled(file_handler, name, vector, mult):
  76. file_handler.write(",\""+name+"\":[" + "%.4f,%.4f,%.4f"%(vector.x * mult, vector.z * mult, vector.y * mult) + "]")
  77. def write_string(file_handler, name, string, noComma=False):
  78. if noComma == False:
  79. file_handler.write(",")
  80. file_handler.write("\""+name+"\":\"" + string + "\"")
  81. def write_float(file_handler, name, float):
  82. file_handler.write(",\""+name+"\":" + "%.4f"%(float))
  83. def write_int(file_handler, name, int, noComma=False):
  84. if noComma == False:
  85. file_handler.write(",")
  86. file_handler.write("\""+name+"\":" + str(int))
  87. def write_bool(file_handler, name, bool, noComma=False):
  88. if noComma == False:
  89. file_handler.write(",")
  90. if bool:
  91. file_handler.write("\""+name+"\":" + "true")
  92. else:
  93. file_handler.write("\""+name+"\":" + "false")
  94. def getDirection(matrix):
  95. return (matrix.to_3x3() * mathutils.Vector((0.0, 0.0, -1.0))).normalized()
  96. def export_camera(object, scene, file_handler):
  97. rotation = mathutils.Vector((-object.rotation_euler[0] + math.pi / 2,
  98. object.rotation_euler[1], -object.rotation_euler[2]))
  99. file_handler.write("{")
  100. Export_babylon.write_string(file_handler, "name", object.name, True)
  101. Export_babylon.write_string(file_handler, "id", object.name)
  102. Export_babylon.write_vector(file_handler, "position", object.location)
  103. Export_babylon.write_vector(file_handler, "rotation", rotation)
  104. Export_babylon.write_float(file_handler, "fov", object.data.angle)
  105. Export_babylon.write_float(file_handler, "minZ", object.data.clip_start)
  106. Export_babylon.write_float(file_handler, "maxZ", object.data.clip_end)
  107. Export_babylon.write_float(file_handler, "speed", 1.0)
  108. Export_babylon.write_float(file_handler, "inertia", 0.9)
  109. Export_babylon.write_bool(file_handler, "checkCollisions", object.data.checkCollisions)
  110. Export_babylon.write_bool(file_handler, "applyGravity", object.data.applyGravity)
  111. Export_babylon.write_array3(file_handler, "ellipsoid", object.data.ellipsoid)
  112. locAnim = False
  113. coma = False
  114. if object.animation_data:
  115. if object.animation_data.action:
  116. file_handler.write(",\"animations\":[")
  117. for fcurve in object.animation_data.action.fcurves:
  118. if fcurve.data_path == "location" and locAnim == False:
  119. Export_babylon.export_animation(object, scene, file_handler, "location", "position", coma, 1)
  120. locAnim = coma = True
  121. file_handler.write("]")
  122. #Set Animations
  123. Export_babylon.write_bool(file_handler, "autoAnimate", True)
  124. Export_babylon.write_int(file_handler, "autoAnimateFrom", 0)
  125. Export_babylon.write_int(file_handler, "autoAnimateTo", bpy.context.scene.frame_end - bpy.context.scene.frame_start + 1)
  126. Export_babylon.write_bool(file_handler, "autoAnimateLoop", True)
  127. file_handler.write("}")
  128. def export_light(object, scene, file_handler):
  129. light_type_items = {'POINT': 0, 'SUN': 1, 'SPOT': 2, 'HEMI': 3, 'AREA': 0}
  130. light_type = light_type_items[object.data.type]
  131. file_handler.write("{")
  132. Export_babylon.write_string(file_handler, "name", object.name, True)
  133. Export_babylon.write_string(file_handler, "id", object.name)
  134. Export_babylon.write_float(file_handler, "type", light_type)
  135. if light_type == 0:
  136. Export_babylon.write_vector(file_handler, "position", object.location)
  137. elif light_type == 1:
  138. direction = Export_babylon.getDirection(object.matrix_world)
  139. Export_babylon.write_vector(file_handler, "position", object.location)
  140. Export_babylon.write_vector(file_handler, "direction", direction)
  141. elif light_type == 2:
  142. Export_babylon.write_vector(file_handler, "position", object.location)
  143. direction = Export_babylon.getDirection(object.matrix_world)
  144. Export_babylon.write_vector(file_handler, "direction", direction)
  145. Export_babylon.write_float(file_handler, "angle", object.data.spot_size)
  146. Export_babylon.write_float(file_handler, "exponent", object.data.spot_blend * 2)
  147. else:
  148. matrix_world = object.matrix_world.copy()
  149. matrix_world.translation = mathutils.Vector((0, 0, 0))
  150. direction = mathutils.Vector((0, 0, -1)) * matrix_world
  151. Export_babylon.write_vector(file_handler, "direction", -direction)
  152. Export_babylon.write_color(file_handler, "groundColor", mathutils.Color((0, 0, 0)))
  153. Export_babylon.write_float(file_handler, "intensity", object.data.energy)
  154. if object.data.use_diffuse:
  155. Export_babylon.write_color(file_handler, "diffuse", object.data.color)
  156. else:
  157. Export_babylon.write_color(file_handler, "diffuse", mathutils.Color((0, 0, 0)))
  158. if object.data.use_specular:
  159. Export_babylon.write_color(file_handler, "specular", object.data.color)
  160. else:
  161. Export_babylon.write_color(file_handler, "specular", mathutils.Color((0, 0, 0)))
  162. file_handler.write("}")
  163. def export_texture(slot, level, texture, scene, file_handler, filepath):
  164. # Copy image to output
  165. try:
  166. image = texture.texture.image
  167. imageFilepath = os.path.normpath(bpy.path.abspath(image.filepath))
  168. basename = os.path.basename(imageFilepath)
  169. targetdir = os.path.dirname(filepath)
  170. targetpath = os.path.join(targetdir, basename)
  171. if image.packed_file:
  172. image.save_render(targetpath)
  173. else:
  174. sourcepath = bpy.path.abspath(image.filepath)
  175. shutil.copy(sourcepath, targetdir)
  176. except:
  177. pass
  178. # Export
  179. file_handler.write(",\""+slot+"\":{")
  180. Export_babylon.write_string(file_handler, "name", basename, True)
  181. Export_babylon.write_float(file_handler, "level", level)
  182. Export_babylon.write_float(file_handler, "hasAlpha", texture.texture.use_alpha)
  183. coordinatesMode = 0;
  184. if (texture.mapping == "CUBE"):
  185. coordinatesMode = 3;
  186. if (texture.mapping == "SPHERE"):
  187. coordinatesMode = 1;
  188. Export_babylon.write_int(file_handler, "coordinatesMode", coordinatesMode)
  189. Export_babylon.write_float(file_handler, "uOffset", texture.offset.x)
  190. Export_babylon.write_float(file_handler, "vOffset", texture.offset.y)
  191. Export_babylon.write_float(file_handler, "uScale", texture.scale.x)
  192. Export_babylon.write_float(file_handler, "vScale", texture.scale.y)
  193. Export_babylon.write_float(file_handler, "uAng", 0)
  194. Export_babylon.write_float(file_handler, "vAng", 0)
  195. Export_babylon.write_float(file_handler, "wAng", 0)
  196. if (texture.texture.extension == "REPEAT"):
  197. Export_babylon.write_bool(file_handler, "wrapU", True)
  198. Export_babylon.write_bool(file_handler, "wrapV", True)
  199. else:
  200. Export_babylon.write_bool(file_handler, "wrapU", False)
  201. Export_babylon.write_bool(file_handler, "wrapV", False)
  202. Export_babylon.write_int(file_handler, "coordinatesIndex", 0)
  203. file_handler.write("}")
  204. def export_material(material, scene, file_handler, filepath):
  205. file_handler.write("{")
  206. Export_babylon.write_string(file_handler, "name", material.name, True)
  207. Export_babylon.write_string(file_handler, "id", material.name)
  208. Export_babylon.write_color(file_handler, "ambient", material.ambient * material.diffuse_color)
  209. Export_babylon.write_color(file_handler, "diffuse", material.diffuse_intensity * material.diffuse_color)
  210. Export_babylon.write_color(file_handler, "specular", material.specular_intensity * material.specular_color)
  211. Export_babylon.write_float(file_handler, "specularPower", material.specular_hardness)
  212. Export_babylon.write_color(file_handler, "emissive", material.emit * material.diffuse_color)
  213. Export_babylon.write_float(file_handler, "alpha", material.alpha)
  214. Export_babylon.write_bool(file_handler, "backFaceCulling", material.game_settings.use_backface_culling)
  215. # Textures
  216. for mtex in material.texture_slots:
  217. if mtex and mtex.texture and mtex.texture.type == 'IMAGE':
  218. if mtex.texture.image:
  219. if (mtex.use_map_color_diffuse and(mtex.texture_coords != 'REFLECTION')):
  220. # Diffuse
  221. Export_babylon.export_texture("diffuseTexture", mtex.diffuse_color_factor, mtex, scene, file_handler, filepath)
  222. if mtex.use_map_ambient:
  223. # Ambient
  224. Export_babylon.export_texture("ambientTexture", mtex.ambient_factor, mtex, scene, file_handler, filepath)
  225. if mtex.use_map_alpha:
  226. # Opacity
  227. Export_babylon.export_texture("opacityTexture", mtex.alpha_factor, mtex, scene, file_handler, filepath)
  228. if mtex.use_map_color_diffuse and (mtex.texture_coords == 'REFLECTION'):
  229. # Reflection
  230. Export_babylon.export_texture("reflectionTexture", mtex.diffuse_color_factor, mtex, scene, file_handler, filepath)
  231. if mtex.use_map_emit:
  232. # Emissive
  233. Export_babylon.export_texture("emissiveTexture", mtex.emit_factor, mtex, scene, file_handler, filepath)
  234. if mtex.use_map_normal:
  235. # Bump
  236. Export_babylon.export_texture("bumpTexture", mtex.emit_factor, mtex, scene, file_handler, filepath)
  237. file_handler.write("}")
  238. def export_multimaterial(multimaterial, scene, file_handler):
  239. file_handler.write("{")
  240. Export_babylon.write_string(file_handler, "name", multimaterial.name, True)
  241. Export_babylon.write_string(file_handler, "id", multimaterial.name)
  242. file_handler.write(",\"materials\":[")
  243. first = True
  244. for materialName in multimaterial.materials:
  245. if first != True:
  246. file_handler.write(",")
  247. file_handler.write("\"" + materialName +"\"")
  248. first = False
  249. file_handler.write("]")
  250. file_handler.write("}")
  251. def export_animation(object, scene, file_handler, typeBl, typeBa, coma, mult):
  252. if coma == True:
  253. file_handler.write(",")
  254. file_handler.write("{")
  255. Export_babylon.write_int(file_handler, "dataType", 1, True)
  256. Export_babylon.write_int(file_handler, "framePerSecond", 30)
  257. Export_babylon.write_int(file_handler, "loopBehavior", 1)
  258. Export_babylon.write_string(file_handler, "name", typeBa+" animation")
  259. Export_babylon.write_string(file_handler, "property", typeBa)
  260. file_handler.write(",\"keys\":[")
  261. frames = dict()
  262. for fcurve in object.animation_data.action.fcurves:
  263. if fcurve.data_path == typeBl:
  264. for key in fcurve.keyframe_points:
  265. frame = key.co.x
  266. frames[frame] = 1
  267. #for each frame (next step ==> set for key frames)
  268. i = 0
  269. for Frame in sorted(frames):
  270. if i == 0 and Frame != 0.0:
  271. file_handler.write("{")
  272. Export_babylon.write_int(file_handler, "frame", 0, True)
  273. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  274. Export_babylon.write_vectorScaled(file_handler, "values", getattr(object,typeBl), mult)
  275. file_handler.write("},")
  276. i = i + 1
  277. file_handler.write("{")
  278. Export_babylon.write_int(file_handler, "frame", Frame, True)
  279. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  280. Export_babylon.write_vectorScaled(file_handler, "values", getattr(object,typeBl), mult)
  281. file_handler.write("}")
  282. if i != len(frames):
  283. file_handler.write(",")
  284. else:
  285. file_handler.write(",{")
  286. Export_babylon.write_int(file_handler, "frame", bpy.context.scene.frame_end - bpy.context.scene.frame_start + 1, True)
  287. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  288. Export_babylon.write_vectorScaled(file_handler, "values", getattr(object,typeBl), mult)
  289. file_handler.write("}")
  290. file_handler.write("]}")
  291. def export_mesh(object, scene, file_handler, multiMaterials, startFace, forcedParent, nameID):
  292. # Get mesh
  293. mesh = object.to_mesh(scene, True, "PREVIEW")
  294. # Transform
  295. loc = mathutils.Vector((0, 0, 0))
  296. rot = mathutils.Quaternion((0, 0, 0, -1))
  297. scale = mathutils.Vector((1, 1, 1))
  298. hasSkeleton = False
  299. world = object.matrix_world
  300. if object.parent and object.parent.type == "ARMATURE" and len(object.vertex_groups) > 0:
  301. hasSkeleton = True
  302. else:
  303. if (object.parent):
  304. world = object.parent.matrix_world.inverted() * object.matrix_world
  305. loc, rot, scale = world.decompose()
  306. # Triangulate mesh if required
  307. Export_babylon.mesh_triangulate(mesh)
  308. # Getting vertices and indices
  309. positions=",\"positions\":["
  310. normals=",\"normals\":["
  311. indices=",\"indices\":["
  312. hasUV = True;
  313. hasUV2 = True;
  314. hasVertexColor = True
  315. if len(mesh.tessface_uv_textures) > 0:
  316. UVmap=mesh.tessface_uv_textures[0].data
  317. uvs=",\"uvs\":["
  318. else:
  319. hasUV = False
  320. if len(mesh.tessface_uv_textures) > 1:
  321. UV2map=mesh.tessface_uv_textures[1].data
  322. uvs2=",\"uvs2\":["
  323. else:
  324. hasUV2 = False
  325. if len(mesh.vertex_colors) > 0:
  326. Colormap = mesh.tessface_vertex_colors.active.data
  327. colors=",\"colors\":["
  328. else:
  329. hasVertexColor = False
  330. if hasSkeleton:
  331. skeletonWeight = ",\"matricesWeights\":["
  332. skeletonIndices = ",\"matricesIndices\":["
  333. alreadySavedVertices = []
  334. vertices_UVs=[]
  335. vertices_UV2s=[]
  336. vertices_Colors=[]
  337. vertices_indices=[]
  338. subMeshes = []
  339. offsetFace = 0
  340. for v in range(0, len(mesh.vertices)):
  341. alreadySavedVertices.append(False)
  342. vertices_UVs.append([])
  343. vertices_UV2s.append([])
  344. vertices_Colors.append([])
  345. vertices_indices.append([])
  346. materialsCount = max(1, len(object.material_slots))
  347. verticesCount = 0
  348. indicesCount = 0
  349. for materialIndex in range(materialsCount):
  350. if offsetFace != 0:
  351. break
  352. subMeshes.append(SubMesh())
  353. subMeshes[materialIndex].materialIndex = materialIndex
  354. subMeshes[materialIndex].verticesStart = verticesCount
  355. subMeshes[materialIndex].indexStart = indicesCount
  356. for faceIndex in range(startFace, len(mesh.tessfaces)): # For each face
  357. face = mesh.tessfaces[faceIndex]
  358. if face.material_index != materialIndex:
  359. continue
  360. if verticesCount + 3 > MAX_VERTICES:
  361. offsetFace = faceIndex
  362. break
  363. for v in range(3): # For each vertex in face
  364. vertex_index = face.vertices[v]
  365. vertex = mesh.vertices[vertex_index]
  366. position = vertex.co
  367. normal = vertex.normal
  368. #skeletons
  369. if hasSkeleton:
  370. matricesWeights = []
  371. matricesIndices = 0
  372. matricesWeights.append(0.0)
  373. matricesWeights.append(0.0)
  374. matricesWeights.append(0.0)
  375. matricesWeights.append(0.0)
  376. # Getting influences
  377. i = 0
  378. offset = 0
  379. for group in vertex.groups:
  380. index = group.group
  381. weight = group.weight
  382. for boneIndex, bone in enumerate(object.parent.pose.bones):
  383. if object.vertex_groups[index].name == bone.name:
  384. matricesWeights[i] = weight
  385. matricesIndices += boneIndex << offset
  386. offset = offset + 8
  387. i = i + 1
  388. if (i == 4):
  389. break;
  390. if (i == 4):
  391. break;
  392. # Texture coordinates
  393. if hasUV:
  394. vertex_UV = UVmap[face.index].uv[v]
  395. if hasUV2:
  396. vertex_UV2 = UV2map[face.index].uv[v]
  397. # Vertex color
  398. if hasVertexColor:
  399. if v == 0:
  400. vertex_Color = Colormap[face.index].color1
  401. if v == 1:
  402. vertex_Color = Colormap[face.index].color2
  403. if v == 2:
  404. vertex_Color = Colormap[face.index].color3
  405. # Check if the current vertex is already saved
  406. alreadySaved = alreadySavedVertices[vertex_index] and not hasSkeleton
  407. if alreadySaved:
  408. alreadySaved=False
  409. # UV
  410. index_UV = 0
  411. for savedIndex in vertices_indices[vertex_index]:
  412. if hasUV:
  413. vUV = vertices_UVs[vertex_index][index_UV]
  414. if (vUV[0]!=vertex_UV[0] or vUV[1]!=vertex_UV[1]):
  415. continue
  416. if hasUV2:
  417. vUV2 = vertices_UV2s[vertex_index][index_UV]
  418. if (vUV2[0]!=vertex_UV2[0] or vUV2[1]!=vertex_UV2[1]):
  419. continue
  420. if hasVertexColor:
  421. vColor = vertices_Colors[vertex_index][index_UV]
  422. if (vColor.r!=vertex_Color.r or vColor.g!=vertex_Color.g or vColor.b!=vertex_Color.b):
  423. continue
  424. if vertices_indices[vertex_index][index_UV] >= subMeshes[materialIndex].verticesStart:
  425. alreadySaved=True
  426. break
  427. index_UV+=1
  428. if (alreadySaved):
  429. # Reuse vertex
  430. index=vertices_indices[vertex_index][index_UV]
  431. else:
  432. # Export new one
  433. index=verticesCount
  434. alreadySavedVertices[vertex_index]=True
  435. if hasUV:
  436. vertices_UVs[vertex_index].append(vertex_UV)
  437. uvs+="%.4f,%.4f,"%(vertex_UV[0], vertex_UV[1])
  438. if hasUV2:
  439. vertices_UV2s[vertex_index].append(vertex_UV2)
  440. uvs2+="%.4f,%.4f,"%(vertex_UV2[0], vertex_UV2[1])
  441. if hasVertexColor:
  442. vertices_Colors[vertex_index].append(vertex_Color)
  443. colors+="%.4f,%.4f,%.4f,"%(vertex_Color.r,vertex_Color.g,vertex_Color.b)
  444. if hasSkeleton:
  445. skeletonWeight+="%.4f,%.4f,%.4f,%.4f,"%(matricesWeights[0], matricesWeights[1], matricesWeights[2], matricesWeights[3])
  446. skeletonIndices+="%i,"%(matricesIndices)
  447. vertices_indices[vertex_index].append(index)
  448. positions+="%.4f,%.4f,%.4f,"%(position.x,position.z,position.y)
  449. normals+="%.4f,%.4f,%.4f,"%(normal.x,normal.z,normal.y)
  450. verticesCount += 1
  451. indices+="%i,"%(index)
  452. indicesCount += 1
  453. subMeshes[materialIndex].verticesCount = verticesCount - subMeshes[materialIndex].verticesStart
  454. subMeshes[materialIndex].indexCount = indicesCount - subMeshes[materialIndex].indexStart
  455. positions=positions.rstrip(',')
  456. normals=normals.rstrip(',')
  457. indices=indices.rstrip(',')
  458. positions+="]\n"
  459. normals+="]\n"
  460. indices+="]\n"
  461. if hasUV:
  462. uvs=uvs.rstrip(',')
  463. uvs+="]\n"
  464. if hasUV2:
  465. uvs2=uvs2.rstrip(',')
  466. uvs2+="]\n"
  467. if hasVertexColor:
  468. colors=colors.rstrip(',')
  469. colors+="]\n"
  470. if hasSkeleton:
  471. skeletonWeight=skeletonWeight.rstrip(', ')
  472. skeletonWeight+="]\n"
  473. skeletonIndices= skeletonIndices.rstrip(', ')
  474. skeletonIndices+="]\n"
  475. # Writing mesh
  476. file_handler.write("{")
  477. Export_babylon.write_string(file_handler, "name", object.name + nameID, True)
  478. Export_babylon.write_string(file_handler, "id", object.name + nameID)
  479. if forcedParent is None:
  480. if object.parent != None:
  481. Export_babylon.write_string(file_handler, "parentId", object.parent.name)
  482. else:
  483. Export_babylon.write_string(file_handler, "parentId", forcedParent.name)
  484. if len(object.material_slots) == 1:
  485. material = object.material_slots[0].material
  486. Export_babylon.write_string(file_handler, "materialId", object.material_slots[0].name)
  487. if material.game_settings.face_orientation != "BILLBOARD":
  488. billboardMode = 0
  489. else:
  490. billboardMode = 7
  491. elif len(object.material_slots) > 1:
  492. multimat = MultiMaterial()
  493. multimat.name = "Multimaterial#" + str(len(multiMaterials))
  494. multimat.materials = []
  495. Export_babylon.write_string(file_handler, "materialId", multimat.name)
  496. for mat in object.material_slots:
  497. multimat.materials.append(mat.name)
  498. multiMaterials.append(multimat)
  499. billboardMode = 0
  500. else:
  501. billboardMode = 0
  502. if forcedParent is None:
  503. Export_babylon.write_vector(file_handler, "position", loc)
  504. Export_babylon.write_vectorScaled(file_handler, "rotation", rot.to_euler("XYZ"), -1)
  505. Export_babylon.write_vector(file_handler, "scaling", scale)
  506. else:
  507. Export_babylon.write_vector(file_handler, "position", mathutils.Vector((0, 0, 0)))
  508. Export_babylon.write_vectorScaled(file_handler, "rotation", mathutils.Vector((0, 0, 0)), 1)
  509. Export_babylon.write_vector(file_handler, "scaling", mathutils.Vector((1, 1, 1)))
  510. Export_babylon.write_bool(file_handler, "isVisible", object.is_visible(scene))
  511. Export_babylon.write_bool(file_handler, "isEnabled", True)
  512. Export_babylon.write_bool(file_handler, "useFlatShading", object.data.useFlatShading)
  513. Export_babylon.write_bool(file_handler, "checkCollisions", object.data.checkCollisions)
  514. Export_babylon.write_int(file_handler, "billboardMode", billboardMode)
  515. Export_babylon.write_bool(file_handler, "receiveShadows", object.data.receiveShadows)
  516. # Export Physics
  517. if object.rigid_body != None:
  518. shape_items = {'BOX': 1, 'SPHERE': 2}
  519. shape_type = shape_items[object.rigid_body.collision_shape]
  520. Export_babylon.write_int(file_handler, "physicsImpostor", shape_type)
  521. mass = object.rigid_body.mass
  522. if mass < 0.005:
  523. mass = 0
  524. Export_babylon.write_float(file_handler, "physicsMass", mass)
  525. Export_babylon.write_float(file_handler, "physicsFriction", object.rigid_body.friction)
  526. Export_babylon.write_float(file_handler, "physicsRestitution", object.rigid_body.restitution)
  527. # Geometry
  528. if hasSkeleton:
  529. i = 0
  530. for obj in [object for object in scene.objects if object.is_visible(scene)]:
  531. if (obj.type == 'ARMATURE'):
  532. if (obj.name == object.parent.name):
  533. Export_babylon.write_int(file_handler, "skeletonId", i)
  534. else:
  535. i = i+1
  536. file_handler.write(positions)
  537. file_handler.write(normals)
  538. if hasUV:
  539. file_handler.write(uvs)
  540. if hasUV2:
  541. file_handler.write(uvs2)
  542. if hasVertexColor:
  543. file_handler.write(colors)
  544. if hasSkeleton:
  545. file_handler.write(skeletonWeight)
  546. file_handler.write(skeletonIndices)
  547. file_handler.write(indices)
  548. # Sub meshes
  549. file_handler.write(",\"subMeshes\":[")
  550. first = True
  551. for subMesh in subMeshes:
  552. if first == False:
  553. file_handler.write(",")
  554. file_handler.write("{")
  555. Export_babylon.write_int(file_handler, "materialIndex", subMesh.materialIndex, True)
  556. Export_babylon.write_int(file_handler, "verticesStart", subMesh.verticesStart)
  557. Export_babylon.write_int(file_handler, "verticesCount", subMesh.verticesCount)
  558. Export_babylon.write_int(file_handler, "indexStart", subMesh.indexStart)
  559. Export_babylon.write_int(file_handler, "indexCount", subMesh.indexCount)
  560. file_handler.write("}")
  561. first = False
  562. file_handler.write("]")
  563. #Export Animations
  564. rotAnim = False
  565. locAnim = False
  566. scaAnim = False
  567. coma = False
  568. if object.animation_data:
  569. if object.animation_data.action:
  570. file_handler.write(",\"animations\":[")
  571. for fcurve in object.animation_data.action.fcurves:
  572. if fcurve.data_path == "rotation_euler" and rotAnim == False:
  573. Export_babylon.export_animation(object, scene, file_handler, "rotation_euler", "rotation", coma, -1)
  574. rotAnim = coma = True
  575. elif fcurve.data_path == "location" and locAnim == False:
  576. Export_babylon.export_animation(object, scene, file_handler, "location", "position", coma, 1)
  577. locAnim = coma = True
  578. elif fcurve.data_path == "scale" and scaAnim == False:
  579. Export_babylon.export_animation(object, scene, file_handler, "scale", "scaling", coma, 1)
  580. locAnim = coma = True
  581. file_handler.write("]")
  582. #Set Animations
  583. Export_babylon.write_bool(file_handler, "autoAnimate", True)
  584. Export_babylon.write_int(file_handler, "autoAnimateFrom", 0)
  585. Export_babylon.write_int(file_handler, "autoAnimateTo", bpy.context.scene.frame_end - bpy.context.scene.frame_start + 1)
  586. Export_babylon.write_bool(file_handler, "autoAnimateLoop", True)
  587. # Closing
  588. file_handler.write("}")
  589. return offsetFace
  590. def export_node(object, scene, file_handler):
  591. # Transform
  592. loc = mathutils.Vector((0, 0, 0))
  593. rot = mathutils.Quaternion((0, 0, 0, 1))
  594. scale = mathutils.Vector((1, 1, 1))
  595. world = object.matrix_world
  596. if (object.parent):
  597. world = object.parent.matrix_world.inverted() * object.matrix_world
  598. loc, rot, scale = world.decompose()
  599. # Writing node
  600. file_handler.write("{")
  601. Export_babylon.write_string(file_handler, "name", object.name, True)
  602. Export_babylon.write_string(file_handler, "id", object.name)
  603. if object.parent != None:
  604. Export_babylon.write_string(file_handler, "parentId", object.parent.name)
  605. Export_babylon.write_vector(file_handler, "position", loc)
  606. Export_babylon.write_vectorScaled(file_handler, "rotation", rot.to_euler("XYZ"), -1)
  607. Export_babylon.write_vector(file_handler, "scaling", scale)
  608. Export_babylon.write_bool(file_handler, "isVisible", False)
  609. Export_babylon.write_bool(file_handler, "isEnabled", True)
  610. Export_babylon.write_bool(file_handler, "checkCollisions", False)
  611. Export_babylon.write_int(file_handler, "billboardMode", 0)
  612. Export_babylon.write_bool(file_handler, "receiveShadows", False)
  613. # Closing
  614. file_handler.write("}")
  615. def export_shadowGenerator(lamp, scene, file_handler):
  616. file_handler.write("{")
  617. if lamp.data.shadowMap == 'VAR':
  618. Export_babylon.write_bool(file_handler, "useVarianceShadowMap", True, True)
  619. else:
  620. Export_babylon.write_bool(file_handler, "useVarianceShadowMap", False, True)
  621. Export_babylon.write_int(file_handler, "mapSize", lamp.data.shadowMapSize)
  622. Export_babylon.write_string(file_handler, "lightId", lamp.name)
  623. file_handler.write(",\"renderList\":[")
  624. multiMaterials = []
  625. first = True
  626. for object in [object for object in scene.objects]:
  627. if (object.type == 'MESH' and object.data.castShadows):
  628. if first != True:
  629. file_handler.write(",")
  630. first = False
  631. file_handler.write("\"" + object.name + "\"")
  632. file_handler.write("]")
  633. file_handler.write("}")
  634. def export_bone_matrix(armature, bone, label, file_handler):
  635. SystemMatrix = Matrix.Scale(-1, 4, Vector((0, 0, 1))) * Matrix.Rotation(radians(-90), 4, 'X')
  636. if (bone.parent):
  637. Export_babylon.write_matrix4(file_handler, label, (SystemMatrix * armature.matrix_world * bone.parent.matrix).inverted() * (SystemMatrix * armature.matrix_world * bone.matrix))
  638. else:
  639. Export_babylon.write_matrix4(file_handler, label, SystemMatrix * armature.matrix_world * bone.matrix)
  640. def export_bones(armature, scene, file_handler, id):
  641. file_handler.write("{")
  642. Export_babylon.write_string(file_handler, "name", armature.name, True)
  643. Export_babylon.write_int(file_handler, "id", id)
  644. file_handler.write(",\"bones\":[")
  645. bones = armature.pose.bones
  646. first = True
  647. j = 0
  648. for bone in bones:
  649. if first != True:
  650. file_handler.write(",")
  651. first = False
  652. file_handler.write("{")
  653. Export_babylon.write_string(file_handler, "name", bone.name, True)
  654. Export_babylon.write_int(file_handler, "index", j)
  655. Export_babylon.export_bone_matrix(armature, bone, "matrix", file_handler)
  656. if (bone.parent):
  657. parentId = 0
  658. for parent in bones:
  659. if parent == bone.parent:
  660. break;
  661. parentId += 1
  662. Export_babylon.write_int(file_handler, "parentBoneIndex", parentId)
  663. else:
  664. Export_babylon.write_int(file_handler, "parentBoneIndex", -1)
  665. #animation
  666. if (armature.animation_data.action):
  667. Export_babylon.export_bonesAnimation(armature, bone, scene, file_handler)
  668. j = j + 1
  669. file_handler.write("}")
  670. file_handler.write("]")
  671. file_handler.write("}")
  672. def export_bonesAnimation(armature, bone, scene, file_handler):
  673. file_handler.write(",\"animation\": {")
  674. start_frame = scene.frame_start
  675. end_frame = scene.frame_end
  676. fps = scene.render.fps
  677. Export_babylon.write_int(file_handler, "dataType", 3, True)
  678. Export_babylon.write_int(file_handler, "framePerSecond", fps)
  679. #keys
  680. file_handler.write(",\"keys\":[")
  681. for Frame in range(start_frame, end_frame + 1):
  682. file_handler.write("{")
  683. Export_babylon.write_int(file_handler, "frame", Frame, True)
  684. bpy.context.scene.frame_set(Frame)
  685. Export_babylon.export_bone_matrix(armature, bone, "values", file_handler)
  686. if Frame == end_frame:
  687. file_handler.write("}")
  688. else:
  689. file_handler.write("},")
  690. file_handler.write("]")
  691. Export_babylon.write_int(file_handler, "loopBehavior", 1)
  692. Export_babylon.write_string(file_handler, "name", "anim")
  693. Export_babylon.write_string(file_handler, "property", "_matrix")
  694. file_handler.write("}")
  695. bpy.context.scene.frame_set(start_frame)
  696. def save(operator, context, filepath="",
  697. use_apply_modifiers=False,
  698. use_triangulate=True,
  699. use_compress=False):
  700. # Open file
  701. file_handler = open(filepath, 'w')
  702. if bpy.ops.object.mode_set.poll():
  703. bpy.ops.object.mode_set(mode='OBJECT')
  704. # Writing scene
  705. scene=context.scene
  706. world = scene.world
  707. if world:
  708. world_ambient = world.ambient_color
  709. else:
  710. world_ambient = Color((0.0, 0.0, 0.0))
  711. bpy.ops.screen.animation_cancel()
  712. currentFrame = bpy.context.scene.frame_current
  713. bpy.context.scene.frame_set(0)
  714. file_handler.write("{")
  715. file_handler.write("\"autoClear\":true")
  716. Export_babylon.write_color(file_handler, "clearColor", world_ambient)
  717. Export_babylon.write_color(file_handler, "ambientColor", world_ambient)
  718. Export_babylon.write_vector(file_handler, "gravity", scene.gravity)
  719. if world and world.mist_settings.use_mist:
  720. Export_babylon.write_int(file_handler, "fogMode", 3)
  721. Export_babylon.write_color(file_handler, "fogColor", world.horizon_color)
  722. Export_babylon.write_float(file_handler, "fogStart", world.mist_settings.start)
  723. Export_babylon.write_float(file_handler, "fogEnd", world.mist_settings.depth)
  724. Export_babylon.write_float(file_handler, "fogDensity", 0.1)
  725. # Cameras
  726. file_handler.write(",\"cameras\":[")
  727. first = True
  728. for object in [object for object in scene.objects if object.is_visible(scene)]:
  729. if (object.type == 'CAMERA'):
  730. if first != True:
  731. file_handler.write(",")
  732. first = False
  733. data_string = Export_babylon.export_camera(object, scene, file_handler)
  734. file_handler.write("]")
  735. # Active camera
  736. if scene.camera != None:
  737. Export_babylon.write_string(file_handler, "activeCamera", scene.camera.name)
  738. # Lights
  739. file_handler.write(",\"lights\":[")
  740. first = True
  741. for object in [object for object in scene.objects if object.is_visible(scene)]:
  742. if (object.type == 'LAMP'):
  743. if first != True:
  744. file_handler.write(",")
  745. first = False
  746. data_string = Export_babylon.export_light(object, scene, file_handler)
  747. file_handler.write("]")
  748. # Materials
  749. materials = [mat for mat in bpy.data.materials if mat.users >= 1]
  750. file_handler.write(",\"materials\":[")
  751. first = True
  752. for material in materials:
  753. if first != True:
  754. file_handler.write(",")
  755. first = False
  756. data_string = Export_babylon.export_material(material, scene, file_handler, filepath)
  757. file_handler.write("]")
  758. # Meshes
  759. file_handler.write(",\"meshes\":[")
  760. multiMaterials = []
  761. first = True
  762. for object in [object for object in scene.objects]:
  763. if object.type == 'MESH' or object.type == 'EMPTY':
  764. if first != True:
  765. file_handler.write(",")
  766. first = False
  767. if object.type == 'MESH':
  768. forcedParent = None
  769. nameID = ""
  770. startFace = 0
  771. while True:
  772. startFace = Export_babylon.export_mesh(object, scene, file_handler, multiMaterials, startFace, forcedParent, str(nameID))
  773. if startFace == 0:
  774. break
  775. if forcedParent is None:
  776. nameID = 0
  777. forcedParent = object
  778. nameID = nameID + 1
  779. file_handler.write(",")
  780. else:
  781. data_string = Export_babylon.export_node(object, scene, file_handler)
  782. file_handler.write("]")
  783. # Multi-materials
  784. file_handler.write(",\"multiMaterials\":[")
  785. first = True
  786. for multimaterial in multiMaterials:
  787. if first != True:
  788. file_handler.write(",")
  789. first = False
  790. data_string = Export_babylon.export_multimaterial(multimaterial, scene, file_handler)
  791. file_handler.write("]")
  792. # Shadow generators
  793. file_handler.write(",\"shadowGenerators\":[")
  794. first = True
  795. for object in [object for object in scene.objects if object.is_visible(scene)]:
  796. if (object.type == 'LAMP' and object.data.shadowMap != 'NONE'):
  797. if first != True:
  798. file_handler.write(",")
  799. first = False
  800. data_string = Export_babylon.export_shadowGenerator(object, scene, file_handler)
  801. file_handler.write("]")
  802. # Armatures/Bones
  803. file_handler.write(",\"skeletons\":[")
  804. first = True
  805. i = 0
  806. for object in [object for object in scene.objects if object.is_visible(scene)]:
  807. if (object.type == 'ARMATURE'):
  808. if first != True:
  809. file_handler.write(",")
  810. first = False
  811. data_string = Export_babylon.export_bones(object, scene, file_handler, i)
  812. i = i+1
  813. file_handler.write("]")
  814. # Closing
  815. file_handler.write("}")
  816. file_handler.close()
  817. bpy.context.scene.frame_set(currentFrame)
  818. return {'FINISHED'}
  819. # UI
  820. bpy.types.Mesh.useFlatShading = BoolProperty(
  821. name="Use Flat Shading",
  822. default = False)
  823. bpy.types.Mesh.checkCollisions = BoolProperty(
  824. name="Check Collisions",
  825. default = False)
  826. bpy.types.Mesh.castShadows = BoolProperty(
  827. name="Cast Shadows",
  828. default = False)
  829. bpy.types.Mesh.receiveShadows = BoolProperty(
  830. name="Receive Shadows",
  831. default = False)
  832. bpy.types.Camera.checkCollisions = BoolProperty(
  833. name="Check Collisions",
  834. default = False)
  835. bpy.types.Camera.applyGravity = BoolProperty(
  836. name="Apply Gravity",
  837. default = False)
  838. bpy.types.Camera.ellipsoid = FloatVectorProperty(
  839. name="Ellipsoid",
  840. default = mathutils.Vector((0.2, 0.9, 0.2)))
  841. bpy.types.Lamp.shadowMap = EnumProperty(
  842. name="Shadow Map Type",
  843. items = (('NONE', "None", "No Shadow Maps"), ('STD', "Standard", "Use Standard Shadow Maps"), ('VAR', "Variance", "Use Variance Shadow Maps")),
  844. default = 'NONE')
  845. bpy.types.Lamp.shadowMapSize = IntProperty(
  846. name="Shadow Map Size",
  847. default = 512)
  848. class ObjectPanel(bpy.types.Panel):
  849. bl_label = "Babylon.js"
  850. bl_space_type = "PROPERTIES"
  851. bl_region_type = "WINDOW"
  852. bl_context = "data"
  853. def draw(self, context):
  854. ob = context.object
  855. if not ob or not ob.data:
  856. return
  857. layout = self.layout
  858. isMesh = isinstance(ob.data, bpy.types.Mesh)
  859. isCamera = isinstance(ob.data, bpy.types.Camera)
  860. isLight = isinstance(ob.data, bpy.types.Lamp)
  861. if isMesh:
  862. layout.prop(ob.data, 'useFlatShading')
  863. layout.prop(ob.data, 'checkCollisions')
  864. layout.prop(ob.data, 'castShadows')
  865. layout.prop(ob.data, 'receiveShadows')
  866. elif isCamera:
  867. layout.prop(ob.data, 'checkCollisions')
  868. layout.prop(ob.data, 'applyGravity')
  869. layout.prop(ob.data, 'ellipsoid')
  870. elif isLight:
  871. layout.prop(ob.data, 'shadowMap')
  872. layout.prop(ob.data, 'shadowMapSize')
  873. ### REGISTER ###
  874. def menu_func(self, context):
  875. self.layout.operator(Export_babylon.bl_idname, text="Babylon.js (.babylon)")
  876. def register():
  877. bpy.utils.register_module(__name__)
  878. bpy.types.INFO_MT_file_export.append(menu_func)
  879. def unregister():
  880. bpy.utils.unregister_module(__name__)
  881. bpy.types.INFO_MT_file_export.remove(menu_func)
  882. if __name__ == "__main__":
  883. register()