io_export_babylon.py 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933
  1. bl_info = {
  2. 'name': 'Babylon.js',
  3. 'author': 'David Catuhe, Jeff Palmer',
  4. 'version': (1, 8, 2),
  5. 'blender': (2, 72, 0),
  6. "location": "File > Export > Babylon.js (.babylon)",
  7. "description": "Export Babylon.js scenes (.babylon)",
  8. 'wiki_url': 'https://github.com/BabylonJS/Babylon.js/wiki/13-Blender',
  9. 'tracker_url': '',
  10. 'category': 'Import-Export'}
  11. import bpy
  12. import bpy_extras.io_utils
  13. import io
  14. import math
  15. import mathutils
  16. import os
  17. import shutil
  18. import sys, traceback # for writing errors to log file
  19. #===============================================================================
  20. # Registration the calling of the INFO_MT_file_export file selector
  21. def menu_func(self, context):
  22. self.layout.operator(BabylonExporter.bl_idname, text = 'Babylon.js [.babylon]')
  23. # store keymaps here to access after registration (commented out for now)
  24. #addon_keymaps = []
  25. def register():
  26. bpy.utils.register_module(__name__)
  27. bpy.types.INFO_MT_file_export.append(menu_func)
  28. # create the hotkey
  29. # kc = bpy.context.window_manager.keyconfigs.addon
  30. # km = kc.keymaps.new(name='3D View', space_type='VIEW_3D')
  31. # kmi = km.keymap_items.new('wm.call_menu', 'W', 'PRESS', alt=True)
  32. # kmi.properties.name = BabylonExporter.bl_idname
  33. # kmi.active = True
  34. # addon_keymaps.append((km, kmi))
  35. def unregister():
  36. bpy.utils.unregister_module(__name__)
  37. bpy.types.INFO_MT_file_export.remove(menu_func)
  38. # for km, kmi in addon_keymaps:
  39. # km.keymap_items.remove(kmi)
  40. # addon_keymaps.clear()
  41. if __name__ == '__main__':
  42. register()
  43. #===============================================================================
  44. # output related constants
  45. MAX_VERTEX_ELEMENTS = 65535
  46. VERTEX_OUTPUT_PER_LINE = 1000
  47. MAX_FLOAT_PRECISION = '%.4f'
  48. MAX_INFLUENCERS_PER_VERTEX = 4
  49. # used in World constructor, defined in BABYLON.Scene
  50. #FOGMODE_NONE = 0
  51. #FOGMODE_EXP = 1
  52. #FOGMODE_EXP2 = 2
  53. FOGMODE_LINEAR = 3
  54. # used in Mesh & Node constructors, defined in BABYLON.AbstractMesh
  55. BILLBOARDMODE_NONE = 0
  56. #BILLBOARDMODE_X = 1
  57. #BILLBOARDMODE_Y = 2
  58. #BILLBOARDMODE_Z = 4
  59. BILLBOARDMODE_ALL = 7
  60. # used in Mesh constructor, defined in BABYLON.PhysicsEngine
  61. SPHERE_IMPOSTER = 1
  62. BOX_IMPOSTER = 2
  63. #PLANE_IMPOSTER = 3
  64. MESH_IMPOSTER = 4
  65. CAPSULE_IMPOSTER = 5
  66. CONE_IMPOSTER = 6
  67. CYLINDER_IMPOSTER = 7
  68. CONVEX_HULL_IMPOSTER = 8
  69. # camera class names, never formally defined in Babylon, but used in babylonFileLoader
  70. ANAGLYPH_ARC_CAM = 'AnaglyphArcRotateCamera'
  71. ANAGLYPH_FREE_CAM = 'AnaglyphFreeCamera'
  72. ARC_ROTATE_CAM = 'ArcRotateCamera'
  73. DEV_ORIENT_CAM = 'DeviceOrientationCamera'
  74. FOLLOW_CAM = 'FollowCamera'
  75. FREE_CAM = 'FreeCamera'
  76. GAMEPAD_CAM = 'GamepadCamera'
  77. TOUCH_CAM = 'TouchCamera'
  78. V_JOYSTICKS_CAM = 'VirtualJoysticksCamera'
  79. VR_DEV_ORIENT_FREE_CAM ='VRDeviceOrientationFreeCamera'
  80. WEB_VR_FREE_CAM = 'WebVRFreeCamera'
  81. # used in Light constructor, never formally defined in Babylon, but used in babylonFileLoader
  82. POINT_LIGHT = 0
  83. DIRECTIONAL_LIGHT = 1
  84. SPOT_LIGHT = 2
  85. HEMI_LIGHT = 3
  86. # used in Texture constructor, defined in BABYLON.Texture
  87. CLAMP_ADDRESSMODE = 0
  88. WRAP_ADDRESSMODE = 1
  89. MIRROR_ADDRESSMODE = 2
  90. # used in Texture constructor, defined in BABYLON.Texture
  91. EXPLICIT_MODE = 0
  92. SPHERICAL_MODE = 1
  93. #PLANAR_MODE = 2
  94. CUBIC_MODE = 3
  95. #PROJECTION_MODE = 4
  96. #SKYBOX_MODE = 5
  97. # passed to Animation constructor from animatable objects, defined in BABYLON.Animation
  98. #ANIMATIONTYPE_FLOAT = 0
  99. ANIMATIONTYPE_VECTOR3 = 1
  100. ANIMATIONTYPE_QUATERNION = 2
  101. ANIMATIONTYPE_MATRIX = 3
  102. #ANIMATIONTYPE_COLOR3 = 4
  103. # passed to Animation constructor from animatable objects, defined in BABYLON.Animation
  104. #ANIMATIONLOOPMODE_RELATIVE = 0
  105. ANIMATIONLOOPMODE_CYCLE = 1
  106. #ANIMATIONLOOPMODE_CONSTANT = 2
  107. #===============================================================================
  108. class BabylonExporter(bpy.types.Operator, bpy_extras.io_utils.ExportHelper):
  109. bl_idname = 'scene.babylon' # module will not load with out it, also must have a dot
  110. bl_label = 'Export Babylon.js scene' # used on the label of the actual 'save' button
  111. filename_ext = '.babylon' # required to have one, although not really used
  112. filepath = bpy.props.StringProperty(subtype = 'FILE_PATH') # assigned once the file selector returns
  113. log_handler = None # assigned in execute
  114. nameSpace = None # assigned in execute
  115. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  116. export_onlyCurrentLayer = bpy.props.BoolProperty(
  117. name="Export only current layer",
  118. description="Export only current layer",
  119. default = False,
  120. )
  121. export_noVertexOpt = bpy.props.BoolProperty(
  122. name="No vertex sharing",
  123. description="Turns off an optimization which reduces vertices",
  124. default = False,
  125. )
  126. attachedSound = bpy.props.StringProperty(
  127. name='Music',
  128. description='',
  129. default = ''
  130. )
  131. loopSound = bpy.props.BoolProperty(
  132. name='Loop sound',
  133. description='',
  134. default = True
  135. )
  136. autoPlaySound = bpy.props.BoolProperty(
  137. name='Auto play sound',
  138. description='',
  139. default = True
  140. )
  141. def draw(self, context):
  142. layout = self.layout
  143. layout.prop(self, 'export_onlyCurrentLayer')
  144. layout.prop(self, "export_noVertexOpt")
  145. layout.separator()
  146. layout.prop(self, 'attachedSound')
  147. layout.prop(self, 'autoPlaySound')
  148. layout.prop(self, 'loopSound')
  149. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  150. nWarnings = 0
  151. @staticmethod
  152. def warn(msg, numTabIndent = 1, noNewLine = False):
  153. BabylonExporter.log(msg, numTabIndent, noNewLine)
  154. BabylonExporter.nWarnings += 1
  155. @staticmethod
  156. def log(msg, numTabIndent = 1, noNewLine = False):
  157. for i in range(numTabIndent):
  158. BabylonExporter.log_handler.write('\t')
  159. BabylonExporter.log_handler.write(msg)
  160. if not noNewLine: BabylonExporter.log_handler.write('\n')
  161. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  162. materials = []
  163. @staticmethod
  164. def uvRequiredForMaterial(baseMaterialId):
  165. fullName = BabylonExporter.nameSpace + '.' + baseMaterialId
  166. for material in BabylonExporter.materials:
  167. if material.name == fullName and len(material.textures) > 0:
  168. return True
  169. return False
  170. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  171. def execute(self, context):
  172. try:
  173. filepathDotExtension = self.filepath.rpartition('.')
  174. self.filepathMinusExtension = filepathDotExtension[0]
  175. # assign nameSpace, based on OS
  176. if self.filepathMinusExtension.find('\\') != -1:
  177. BabylonExporter.nameSpace = legal_js_identifier(self.filepathMinusExtension.rpartition('\\')[2])
  178. else:
  179. BabylonExporter.nameSpace = legal_js_identifier(self.filepathMinusExtension.rpartition('/')[2])
  180. # explicitly reset globals, in case there was an earlier export this session
  181. BabylonExporter.nWarnings = 0
  182. BabylonExporter.materials = []
  183. BabylonExporter.log_handler = io.open(self.filepathMinusExtension + '.log', 'w', encoding='utf8')
  184. BabylonExporter_version = bl_info['version']
  185. BabylonExporter.log('Babylon.js Exporter version: ' + str(BabylonExporter_version[0]) + '.' + str(BabylonExporter_version[1]) + '.' + str(BabylonExporter_version[2]) +
  186. ', Blender version: ' + bpy.app.version_string)
  187. if bpy.ops.object.mode_set.poll():
  188. bpy.ops.object.mode_set(mode = 'OBJECT')
  189. scene = context.scene
  190. BabylonExporter.log('========= Conversion from Blender to Babylon.js =========', 0)
  191. self.world = World(scene)
  192. bpy.ops.screen.animation_cancel()
  193. currentFrame = bpy.context.scene.frame_current
  194. bpy.context.scene.frame_set(0)
  195. # Active camera
  196. if scene.camera != None:
  197. self.activeCamera = scene.camera.name
  198. else:
  199. BabylonExporter.warn('WARNING: No active camera has been assigned, or is not in a currently selected Blender layer')
  200. # Materials, static for ease of uvs requirement testing
  201. stuffs = [mat for mat in bpy.data.materials if mat.users >= 1]
  202. for material in stuffs:
  203. BabylonExporter.materials.append(Material(material, scene, self.filepath)) # need file path incase an image texture
  204. self.cameras = []
  205. self.lights = []
  206. self.shadowGenerators = []
  207. self.skeletons = []
  208. skeletonId = 0
  209. self.meshesAndNodes = []
  210. self.multiMaterials = []
  211. self.meshesWithSound = []
  212. # Music
  213. if self.attachedSound != '':
  214. music = type('', (), {})() #Fake mesh object
  215. music.data = type('', (), {})()
  216. music.data.attachedSound = self.attachedSound
  217. music.data.loopSound = self.loopSound
  218. music.data.autoPlaySound = self.autoPlaySound
  219. self.meshesWithSound.append(music)
  220. # exclude lamps in this pass, so ShadowGenerator constructor can be passed meshesAnNodes
  221. for object in [object for object in scene.objects]:
  222. if object.type == 'CAMERA':
  223. if object.is_visible(scene): # no isInSelectedLayer() required, is_visible() handles this for them
  224. self.cameras.append(Camera(object))
  225. else:
  226. BabylonExporter.warn('WARNING: The following camera not visible in scene thus ignored: ' + object.name)
  227. elif object.type == 'ARMATURE': #skeleton.pose.bones
  228. if object.is_visible(scene):
  229. self.skeletons.append(Skeleton(object, scene, skeletonId))
  230. skeletonId += 1
  231. else:
  232. BabylonExporter.warn('WARNING: The following armature not visible in scene thus ignored: ' + object.name)
  233. elif object.type == 'MESH':
  234. forcedParent = None
  235. nameID = ''
  236. nextStartFace = 0
  237. while True and self.isInSelectedLayer(object, scene):
  238. mesh = Mesh(object, scene, self.multiMaterials, nextStartFace, forcedParent, nameID, self.export_noVertexOpt)
  239. self.meshesAndNodes.append(mesh)
  240. if object.data.attachedSound != '':
  241. self.meshesWithSound.append(object)
  242. nextStartFace = mesh.offsetFace
  243. if nextStartFace == 0:
  244. break
  245. if forcedParent is None:
  246. nameID = 0
  247. forcedParent = object
  248. BabylonExporter.warn('WARNING: The following mesh has exceeded the maximum # of vertex elements & will be broken into multiple Babylon meshes: ' + object.name)
  249. nameID = nameID + 1
  250. elif object.type == 'EMPTY':
  251. self.meshesAndNodes.append(Node(object))
  252. elif object.type != 'LAMP':
  253. BabylonExporter.warn('WARNING: The following object is not currently exportable thus ignored: ' + object.name)
  254. # Lamp / shadow Generator pass; meshesAnNodes complete & forceParents included
  255. for object in [object for object in scene.objects]:
  256. if object.type == 'LAMP':
  257. if object.is_visible(scene): # no isInSelectedLayer() required, is_visible() handles this for them
  258. bulb = Light(object)
  259. self.lights.append(bulb)
  260. if object.data.shadowMap != 'NONE':
  261. if bulb.light_type == DIRECTIONAL_LIGHT or bulb.light_type == SPOT_LIGHT:
  262. self.shadowGenerators.append(ShadowGenerator(object, self.meshesAndNodes, scene))
  263. else:
  264. BabylonExporter.warn('WARNING: Only directional (sun) and spot types of lamp are valid for shadows thus ignored: ' + object.name)
  265. else:
  266. BabylonExporter.warn('WARNING: The following lamp not visible in scene thus ignored: ' + object.name)
  267. bpy.context.scene.frame_set(currentFrame)
  268. # output file
  269. self.to_scene_file ()
  270. except:# catch *all* exceptions
  271. ex = sys.exc_info()
  272. BabylonExporter.log('========= An error was encountered =========', 0)
  273. stack = traceback.format_tb(ex[2])
  274. for line in stack:
  275. BabylonExporter.log_handler.write(line) # avoid tabs & extra newlines by not calling log() inside catch
  276. BabylonExporter.log_handler.write('ERROR: ' + str(ex[1]) + '\n')
  277. raise
  278. finally:
  279. BabylonExporter.log('========= end of processing =========', 0)
  280. BabylonExporter.log_handler.close()
  281. if (BabylonExporter.nWarnings > 0):
  282. self.report({'WARNING'}, 'Processing completed, but ' + str(BabylonExporter.nWarnings) + ' WARNINGS were raised, see log file.')
  283. return {'FINISHED'}
  284. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  285. def to_scene_file(self):
  286. BabylonExporter.log('========= Writing of scene file started =========', 0)
  287. # Open file
  288. file_handler = io.open(self.filepathMinusExtension + '.babylon', 'w', encoding='utf8')
  289. file_handler.write('{')
  290. self.world.to_scene_file(file_handler)
  291. # Materials
  292. file_handler.write(',\n"materials":[')
  293. first = True
  294. for material in BabylonExporter.materials:
  295. if first != True:
  296. file_handler.write(',')
  297. first = False
  298. material.to_scene_file(file_handler)
  299. file_handler.write(']')
  300. # Multi-materials
  301. file_handler.write(',\n"multiMaterials":[')
  302. first = True
  303. for multimaterial in self.multiMaterials:
  304. if first != True:
  305. file_handler.write(',')
  306. first = False
  307. multimaterial.to_scene_file(file_handler)
  308. file_handler.write(']')
  309. # Armatures/Bones
  310. file_handler.write(',\n"skeletons":[')
  311. first = True
  312. for skeleton in self.skeletons:
  313. if first != True:
  314. file_handler.write(',')
  315. first = False
  316. skeleton.to_scene_file(file_handler)
  317. file_handler.write(']')
  318. # Meshes
  319. file_handler.write(',\n"meshes":[')
  320. first = True
  321. for m in range(0, len(self.meshesAndNodes)):
  322. mesh = self.meshesAndNodes[m]
  323. # skip if mesh already written by that name, since this one is an instance
  324. skip = False
  325. for n in range(0, m):
  326. skip |= hasattr(mesh, "dataName") and hasattr(self.meshesAndNodes[n], "dataName") and mesh.dataName == self.meshesAndNodes[n].dataName # nodes have no dataname, so no need to check for
  327. if skip: continue
  328. if first != True:
  329. file_handler.write(',')
  330. first = False
  331. mesh.to_scene_file(file_handler, self.meshesAndNodes)
  332. file_handler.write(']')
  333. # Cameras
  334. file_handler.write(',\n"cameras":[')
  335. first = True
  336. for camera in self.cameras:
  337. if hasattr(camera, 'fatalProblem'): continue
  338. if first != True:
  339. file_handler.write(',')
  340. first = False
  341. camera.update_for_target_attributes(self.meshesAndNodes)
  342. camera.to_scene_file(file_handler)
  343. file_handler.write(']')
  344. # Active camera
  345. if hasattr(self, 'activeCamera'):
  346. write_string(file_handler, 'activeCamera', self.activeCamera)
  347. # Lights
  348. file_handler.write(',\n"lights":[')
  349. first = True
  350. for light in self.lights:
  351. if first != True:
  352. file_handler.write(',')
  353. first = False
  354. light.to_scene_file(file_handler)
  355. file_handler.write(']')
  356. # Shadow generators
  357. file_handler.write(',\n"shadowGenerators":[')
  358. first = True
  359. for shadowGen in self.shadowGenerators:
  360. if first != True:
  361. file_handler.write(',')
  362. first = False
  363. shadowGen.to_scene_file(file_handler)
  364. file_handler.write(']')
  365. # Sounds
  366. if len(self.meshesWithSound) > 0:
  367. file_handler.write('\n,"sounds":[')
  368. first = True
  369. for mesh in self.meshesWithSound:
  370. if first == False:
  371. file_handler.write(',')
  372. file_handler.write('{')
  373. write_string(file_handler, 'name', mesh.data.attachedSound, True)
  374. write_bool(file_handler, 'autoplay', mesh.data.autoPlaySound)
  375. write_bool(file_handler, 'loop', mesh.data.loopSound)
  376. if hasattr(mesh, 'name'):
  377. write_string(file_handler, 'connectedMeshId', mesh.name)
  378. write_float(file_handler, 'maxDistance', mesh.data.maxSoundDistance)
  379. file_handler.write('}')
  380. file_handler.write(']')
  381. # Closing
  382. file_handler.write('}')
  383. file_handler.close()
  384. BabylonExporter.log('========= Writing of scene file completed =========', 0)
  385. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  386. def isInSelectedLayer(self, obj, scene):
  387. return not self.export_onlyCurrentLayer or obj.layers[scene.active_layer]
  388. #===============================================================================
  389. class World:
  390. def __init__(self, scene):
  391. self.autoClear = True
  392. world = scene.world
  393. if world:
  394. self.ambient_color = world.ambient_color
  395. self.clear_color = world.horizon_color
  396. else:
  397. self.ambient_color = mathutils.Color((0.2, 0.2, 0.3))
  398. self.clear_color = mathutils.Color((0.0, 0.0, 0.0))
  399. self.gravity = scene.gravity
  400. if world and world.mist_settings.use_mist:
  401. self.fogMode = FOGMODE_LINEAR
  402. self.fogColor = world.horizon_color
  403. self.fogStart = world.mist_settings.start
  404. self.fogEnd = world.mist_settings.depth
  405. self.fogDensity = 0.1
  406. BabylonExporter.log('Python World class constructor completed')
  407. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  408. def to_scene_file(self, file_handler):
  409. write_bool(file_handler, 'autoClear', self.autoClear, True)
  410. write_color(file_handler, 'clearColor', self.clear_color)
  411. write_color(file_handler, 'ambientColor', self.ambient_color)
  412. write_vector(file_handler, 'gravity', self.gravity)
  413. if hasattr(self, 'fogMode'):
  414. write_int(file_handler, 'fogMode', self.fogMode)
  415. write_color(file_handler, 'fogColor', self.fogColor)
  416. write_float(file_handler, 'fogStart', self.fogStart)
  417. write_float(file_handler, 'fogEnd', self.fogEnd)
  418. write_float(file_handler, 'fogDensity', self.fogDensity)
  419. #===============================================================================
  420. class FCurveAnimatable:
  421. def __init__(self, object, supportsRotation, supportsPosition, supportsScaling, xOffsetForRotation = 0):
  422. # just because a sub-class can be animatable does not mean it is
  423. self.animationsPresent = object.animation_data and object.animation_data.action
  424. rotAnim = False
  425. locAnim = False
  426. scaAnim = False
  427. useQuat = object.rotation_mode=='QUATERNION'
  428. if (self.animationsPresent):
  429. BabylonExporter.log('FCurve animation processing begun for: ' + object.name, 1)
  430. self.animations = []
  431. for fcurve in object.animation_data.action.fcurves:
  432. if supportsRotation and fcurve.data_path == 'rotation_euler' and rotAnim == False and useQuat == False:
  433. self.animations.append(VectorAnimation(object, 'rotation_euler', 'rotation', -1, xOffsetForRotation))
  434. rotAnim = True
  435. elif supportsRotation and fcurve.data_path == 'rotation_quaternion' and rotAnim == False and useQuat == True:
  436. anim = None
  437. if object.type == 'CAMERA':
  438. # if it's a camera, convert quaternions to euler XYZ
  439. anim = QuaternionToEulerAnimation(object, 'rotation_quaternion', 'rotation', -1, xOffsetForRotation)
  440. else:
  441. anim = QuaternionAnimation(object, 'rotation_quaternion', 'rotationQuaternion', 1, xOffsetForRotation)
  442. self.animations.append(anim)
  443. rotAnim = True
  444. elif supportsPosition and fcurve.data_path == 'location' and locAnim == False:
  445. self.animations.append(VectorAnimation(object, 'location', 'position', 1))
  446. locAnim = True
  447. elif supportsScaling and fcurve.data_path == 'scale' and scaAnim == False:
  448. self.animations.append(VectorAnimation(object, 'scale', 'scaling', 1))
  449. scaAnim = True
  450. #Set Animations
  451. if (hasattr(object.data, "autoAnimate") and object.data.autoAnimate):
  452. self.autoAnimate = True
  453. self.autoAnimateFrom = bpy.context.scene.frame_end
  454. self.autoAnimateTo = 0
  455. for animation in self.animations:
  456. if self.autoAnimateFrom > animation.get_first_frame():
  457. self.autoAnimateFrom = animation.get_first_frame()
  458. if self.autoAnimateTo < animation.get_last_frame():
  459. self.autoAnimateTo = animation.get_last_frame()
  460. self.autoAnimateLoop = True
  461. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  462. def to_scene_file(self, file_handler):
  463. if (self.animationsPresent):
  464. file_handler.write('\n,"animations":[')
  465. first = True
  466. for animation in self.animations:
  467. if first == False:
  468. file_handler.write(',')
  469. animation.to_scene_file(file_handler)
  470. first = False
  471. file_handler.write(']')
  472. if (hasattr(self, "autoAnimate") and self.autoAnimate):
  473. write_bool(file_handler, 'autoAnimate', self.autoAnimate)
  474. write_int(file_handler, 'autoAnimateFrom', self.autoAnimateFrom)
  475. write_int(file_handler, 'autoAnimateTo', self.autoAnimateTo)
  476. write_bool(file_handler, 'autoAnimateLoop', self.autoAnimateLoop)
  477. #===============================================================================
  478. class Mesh(FCurveAnimatable):
  479. def __init__(self, object, scene, multiMaterials, startFace, forcedParent, nameID, noVertexOpt):
  480. super().__init__(object, True, True, True) #Should animations be done when forcedParent
  481. self.name = object.name + str(nameID)
  482. BabylonExporter.log('processing begun of mesh: ' + self.name)
  483. self.isVisible = not object.hide_render
  484. self.isEnabled = True
  485. self.useFlatShading = object.data.useFlatShading
  486. self.checkCollisions = object.data.checkCollisions
  487. self.receiveShadows = object.data.receiveShadows
  488. self.castShadows = object.data.castShadows
  489. if forcedParent is None:
  490. self.dataName = object.data.name # used to support shared vertex instances in later passed
  491. if object.parent and object.parent.type != 'ARMATURE':
  492. self.parentId = object.parent.name
  493. else:
  494. self.dataName = self.name
  495. self.parentId = forcedParent.name
  496. # Physics
  497. if object.rigid_body != None:
  498. shape_items = {'SPHERE' : SPHERE_IMPOSTER,
  499. 'BOX' : BOX_IMPOSTER,
  500. 'MESH' : MESH_IMPOSTER,
  501. 'CAPSULE' : CAPSULE_IMPOSTER,
  502. 'CONE' : CONE_IMPOSTER,
  503. 'CYLINDER' : CYLINDER_IMPOSTER,
  504. 'CONVEX_HULL': CONVEX_HULL_IMPOSTER}
  505. shape_type = shape_items[object.rigid_body.collision_shape]
  506. self.physicsImpostor = shape_type
  507. mass = object.rigid_body.mass
  508. if mass < 0.005:
  509. mass = 0
  510. self.physicsMass = mass
  511. self.physicsFriction = object.rigid_body.friction
  512. self.physicsRestitution = object.rigid_body.restitution
  513. # hasSkeleton detection & skeletonID determination
  514. hasSkeleton = False
  515. objArmature = None # if there's an armature, this will be the one!
  516. if len(object.vertex_groups) > 0:
  517. objArmature = object.find_armature()
  518. if objArmature != None:
  519. hasSkeleton = True
  520. i = 0
  521. for obj in scene.objects:
  522. if obj.type == "ARMATURE":
  523. if obj == objArmature:
  524. self.skeletonId = i
  525. break
  526. else:
  527. i += 1
  528. # detect if any textures in the material slots, which would mean UV mapping is required
  529. uvRequired = False
  530. for slot in object.material_slots:
  531. uvRequired |= BabylonExporter.uvRequiredForMaterial(slot.name)
  532. if len(object.material_slots) == 1:
  533. self.materialId = BabylonExporter.nameSpace + '.' + object.material_slots[0].name
  534. self.billboardMode = BILLBOARDMODE_ALL if object.material_slots[0].material.game_settings.face_orientation == 'BILLBOARD' else BILLBOARDMODE_NONE;
  535. elif len(object.material_slots) > 1:
  536. multimat = MultiMaterial(object.material_slots, len(multiMaterials))
  537. self.materialId = multimat.name
  538. multiMaterials.append(multimat)
  539. self.billboardMode = BILLBOARDMODE_NONE
  540. else:
  541. self.billboardMode = BILLBOARDMODE_NONE
  542. BabylonExporter.warn('WARNING: No materials have been assigned: ', 2)
  543. # Get mesh
  544. mesh = object.to_mesh(scene, True, 'PREVIEW')
  545. # use defaults when not None
  546. if forcedParent is None:
  547. # Use local matrix
  548. locMatrix = object.matrix_local
  549. if objArmature != None:
  550. # unless the armature is the parent
  551. if object.parent and object.parent == objArmature:
  552. locMatrix = object.matrix_world * object.parent.matrix_world.inverted()
  553. loc, rot, scale = locMatrix.decompose()
  554. self.position = loc
  555. if object.rotation_mode == 'QUATERNION':
  556. self.rotationQuaternion = rot
  557. else:
  558. self.rotation = scale_vector(rot.to_euler('XYZ'), -1)
  559. self.scaling = scale
  560. else:
  561. self.position = mathutils.Vector((0, 0, 0))
  562. self.rotation = scale_vector(mathutils.Vector((0, 0, 0)), 1) # isn't scaling 0's by 1 same as 0?
  563. self.scaling = mathutils.Vector((1, 1, 1))
  564. # Triangulate mesh if required
  565. Mesh.mesh_triangulate(mesh)
  566. # Getting vertices and indices
  567. self.positions = []
  568. self.normals = []
  569. self.uvs = [] # not always used
  570. self.uvs2 = [] # not always used
  571. self.colors = [] # not always used
  572. self.indices = []
  573. self.subMeshes = []
  574. hasUV = len(mesh.tessface_uv_textures) > 0
  575. if hasUV:
  576. UVmap = mesh.tessface_uv_textures[0].data
  577. hasUV2 = len(mesh.tessface_uv_textures) > 1
  578. if hasUV2:
  579. UV2map = mesh.tessface_uv_textures[1].data
  580. hasVertexColor = len(mesh.vertex_colors) > 0
  581. if hasVertexColor:
  582. Colormap = mesh.tessface_vertex_colors.active.data
  583. if hasSkeleton:
  584. self.skeletonWeights = []
  585. self.skeletonIndicesCompressed = []
  586. # used tracking of vertices as they are received
  587. alreadySavedVertices = []
  588. vertices_UVs = []
  589. vertices_UV2s = []
  590. vertices_Colors = []
  591. vertices_indices = []
  592. self.offsetFace = 0
  593. for v in range(0, len(mesh.vertices)):
  594. alreadySavedVertices.append(False)
  595. vertices_UVs.append([])
  596. vertices_UV2s.append([])
  597. vertices_Colors.append([])
  598. vertices_indices.append([])
  599. materialsCount = max(1, len(object.material_slots))
  600. verticesCount = 0
  601. indicesCount = 0
  602. for materialIndex in range(materialsCount):
  603. if self.offsetFace != 0:
  604. break
  605. subMeshVerticesStart = verticesCount
  606. subMeshIndexStart = indicesCount
  607. for faceIndex in range(startFace, len(mesh.tessfaces)): # For each face
  608. face = mesh.tessfaces[faceIndex]
  609. if face.material_index != materialIndex:
  610. continue
  611. if verticesCount + 3 > MAX_VERTEX_ELEMENTS:
  612. self.offsetFace = faceIndex
  613. break
  614. for v in range(3): # For each vertex in face
  615. vertex_index = face.vertices[v]
  616. vertex = mesh.vertices[vertex_index]
  617. position = vertex.co
  618. normal = vertex.normal
  619. #skeletons
  620. if hasSkeleton:
  621. matricesWeights = []
  622. matricesWeights.append(0.0)
  623. matricesWeights.append(0.0)
  624. matricesWeights.append(0.0)
  625. matricesWeights.append(0.0)
  626. matricesIndicesCompressed = 0
  627. # Getting influences
  628. i = 0
  629. offset = 0
  630. for group in vertex.groups:
  631. index = group.group
  632. weight = group.weight
  633. for boneIndex, bone in enumerate(objArmature.pose.bones):
  634. if object.vertex_groups[index].name == bone.name:
  635. if (i == MAX_INFLUENCERS_PER_VERTEX):
  636. BabylonExporter.warn('WARNING: Maximum # of influencers exceeded for a vertex, extras ignored', 2)
  637. break
  638. matricesWeights[i] = weight
  639. matricesIndicesCompressed += boneIndex << offset
  640. offset = offset + 8
  641. i = i + 1
  642. # Texture coordinates
  643. if hasUV:
  644. vertex_UV = UVmap[face.index].uv[v]
  645. if hasUV2:
  646. vertex_UV2 = UV2map[face.index].uv[v]
  647. # Vertex color
  648. if hasVertexColor:
  649. if v == 0:
  650. vertex_Color = Colormap[face.index].color1
  651. if v == 1:
  652. vertex_Color = Colormap[face.index].color2
  653. if v == 2:
  654. vertex_Color = Colormap[face.index].color3
  655. # Check if the current vertex is already saved
  656. alreadySaved = alreadySavedVertices[vertex_index] and not (hasSkeleton or noVertexOpt)
  657. if alreadySaved:
  658. alreadySaved = False
  659. # UV
  660. index_UV = 0
  661. for savedIndex in vertices_indices[vertex_index]:
  662. if hasUV:
  663. vUV = vertices_UVs[vertex_index][index_UV]
  664. if (vUV[0] != vertex_UV[0] or vUV[1] != vertex_UV[1]):
  665. continue
  666. if hasUV2:
  667. vUV2 = vertices_UV2s[vertex_index][index_UV]
  668. if (vUV2[0] != vertex_UV2[0] or vUV2[1] != vertex_UV2[1]):
  669. continue
  670. if hasVertexColor:
  671. vColor = vertices_Colors[vertex_index][index_UV]
  672. if (vColor.r != vertex_Color.r or vColor.g != vertex_Color.g or vColor.b != vertex_Color.b):
  673. continue
  674. if vertices_indices[vertex_index][index_UV] >= subMeshVerticesStart:
  675. alreadySaved = True
  676. break
  677. index_UV += 1
  678. if (alreadySaved):
  679. # Reuse vertex
  680. index = vertices_indices[vertex_index][index_UV]
  681. else:
  682. # Export new one
  683. index = verticesCount
  684. alreadySavedVertices[vertex_index] = True
  685. if hasUV:
  686. vertices_UVs[vertex_index].append(vertex_UV)
  687. self.uvs.append(vertex_UV[0])
  688. self.uvs.append(vertex_UV[1])
  689. if hasUV2:
  690. vertices_UV2s[vertex_index].append(vertex_UV2)
  691. self.uvs2.append(vertex_UV2[0])
  692. self.uvs2.append(vertex_UV2[1])
  693. if hasVertexColor:
  694. vertices_Colors[vertex_index].append(vertex_Color)
  695. self.colors.append(vertex_Color.r)
  696. self.colors.append(vertex_Color.g)
  697. self.colors.append(vertex_Color.b)
  698. self.colors.append(1.0)
  699. if hasSkeleton:
  700. self.skeletonWeights.append(matricesWeights[0])
  701. self.skeletonWeights.append(matricesWeights[1])
  702. self.skeletonWeights.append(matricesWeights[2])
  703. self.skeletonWeights.append(matricesWeights[3])
  704. self.skeletonIndicesCompressed.append(matricesIndicesCompressed)
  705. vertices_indices[vertex_index].append(index)
  706. self.positions.append(position)
  707. self.normals.append(normal)
  708. verticesCount += 1
  709. self.indices.append(index)
  710. indicesCount += 1
  711. self.subMeshes.append(SubMesh(materialIndex, subMeshVerticesStart, subMeshIndexStart, verticesCount - subMeshVerticesStart, indicesCount - subMeshIndexStart))
  712. BabylonExporter.log('num positions : ' + str(len(self.positions)), 2)
  713. BabylonExporter.log('num normals : ' + str(len(self.normals )), 2)
  714. BabylonExporter.log('num uvs : ' + str(len(self.uvs )), 2)
  715. BabylonExporter.log('num uvs2 : ' + str(len(self.uvs2 )), 2)
  716. BabylonExporter.log('num colors : ' + str(len(self.colors )), 2)
  717. BabylonExporter.log('num indices : ' + str(len(self.indices )), 2)
  718. if hasattr(self, 'skeletonWeights'):
  719. BabylonExporter.log('num skeletonWeights: ' + str(len(self.skeletonWeights)), 2)
  720. BabylonExporter.log('num skeletonIndices: ' + str(len(self.skeletonIndicesCompressed * 4)), 2)
  721. if uvRequired and len(self.uvs) == 0:
  722. BabylonExporter.warn('WARNING: textures being used, but no UV Map found', 2)
  723. numZeroAreaFaces = self.find_zero_area_faces()
  724. if numZeroAreaFaces > 0:
  725. BabylonExporter.warn('WARNING: # of 0 area faces found: ' + str(numZeroAreaFaces), 2)
  726. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  727. def find_zero_area_faces(self):
  728. nFaces = int(len(self.indices) / 3)
  729. nZeroAreaFaces = 0
  730. for f in range(0, nFaces):
  731. faceOffset = f * 3
  732. p1 = self.positions[self.indices[faceOffset ]]
  733. p2 = self.positions[self.indices[faceOffset + 1]]
  734. p3 = self.positions[self.indices[faceOffset + 2]]
  735. if same_vertex(p1, p2) or same_vertex(p1, p3) or same_vertex(p2, p3): nZeroAreaFaces += 1
  736. return nZeroAreaFaces
  737. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  738. @staticmethod
  739. def mesh_triangulate(mesh):
  740. try:
  741. import bmesh
  742. bm = bmesh.new()
  743. bm.from_mesh(mesh)
  744. bmesh.ops.triangulate(bm, faces = bm.faces)
  745. bm.to_mesh(mesh)
  746. mesh.calc_tessface()
  747. bm.free()
  748. except:
  749. pass
  750. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  751. def to_scene_file(self, file_handler, meshesAndNodes):
  752. file_handler.write('{')
  753. write_string(file_handler, 'name', self.name, True)
  754. write_string(file_handler, 'id', self.name)
  755. if hasattr(self, 'parentId'): write_string(file_handler, 'parentId', self.parentId)
  756. if hasattr(self, 'materialId'): write_string(file_handler, 'materialId', self.materialId)
  757. write_int(file_handler, 'billboardMode', self.billboardMode)
  758. write_vector(file_handler, 'position', self.position)
  759. if hasattr(self, "rotationQuaternion"):
  760. write_quaternion(file_handler, 'rotationQuaternion', self.rotationQuaternion)
  761. else:
  762. write_vector(file_handler, 'rotation', self.rotation)
  763. write_vector(file_handler, 'scaling', self.scaling)
  764. write_bool(file_handler, 'isVisible', self.isVisible)
  765. write_bool(file_handler, 'isEnabled', self.isEnabled)
  766. write_bool(file_handler, 'useFlatShading', self.useFlatShading)
  767. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  768. write_bool(file_handler, 'receiveShadows', self.receiveShadows)
  769. if hasattr(self, 'physicsImpostor'):
  770. write_int(file_handler, 'physicsImpostor', self.physicsImpostor)
  771. write_float(file_handler, 'physicsMass', self.physicsMass)
  772. write_float(file_handler, 'physicsFriction', self.physicsFriction)
  773. write_float(file_handler, 'physicsRestitution', self.physicsRestitution)
  774. # Geometry
  775. if hasattr(self, 'skeletonId'): write_int(file_handler, 'skeletonId', self.skeletonId)
  776. write_vector_array(file_handler, 'positions', self.positions)
  777. write_vector_array(file_handler, 'normals' , self.normals )
  778. if len(self.uvs) > 0:
  779. write_array(file_handler, 'uvs', self.uvs)
  780. if len(self.uvs2) > 0:
  781. write_array(file_handler, 'uvs2', self.uvs2)
  782. if len(self.colors) > 0:
  783. write_array(file_handler, 'colors', self.colors)
  784. if hasattr(self, 'skeletonWeights'):
  785. write_array(file_handler, 'matricesWeights', self.skeletonWeights)
  786. write_array(file_handler, 'matricesIndices', self.skeletonIndicesCompressed)
  787. write_array(file_handler, 'indices', self.indices)
  788. # Sub meshes
  789. file_handler.write('\n,"subMeshes":[')
  790. first = True
  791. for subMesh in self.subMeshes:
  792. if first == False:
  793. file_handler.write(',')
  794. subMesh.to_scene_file(file_handler)
  795. first = False
  796. file_handler.write(']')
  797. super().to_scene_file(file_handler) # Animations
  798. # Instances
  799. first = True
  800. file_handler.write('\n,"instances":[')
  801. for mesh in meshesAndNodes:
  802. if hasattr(mesh, "dataName") and mesh.dataName == self.dataName and mesh != self: # nodes have no dataname, so no need to check for
  803. if first == False:
  804. file_handler.write(',')
  805. file_handler.write('{')
  806. write_string(file_handler, 'name', mesh.name, True)
  807. write_vector(file_handler, 'position', mesh.position)
  808. write_vector(file_handler, 'rotation', mesh.rotation)
  809. write_vector(file_handler, 'scaling', mesh.scaling)
  810. file_handler.write('}')
  811. first = False
  812. file_handler.write(']')
  813. # Close mesh
  814. file_handler.write('}\n')
  815. self.alreadyExported = True
  816. #===============================================================================
  817. class Node(FCurveAnimatable):
  818. def __init__(self, node):
  819. super().__init__(node, True, True, True) #Should animations be done when foredParent
  820. BabylonExporter.log('processing begun of node: ' + node.name)
  821. self.name = node.name
  822. if node.parent and node.parent.type != 'ARMATURE':
  823. self.parentId = node.parent.name
  824. loc, rot, scale = node.matrix_local.decompose()
  825. if node.parent != None:
  826. self.parentId = node.parent.name
  827. self.position = loc
  828. if node.rotation_mode == 'QUATERNION':
  829. self.rotationQuaternion = rot
  830. else:
  831. self.rotation = scale_vector(rot.to_euler('XYZ'), -1)
  832. self.scaling = scale
  833. self.isVisible = False
  834. self.isEnabled = True
  835. self.checkCollisions = False
  836. self.billboardMode = BILLBOARDMODE_NONE
  837. self.castShadows = False
  838. self.receiveShadows = False
  839. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  840. def get_proper_name(self):
  841. return legal_js_identifier(self.name)
  842. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  843. def to_scene_file(self, file_handler, ignored):
  844. file_handler.write('{')
  845. write_string(file_handler, 'name', self.name, True)
  846. write_string(file_handler, 'id', self.name)
  847. if hasattr(self, 'parentId'): write_string(file_handler, 'parentId', self.parentId)
  848. write_vector(file_handler, 'position', self.position)
  849. if hasattr(self, "rotationQuaternion"):
  850. write_quaternion(file_handler, "rotationQuaternion", self.rotationQuaternion)
  851. else:
  852. write_vector(file_handler, 'rotation', self.rotation)
  853. write_vector(file_handler, 'scaling', self.scaling)
  854. write_bool(file_handler, 'isVisible', self.isVisible)
  855. write_bool(file_handler, 'isEnabled', self.isEnabled)
  856. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  857. write_int(file_handler, 'billboardMode', self.billboardMode)
  858. write_bool(file_handler, 'receiveShadows', self.receiveShadows)
  859. super().to_scene_file(file_handler) # Animations
  860. file_handler.write('}')
  861. #===============================================================================
  862. class SubMesh:
  863. def __init__(self, materialIndex, verticesStart, indexStart, verticesCount, indexCount):
  864. self.materialIndex = materialIndex
  865. self.verticesStart = verticesStart
  866. self.indexStart = indexStart
  867. self.verticesCount = verticesCount
  868. self.indexCount = indexCount
  869. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  870. def to_scene_file(self, file_handler):
  871. file_handler.write('{')
  872. write_int(file_handler, 'materialIndex', self.materialIndex, True)
  873. write_int(file_handler, 'verticesStart', self.verticesStart)
  874. write_int(file_handler, 'verticesCount', self.verticesCount)
  875. write_int(file_handler, 'indexStart' , self.indexStart)
  876. write_int(file_handler, 'indexCount' , self.indexCount)
  877. file_handler.write('}')
  878. #===============================================================================
  879. class Bone:
  880. def __init__(self, bone, skeleton, scene, index):
  881. BabylonExporter.log('processing begun of bone: ' + bone.name + ', index: '+ str(index))
  882. self.name = bone.name
  883. self.index = index
  884. matrix_world = skeleton.matrix_world
  885. self.matrix = Bone.get_matrix(bone, matrix_world)
  886. parentId = -1
  887. if (bone.parent):
  888. for parent in skeleton.pose.bones:
  889. parentId += 1
  890. if parent == bone.parent:
  891. break;
  892. self.parentBoneIndex = parentId
  893. #animation
  894. if (skeleton.animation_data):
  895. BabylonExporter.log('animation begun of bone: ' + self.name)
  896. self.animation = Animation(ANIMATIONTYPE_MATRIX, scene.render.fps, ANIMATIONLOOPMODE_CYCLE, 'anim', '_matrix')
  897. start_frame = scene.frame_start
  898. end_frame = scene.frame_end
  899. previousBoneMatrix = None
  900. for frame in range(start_frame, end_frame + 1):
  901. bpy.context.scene.frame_set(frame)
  902. currentBoneMatrix = Bone.get_matrix(bone, matrix_world)
  903. if (frame != end_frame and currentBoneMatrix == previousBoneMatrix):
  904. continue
  905. self.animation.frames.append(frame)
  906. self.animation.values.append(Bone.get_matrix(bone, matrix_world))
  907. previousBoneMatrix = currentBoneMatrix
  908. bpy.context.scene.frame_set(start_frame)
  909. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  910. @staticmethod
  911. def get_matrix(bone, matrix_world):
  912. SystemMatrix = mathutils.Matrix.Scale(-1, 4, mathutils.Vector((0, 0, 1))) * mathutils.Matrix.Rotation(math.radians(-90), 4, 'X')
  913. if (bone.parent):
  914. return (SystemMatrix * matrix_world * bone.parent.matrix).inverted() * (SystemMatrix * matrix_world * bone.matrix)
  915. else:
  916. return SystemMatrix * matrix_world * bone.matrix
  917. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  918. def to_scene_file(self, file_handler):
  919. file_handler.write('\n{')
  920. write_string(file_handler, 'name', self.name, True)
  921. write_int(file_handler, 'index', self.index)
  922. write_matrix4(file_handler, 'matrix', self.matrix)
  923. write_int(file_handler, 'parentBoneIndex', self.parentBoneIndex)
  924. #animation
  925. if hasattr(self, 'animation'):
  926. file_handler.write(',"animation":')
  927. self.animation.to_scene_file(file_handler)
  928. file_handler.write('}')
  929. #===============================================================================
  930. class Skeleton:
  931. def __init__(self, skeleton, scene, id):
  932. BabylonExporter.log('processing begun of skeleton: ' + skeleton.name + ', id: '+ str(id))
  933. self.name = skeleton.name
  934. self.id = id
  935. self.bones = []
  936. bones = skeleton.pose.bones
  937. j = 0
  938. for bone in bones:
  939. self.bones.append(Bone(bone, skeleton, scene, j))
  940. j = j + 1
  941. BabylonExporter.log('processing complete of skeleton: ' + skeleton.name)
  942. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  943. def to_scene_file(self, file_handler):
  944. file_handler.write('{')
  945. write_string(file_handler, 'name', self.name, True)
  946. write_int(file_handler, 'id', self.id) # keep int for legacy of original exporter
  947. file_handler.write(',"bones":[')
  948. first = True
  949. for bone in self.bones:
  950. if first != True:
  951. file_handler.write(',')
  952. first = False
  953. bone.to_scene_file(file_handler)
  954. file_handler.write(']')
  955. file_handler.write('}')
  956. #===============================================================================
  957. class Camera(FCurveAnimatable):
  958. def __init__(self, camera):
  959. super().__init__(camera, True, True, False, math.pi / 2)
  960. if camera.parent and camera.parent.type != 'ARMATURE':
  961. self.parentId = camera.parent.name
  962. self.CameraType = camera.data.CameraType
  963. self.name = camera.name
  964. BabylonExporter.log('processing begun of camera (' + self.CameraType + '): ' + self.name)
  965. self.position = camera.location
  966. # for quaternions, convert to euler XYZ, otherwise, use the default rotation_euler
  967. eul = camera.rotation_quaternion.to_euler("XYZ") if camera.rotation_mode == 'QUATERNION' else camera.rotation_euler
  968. self.rotation = mathutils.Vector((-eul[0] + math.pi / 2, eul[1], -eul[2]))
  969. self.fov = camera.data.angle
  970. self.minZ = camera.data.clip_start
  971. self.maxZ = camera.data.clip_end
  972. self.speed = 1.0
  973. self.inertia = 0.9
  974. self.checkCollisions = camera.data.checkCollisions
  975. self.applyGravity = camera.data.applyGravity
  976. self.ellipsoid = camera.data.ellipsoid
  977. for constraint in camera.constraints:
  978. if constraint.type == 'TRACK_TO':
  979. self.lockedTargetId = constraint.target.name
  980. break
  981. if self.CameraType == ANAGLYPH_ARC_CAM or self.CameraType == ANAGLYPH_FREE_CAM:
  982. self.anaglyphEyeSpace = camera.data.anaglyphEyeSpace
  983. if self.CameraType == ANAGLYPH_ARC_CAM or self.CameraType == ARC_ROTATE_CAM or self.CameraType == FOLLOW_CAM:
  984. if not hasattr(self, 'lockedTargetId'):
  985. BabylonExporter.warn('ERROR: Camera type with manditory target specified, but no target to track set', 2)
  986. self.fatalProblem = True
  987. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  988. def update_for_target_attributes(self, meshesAndNodes):
  989. if not hasattr(self, 'lockedTargetId'): return
  990. # find the actual mesh tracking, so properties can be derrived
  991. targetFound = False
  992. for mesh in meshesAndNodes:
  993. if mesh.name == self.lockedTargetId:
  994. targetMesh = mesh
  995. targetFound = True
  996. break;
  997. xApart = 3 if not targetFound else self.position.x - targetMesh.position.x
  998. yApart = 3 if not targetFound else self.position.y - targetMesh.position.y
  999. zApart = 3 if not targetFound else self.position.z - targetMesh.position.z
  1000. distance3D = math.sqrt(xApart * xApart + yApart * yApart + zApart * zApart)
  1001. alpha = math.atan2(yApart, xApart);
  1002. beta = math.atan2(yApart, zApart);
  1003. if self.CameraType == FOLLOW_CAM:
  1004. self.followHeight = zApart
  1005. self.followDistance = distance3D
  1006. self.followRotation = 90 + (alpha * 180 / math.pi)
  1007. elif self.CameraType == ANAGLYPH_ARC_CAM or self.CameraType == ARC_ROTATE_CAM:
  1008. self.arcRotAlpha = alpha
  1009. self.arcRotBeta = beta
  1010. self.arcRotRadius = distance3D
  1011. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1012. def to_scene_file(self, file_handler):
  1013. file_handler.write('{')
  1014. write_string(file_handler, 'name', self.name, True)
  1015. write_string(file_handler, 'id', self.name)
  1016. write_vector(file_handler, 'position', self.position)
  1017. write_vector(file_handler, 'rotation', self.rotation)
  1018. write_float(file_handler, 'fov', self.fov)
  1019. write_float(file_handler, 'minZ', self.minZ)
  1020. write_float(file_handler, 'maxZ', self.maxZ)
  1021. write_float(file_handler, 'speed', self.speed)
  1022. write_float(file_handler, 'inertia', self.inertia)
  1023. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  1024. write_bool(file_handler, 'applyGravity', self.applyGravity)
  1025. write_array3(file_handler, 'ellipsoid', self.ellipsoid)
  1026. write_string(file_handler, 'type', self.CameraType)
  1027. if hasattr(self, 'parentId'): write_string(file_handler, 'parentId', self.parentId)
  1028. if self.CameraType == FOLLOW_CAM:
  1029. write_float(file_handler, 'heightOffset', self.followHeight)
  1030. write_float(file_handler, 'radius', self.followDistance)
  1031. write_float(file_handler, 'rotationOffset', self.followRotation)
  1032. elif self.CameraType == ANAGLYPH_ARC_CAM or self.CameraType == ARC_ROTATE_CAM:
  1033. write_float(file_handler, 'alpha', self.arcRotAlpha)
  1034. write_float(file_handler, 'beta', self.arcRotBeta)
  1035. write_float(file_handler, 'radius', self.arcRotRadius)
  1036. if self.CameraType == ANAGLYPH_ARC_CAM:
  1037. write_float(file_handler, 'eye_space', self.anaglyphEyeSpace)
  1038. elif self.CameraType == ANAGLYPH_FREE_CAM:
  1039. write_float(file_handler, 'eye_space', self.anaglyphEyeSpace)
  1040. if hasattr(self, 'lockedTargetId'):
  1041. write_string(file_handler, 'lockedTargetId', self.lockedTargetId)
  1042. super().to_scene_file(file_handler) # Animations
  1043. file_handler.write('}')
  1044. #===============================================================================
  1045. class Light(FCurveAnimatable):
  1046. def __init__(self, light):
  1047. super().__init__(light, False, True, False)
  1048. if light.parent and light.parent.type != 'ARMATURE':
  1049. self.parentId = light.parent.name
  1050. self.name = light.name
  1051. BabylonExporter.log('processing begun of light (' + light.data.type + '): ' + self.name)
  1052. light_type_items = {'POINT': POINT_LIGHT, 'SUN': DIRECTIONAL_LIGHT, 'SPOT': SPOT_LIGHT, 'HEMI': HEMI_LIGHT, 'AREA': 0}
  1053. self.light_type = light_type_items[light.data.type]
  1054. if self.light_type == POINT_LIGHT:
  1055. self.position = light.location
  1056. if hasattr(light.data, 'use_sphere'):
  1057. if light.data.use_sphere:
  1058. self.range = light.data.distance
  1059. elif self.light_type == DIRECTIONAL_LIGHT:
  1060. self.position = light.location
  1061. self.direction = Light.get_direction(light.matrix_local)
  1062. elif self.light_type == SPOT_LIGHT:
  1063. self.position = light.location
  1064. self.direction = Light.get_direction(light.matrix_local)
  1065. self.angle = light.data.spot_size
  1066. self.exponent = light.data.spot_blend * 2
  1067. if light.data.use_sphere:
  1068. self.range = light.data.distance
  1069. else:
  1070. # Hemi & Area
  1071. matrix_local = light.matrix_local.copy()
  1072. matrix_local.translation = mathutils.Vector((0, 0, 0))
  1073. self.direction = (mathutils.Vector((0, 0, -1)) * matrix_local)
  1074. self.direction = scale_vector(self.direction, -1)
  1075. self.groundColor = mathutils.Color((0, 0, 0))
  1076. self.intensity = light.data.energy
  1077. self.diffuse = light.data.color if light.data.use_diffuse else mathutils.Color((0, 0, 0))
  1078. self.specular = light.data.color if light.data.use_specular else mathutils.Color((0, 0, 0))
  1079. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1080. def to_scene_file(self, file_handler):
  1081. file_handler.write('{')
  1082. write_string(file_handler, 'name', self.name, True)
  1083. write_string(file_handler, 'id', self.name)
  1084. write_float(file_handler, 'type', self.light_type)
  1085. if hasattr(self, 'parentId' ): write_string(file_handler, 'parentId', self.parentId)
  1086. if hasattr(self, 'position' ): write_vector(file_handler, 'position' , self.position )
  1087. if hasattr(self, 'direction' ): write_vector(file_handler, 'direction' , self.direction )
  1088. if hasattr(self, 'angle' ): write_float (file_handler, 'angle' , self.angle )
  1089. if hasattr(self, 'exponent' ): write_float (file_handler, 'exponent' , self.exponent )
  1090. if hasattr(self, 'groundColor'): write_color (file_handler, 'groundColor', self.groundColor)
  1091. if hasattr(self, 'range' ): write_float (file_handler, 'range' , self.range )
  1092. write_float(file_handler, 'intensity', self.intensity)
  1093. write_color(file_handler, 'diffuse', self.diffuse)
  1094. write_color(file_handler, 'specular', self.specular)
  1095. super().to_scene_file(file_handler) # Animations
  1096. file_handler.write('}')
  1097. @staticmethod
  1098. def get_direction(matrix):
  1099. return (matrix.to_3x3() * mathutils.Vector((0.0, 0.0, -1.0))).normalized()
  1100. #===============================================================================
  1101. class ShadowGenerator:
  1102. def __init__(self, lamp, meshesAndNodes, scene):
  1103. BabylonExporter.log('processing begun of shadows for light: ' + lamp.name)
  1104. self.useVarianceShadowMap = lamp.data.shadowMap == 'VAR' if True else False
  1105. self.mapSize = lamp.data.shadowMapSize
  1106. self.lightId = lamp.name
  1107. self.shadowCasters = []
  1108. for mesh in meshesAndNodes:
  1109. if (mesh.castShadows):
  1110. self.shadowCasters.append(mesh.name)
  1111. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1112. def to_scene_file(self, file_handler):
  1113. file_handler.write('{')
  1114. write_bool(file_handler, 'useVarianceShadowMap', self.useVarianceShadowMap, True)
  1115. write_int(file_handler, 'mapSize', self.mapSize)
  1116. write_string(file_handler, 'lightId', self.lightId)
  1117. file_handler.write(',"renderList":[')
  1118. first = True
  1119. for caster in self.shadowCasters:
  1120. if first != True:
  1121. file_handler.write(',')
  1122. first = False
  1123. file_handler.write('"' + caster + '"')
  1124. file_handler.write(']')
  1125. file_handler.write('}')
  1126. #===============================================================================
  1127. class MultiMaterial:
  1128. def __init__(self, material_slots, idx):
  1129. self.name = BabylonExporter.nameSpace + '.' + 'Multimaterial#' + str(idx)
  1130. BabylonExporter.log('processing begun of multimaterial: ' + self.name, 2)
  1131. self.materials = []
  1132. for mat in material_slots:
  1133. self.materials.append(BabylonExporter.nameSpace + '.' + mat.name)
  1134. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1135. def to_scene_file(self, file_handler):
  1136. file_handler.write('{')
  1137. write_string(file_handler, 'name', self.name, True)
  1138. write_string(file_handler, 'id', self.name)
  1139. file_handler.write(',"materials":[')
  1140. first = True
  1141. for materialName in self.materials:
  1142. if first != True:
  1143. file_handler.write(',')
  1144. file_handler.write('"' + materialName +'"')
  1145. first = False
  1146. file_handler.write(']')
  1147. file_handler.write('}')
  1148. #===============================================================================
  1149. class Texture:
  1150. def __init__(self, slot, level, texture, filepath):
  1151. # Copy image to output
  1152. try:
  1153. image = texture.texture.image
  1154. imageFilepath = os.path.normpath(bpy.path.abspath(image.filepath))
  1155. basename = os.path.basename(imageFilepath)
  1156. targetdir = os.path.dirname(filepath)
  1157. targetpath = os.path.join(targetdir, basename)
  1158. if image.packed_file:
  1159. image.save_render(targetpath)
  1160. else:
  1161. sourcepath = bpy.path.abspath(image.filepath)
  1162. shutil.copy(sourcepath, targetdir)
  1163. except:
  1164. ex = sys.exc_info()
  1165. BabylonExporter.log_handler.write('Error encountered processing image file: ' + imageFilepath + ', Error: '+ str(ex[1]) + '\n')
  1166. #pass
  1167. # Export
  1168. self.slot = slot
  1169. self.name = basename
  1170. self.level = level
  1171. self.hasAlpha = texture.texture.use_alpha
  1172. if (texture.mapping == 'CUBE'):
  1173. self.coordinatesMode = CUBIC_MODE
  1174. if (texture.mapping == 'SPHERE'):
  1175. self.coordinatesMode = SPHERICAL_MODE
  1176. else:
  1177. self.coordinatesMode = EXPLICIT_MODE
  1178. self.uOffset = texture.offset.x
  1179. self.vOffset = texture.offset.y
  1180. self.uScale = texture.scale.x
  1181. self.vScale = texture.scale.y
  1182. self.uAng = 0
  1183. self.vAng = 0
  1184. self.wAng = 0
  1185. if (texture.texture.extension == 'REPEAT'):
  1186. if (texture.texture.use_mirror_x):
  1187. self.wrapU = MIRROR_ADDRESSMODE
  1188. else:
  1189. self.wrapU = WRAP_ADDRESSMODE
  1190. if (texture.texture.use_mirror_y):
  1191. self.wrapV = MIRROR_ADDRESSMODE
  1192. else:
  1193. self.wrapV = WRAP_ADDRESSMODE
  1194. else:
  1195. self.wrapU = CLAMP_ADDRESSMODE
  1196. self.wrapV = CLAMP_ADDRESSMODE
  1197. self.coordinatesIndex = 0
  1198. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1199. def to_scene_file(self, file_handler):
  1200. file_handler.write(', "' + self.slot + '":{')
  1201. write_string(file_handler, 'name', self.name, True)
  1202. write_float(file_handler, 'level', self.level)
  1203. write_float(file_handler, 'hasAlpha', self.hasAlpha)
  1204. write_int(file_handler, 'coordinatesMode', self.coordinatesMode)
  1205. write_float(file_handler, 'uOffset', self.uOffset)
  1206. write_float(file_handler, 'vOffset', self.vOffset)
  1207. write_float(file_handler, 'uScale', self.uScale)
  1208. write_float(file_handler, 'vScale', self.vScale)
  1209. write_float(file_handler, 'uAng', self.uAng)
  1210. write_float(file_handler, 'vAng', self.vAng)
  1211. write_float(file_handler, 'wAng', self.wAng)
  1212. write_int(file_handler, 'wrapU', self.wrapU)
  1213. write_int(file_handler, 'wrapV', self.wrapV)
  1214. write_int(file_handler, 'coordinatesIndex', self.coordinatesIndex)
  1215. file_handler.write('}')
  1216. #===============================================================================
  1217. class Material:
  1218. def __init__(self, material, scene, filepath):
  1219. self.name = BabylonExporter.nameSpace + '.' + material.name
  1220. BabylonExporter.log('processing begun of material: ' + self.name)
  1221. self.ambient = material.ambient * material.diffuse_color
  1222. self.diffuse = material.diffuse_intensity * material.diffuse_color
  1223. self.specular = material.specular_intensity * material.specular_color
  1224. self.emissive = material.emit * material.diffuse_color
  1225. self.specularPower = material.specular_hardness
  1226. self.alpha = material.alpha
  1227. self.backFaceCulling = material.game_settings.use_backface_culling
  1228. # Textures
  1229. self.textures = []
  1230. textures = [mtex for mtex in material.texture_slots if mtex and mtex.texture]
  1231. for mtex in textures:
  1232. if mtex.texture.type == 'IMAGE':
  1233. if mtex.texture.image:
  1234. if (mtex.use_map_color_diffuse and (mtex.texture_coords != 'REFLECTION')):
  1235. # Diffuse
  1236. BabylonExporter.log('Diffuse texture found');
  1237. self.textures.append(Texture('diffuseTexture', mtex.diffuse_color_factor, mtex, filepath))
  1238. if mtex.use_map_ambient:
  1239. # Ambient
  1240. BabylonExporter.log('Ambient texture found');
  1241. self.textures.append(Texture('ambientTexture', mtex.ambient_factor, mtex, filepath))
  1242. if mtex.use_map_alpha:
  1243. # Opacity
  1244. BabylonExporter.log('Opacity texture found');
  1245. self.textures.append(Texture('opacityTexture', mtex.alpha_factor, mtex, filepath))
  1246. if mtex.use_map_color_diffuse and (mtex.texture_coords == 'REFLECTION'):
  1247. # Reflection
  1248. BabylonExporter.log('Reflection texture found');
  1249. self.textures.append(Texture('reflectionTexture', mtex.diffuse_color_factor, mtex, filepath))
  1250. if mtex.use_map_emit:
  1251. # Emissive
  1252. BabylonExporter.log('Emissive texture found');
  1253. self.textures.append(Texture('emissiveTexture', mtex.emit_factor, mtex, filepath))
  1254. if mtex.use_map_normal:
  1255. # Bump
  1256. BabylonExporter.log('Bump texture found');
  1257. self.textures.append(Texture('bumpTexture', 1.0/mtex.normal_factor, mtex, filepath))
  1258. elif mtex.use_map_color_spec:
  1259. # Specular
  1260. BabylonExporter.log('Specular texture found');
  1261. self.textures.append(Texture('specularTexture', mtex.specular_color_factor, mtex, filepath))
  1262. else:
  1263. BabylonExporter.warn('WARNING texture type not currently supported: ' + mtex.texture.type + ', ignored.')
  1264. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1265. def to_scene_file(self, file_handler):
  1266. file_handler.write('{')
  1267. write_string(file_handler, 'name', self.name, True)
  1268. write_string(file_handler, 'id', self.name)
  1269. write_color(file_handler, 'ambient', self.ambient)
  1270. write_color(file_handler, 'diffuse', self.diffuse)
  1271. write_color(file_handler, 'specular', self.specular)
  1272. write_color(file_handler, 'emissive', self.emissive)
  1273. write_float(file_handler, 'specularPower', self.specularPower)
  1274. write_float(file_handler, 'alpha', self.alpha)
  1275. write_bool(file_handler, 'backFaceCulling', self.backFaceCulling)
  1276. for texSlot in self.textures:
  1277. texSlot.to_scene_file(file_handler)
  1278. file_handler.write('}')
  1279. #===============================================================================
  1280. class Animation:
  1281. def __init__(self, dataType, framePerSecond, loopBehavior, name, propertyInBabylon):
  1282. self.dataType = dataType
  1283. self.framePerSecond = framePerSecond
  1284. self.loopBehavior = loopBehavior
  1285. self.name = name
  1286. self.propertyInBabylon = propertyInBabylon
  1287. #keys
  1288. self.frames = []
  1289. self.values = [] # vector3 for ANIMATIONTYPE_VECTOR3 & matrices for ANIMATIONTYPE_MATRIX
  1290. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1291. # for auto animate
  1292. def get_first_frame(self):
  1293. return self.frames[0] if len(self.frames) > 0 else -1
  1294. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1295. # for auto animate
  1296. def get_last_frame(self):
  1297. return self.frames[len(self.frames) - 1] if len(self.frames) > 0 else -1
  1298. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1299. def to_scene_file(self, file_handler):
  1300. file_handler.write('{')
  1301. write_int(file_handler, 'dataType', self.dataType, True)
  1302. write_int(file_handler, 'framePerSecond', self.framePerSecond)
  1303. file_handler.write(',"keys":[')
  1304. first = True
  1305. for frame_idx in range(len(self.frames)):
  1306. if first != True:
  1307. file_handler.write(',')
  1308. first = False
  1309. file_handler.write('{')
  1310. write_int(file_handler, 'frame', self.frames[frame_idx], True)
  1311. value_idx = self.values[frame_idx]
  1312. if self.dataType == ANIMATIONTYPE_MATRIX:
  1313. write_matrix4(file_handler, 'values', value_idx)
  1314. elif self.dataType == ANIMATIONTYPE_QUATERNION:
  1315. write_quaternion(file_handler, 'values', value_idx)
  1316. else:
  1317. write_vector(file_handler, 'values', value_idx)
  1318. file_handler.write('}')
  1319. file_handler.write(']') # close keys
  1320. # put this at the end to make less crazy looking ]}]]]}}}}}}}]]]],
  1321. # since animation is also at the end of the bone, mesh, camera, or light
  1322. write_int(file_handler, 'loopBehavior', self.loopBehavior)
  1323. write_string(file_handler, 'name', self.name)
  1324. write_string(file_handler, 'property', self.propertyInBabylon)
  1325. file_handler.write('}')
  1326. #===============================================================================
  1327. class VectorAnimation(Animation):
  1328. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1329. super().__init__(ANIMATIONTYPE_VECTOR3, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1330. # capture built up from fcurves
  1331. frames = dict()
  1332. for fcurve in object.animation_data.action.fcurves:
  1333. if fcurve.data_path == attrInBlender:
  1334. for key in fcurve.keyframe_points:
  1335. frame = key.co.x
  1336. frames[frame] = 1
  1337. #for each frame (next step ==> set for key frames)
  1338. for Frame in sorted(frames):
  1339. self.frames.append(Frame)
  1340. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1341. self.values.append(scale_vector(getattr(object, attrInBlender), mult, xOffset))
  1342. #===============================================================================
  1343. class QuaternionAnimation(Animation):
  1344. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1345. super().__init__(ANIMATIONTYPE_QUATERNION, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1346. # capture built up from fcurves
  1347. frames = dict()
  1348. for fcurve in object.animation_data.action.fcurves:
  1349. if fcurve.data_path == attrInBlender:
  1350. for key in fcurve.keyframe_points:
  1351. frame = key.co.x
  1352. frames[frame] = 1
  1353. #for each frame (next step ==> set for key frames)
  1354. for Frame in sorted(frames):
  1355. self.frames.append(Frame)
  1356. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1357. self.values.append(post_rotate_quaternion(getattr(object, attrInBlender), xOffset))
  1358. #===============================================================================
  1359. class QuaternionToEulerAnimation(Animation):
  1360. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1361. super().__init__(ANIMATIONTYPE_VECTOR3, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1362. # capture built up from fcurves
  1363. frames = dict()
  1364. for fcurve in object.animation_data.action.fcurves:
  1365. if fcurve.data_path == attrInBlender:
  1366. for key in fcurve.keyframe_points:
  1367. frame = key.co.x
  1368. frames[frame] = 1
  1369. #for each frame (next step ==> set for key frames)
  1370. for Frame in sorted(frames):
  1371. self.frames.append(Frame)
  1372. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1373. quat = getattr(object, attrInBlender)
  1374. eul = quat.to_euler("XYZ")
  1375. self.values.append(scale_vector(eul, mult, xOffset))
  1376. #===============================================================================
  1377. # module level formatting methods, called from multiple classes
  1378. #===============================================================================
  1379. def legal_js_identifier(input):
  1380. out = ''
  1381. prefix = ''
  1382. for char in input:
  1383. if len(out) == 0:
  1384. if char in '0123456789':
  1385. # cannot take the chance that leading numbers being chopped of cause name conflicts, e.g (01.R & 02.R)
  1386. prefix += char
  1387. continue
  1388. elif char.upper() not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
  1389. continue
  1390. legal = char if char.upper() in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_' else '_'
  1391. out += legal
  1392. if len(prefix) > 0:
  1393. out += '_' + prefix
  1394. return out
  1395. def format_f(num):
  1396. s = MAX_FLOAT_PRECISION % num # rounds to N decimal places while changing to string
  1397. s = s.rstrip('0') # ignore trailing zeroes
  1398. s = s.rstrip('.') # ignore trailing .
  1399. return '0' if s == '-0' else s
  1400. def format_matrix4(matrix):
  1401. tempMatrix = matrix.copy()
  1402. tempMatrix.transpose()
  1403. ret = ''
  1404. first = True
  1405. for vect in tempMatrix:
  1406. if (first != True):
  1407. ret +=','
  1408. first = False;
  1409. ret += format_f(vect[0]) + ',' + format_f(vect[1]) + ',' + format_f(vect[2]) + ',' + format_f(vect[3])
  1410. return ret
  1411. def format_array3(array):
  1412. return format_f(array[0]) + ',' + format_f(array[1]) + ',' + format_f(array[2])
  1413. def format_array(array, max_per_line = MAX_VERTEX_ELEMENTS, indent = ''):
  1414. ret = ''
  1415. first = True
  1416. nOnLine = 0
  1417. for element in array:
  1418. if (first != True):
  1419. ret +=','
  1420. first = False;
  1421. ret += format_f(element)
  1422. nOnLine += 1
  1423. if nOnLine >= max_per_line:
  1424. ret += '\n' + indent
  1425. nOnLine = 0
  1426. return ret
  1427. def format_color(color):
  1428. return format_f(color.r) + ',' + format_f(color.g) + ',' + format_f(color.b)
  1429. def format_vector(vector):
  1430. return format_f(vector.x) + ',' + format_f(vector.z) + ',' + format_f(vector.y)
  1431. def format_vector_array(vectorArray, max_per_line = MAX_VERTEX_ELEMENTS, indent = ''):
  1432. ret = ''
  1433. first = True
  1434. nOnLine = 0
  1435. for vector in vectorArray:
  1436. if (first != True):
  1437. ret +=','
  1438. first = False;
  1439. ret += format_vector(vector)
  1440. nOnLine += 3
  1441. if nOnLine >= max_per_line:
  1442. ret += '\n' + indent
  1443. nOnLine = 0
  1444. return ret
  1445. def format_quaternion(quaternion):
  1446. return format_f(quaternion.x) + ',' + format_f(quaternion.z) + ',' + format_f(quaternion.y) + ',' + format_f(-quaternion.w)
  1447. def format_int(int):
  1448. candidate = str(int) # when int string of an int
  1449. if '.' in candidate:
  1450. return format_f(math.floor(int)) # format_f removes un-neccessary precision
  1451. else:
  1452. return candidate
  1453. def format_bool(bool):
  1454. if bool:
  1455. return 'true'
  1456. else:
  1457. return 'false'
  1458. def scale_vector(vector, mult, xOffset = 0):
  1459. ret = vector.copy()
  1460. ret.x *= mult
  1461. ret.x += xOffset
  1462. ret.z *= mult
  1463. ret.y *= mult
  1464. return ret
  1465. def same_vertex(vertA, vertB):
  1466. return vertA.x == vertB.x and vertA.y == vertB.y and vertA.z == vertB.z
  1467. def post_rotate_quaternion(quat, angle):
  1468. post = mathutils.Euler((angle, 0.0, 0.0)).to_matrix()
  1469. mqtn = quat.to_matrix()
  1470. quat = (mqtn*post).to_quaternion()
  1471. return quat
  1472. #===============================================================================
  1473. # module level methods for writing JSON (.babylon) files
  1474. #===============================================================================
  1475. def write_matrix4(file_handler, name, matrix):
  1476. file_handler.write(',"' + name + '":[' + format_matrix4(matrix) + ']')
  1477. def write_array(file_handler, name, array):
  1478. file_handler.write('\n,"' + name + '":[' + format_array(array) + ']')
  1479. def write_array3(file_handler, name, array):
  1480. file_handler.write(',"' + name + '":[' + format_array3(array) + ']')
  1481. def write_color(file_handler, name, color):
  1482. file_handler.write(',"' + name + '":[' + format_color(color) + ']')
  1483. def write_vector(file_handler, name, vector):
  1484. file_handler.write(',"' + name + '":[' + format_vector(vector) + ']')
  1485. def write_vector_array(file_handler, name, vectorArray):
  1486. file_handler.write('\n,"' + name + '":[' + format_vector_array(vectorArray) + ']')
  1487. def write_quaternion(file_handler, name, quaternion):
  1488. file_handler.write(',"' + name +'":[' + format_quaternion(quaternion) + ']')
  1489. def write_string(file_handler, name, string, noComma = False):
  1490. if noComma == False:
  1491. file_handler.write(',')
  1492. file_handler.write('"' + name + '":"' + string + '"')
  1493. def write_float(file_handler, name, float):
  1494. file_handler.write(',"' + name + '":' + format_f(float))
  1495. def write_int(file_handler, name, int, noComma = False):
  1496. if noComma == False:
  1497. file_handler.write(',')
  1498. file_handler.write('"' + name + '":' + format_int(int))
  1499. def write_bool(file_handler, name, bool, noComma = False):
  1500. if noComma == False:
  1501. file_handler.write(',')
  1502. file_handler.write('"' + name + '":' + format_bool(bool))
  1503. #===============================================================================
  1504. # custom properties definition and display
  1505. #===============================================================================
  1506. bpy.types.Mesh.autoAnimate = bpy.props.BoolProperty(
  1507. name='Automatically launch animations',
  1508. description='',
  1509. default = False
  1510. )
  1511. bpy.types.Mesh.useFlatShading = bpy.props.BoolProperty(
  1512. name='Use Flat Shading',
  1513. description='',
  1514. default = False
  1515. )
  1516. bpy.types.Mesh.checkCollisions = bpy.props.BoolProperty(
  1517. name='Check Collisions',
  1518. description='Indicates mesh should be checked that it does not run into anything.',
  1519. default = False
  1520. )
  1521. bpy.types.Mesh.castShadows = bpy.props.BoolProperty(
  1522. name='Cast Shadows',
  1523. description='',
  1524. default = False
  1525. )
  1526. bpy.types.Mesh.receiveShadows = bpy.props.BoolProperty(
  1527. name='Receive Shadows',
  1528. description='',
  1529. default = False
  1530. )
  1531. bpy.types.Mesh.attachedSound = bpy.props.StringProperty(
  1532. name='Sound',
  1533. description='',
  1534. default = ''
  1535. )
  1536. bpy.types.Mesh.loopSound = bpy.props.BoolProperty(
  1537. name='Loop sound',
  1538. description='',
  1539. default = True
  1540. )
  1541. bpy.types.Mesh.autoPlaySound = bpy.props.BoolProperty(
  1542. name='Auto play sound',
  1543. description='',
  1544. default = True
  1545. )
  1546. bpy.types.Mesh.maxSoundDistance = bpy.props.FloatProperty(
  1547. name='Max sound distance',
  1548. description='',
  1549. default = 100
  1550. )
  1551. #===============================================================================
  1552. bpy.types.Camera.autoAnimate = bpy.props.BoolProperty(
  1553. name='Automatically launch animations',
  1554. description='',
  1555. default = False
  1556. )
  1557. bpy.types.Camera.CameraType = bpy.props.EnumProperty(
  1558. name='Camera Type',
  1559. description='',
  1560. # ONLY Append, or existing .blends will have their camera changed
  1561. items = (
  1562. (V_JOYSTICKS_CAM , 'Virtual Joysticks' , 'Use Virtual Joysticks Camera'),
  1563. (TOUCH_CAM , 'Touch' , 'Use Touch Camera'),
  1564. (GAMEPAD_CAM , 'Gamepad' , 'Use Gamepad Camera'),
  1565. (FREE_CAM , 'Free' , 'Use Free Camera'),
  1566. (FOLLOW_CAM , 'Follow' , 'Use Follow Camera'),
  1567. (DEV_ORIENT_CAM , 'Device Orientation' , 'Use Device Orientation Camera'),
  1568. (ARC_ROTATE_CAM , 'Arc Rotate' , 'Use Arc Rotate Camera'),
  1569. (ANAGLYPH_FREE_CAM , 'Anaglyph Free' , 'Use Anaglyph Free Camera'),
  1570. (ANAGLYPH_ARC_CAM , 'Anaglyph Arc Rotate' , 'Use Anaglyph Arc Rotate Camera'),
  1571. (VR_DEV_ORIENT_FREE_CAM , 'VR Dev Orientation Free' , 'Use VR Dev Orientation Free Camera'),
  1572. (WEB_VR_FREE_CAM , 'Web VR Free' , 'Use Web VR Free Camera')
  1573. ),
  1574. default = FREE_CAM
  1575. )
  1576. bpy.types.Camera.checkCollisions = bpy.props.BoolProperty(
  1577. name='Check Collisions',
  1578. description='',
  1579. default = False
  1580. )
  1581. bpy.types.Camera.applyGravity = bpy.props.BoolProperty(
  1582. name='Apply Gravity',
  1583. description='',
  1584. default = False
  1585. )
  1586. bpy.types.Camera.ellipsoid = bpy.props.FloatVectorProperty(
  1587. name='Ellipsoid',
  1588. description='',
  1589. default = mathutils.Vector((0.2, 0.9, 0.2))
  1590. )
  1591. bpy.types.Camera.anaglyphEyeSpace = bpy.props.IntProperty(
  1592. name='Anaglyph Eye space',
  1593. description='Used by the Anaglyph Arc Rotate camera',
  1594. default = 1
  1595. )
  1596. #===============================================================================
  1597. bpy.types.Lamp.autoAnimate = bpy.props.BoolProperty(
  1598. name='Automatically launch animations',
  1599. description='',
  1600. default = False
  1601. )
  1602. bpy.types.Lamp.shadowMap = bpy.props.EnumProperty(
  1603. name='Shadow Map Type',
  1604. description='',
  1605. items = (('NONE', 'None', 'No Shadow Maps'), ('STD', 'Standard', 'Use Standard Shadow Maps'), ('VAR', 'Variance', 'Use Variance Shadow Maps')),
  1606. default = 'NONE'
  1607. )
  1608. bpy.types.Lamp.shadowMapSize = bpy.props.IntProperty(
  1609. name='Shadow Map Size',
  1610. description='',
  1611. default = 512
  1612. )
  1613. class ObjectPanel(bpy.types.Panel):
  1614. bl_label = 'Babylon.js'
  1615. bl_space_type = 'PROPERTIES'
  1616. bl_region_type = 'WINDOW'
  1617. bl_context = 'data'
  1618. def draw(self, context):
  1619. ob = context.object
  1620. if not ob or not ob.data:
  1621. return
  1622. layout = self.layout
  1623. isMesh = isinstance(ob.data, bpy.types.Mesh)
  1624. isCamera = isinstance(ob.data, bpy.types.Camera)
  1625. isLight = isinstance(ob.data, bpy.types.Lamp)
  1626. if isMesh:
  1627. layout.prop(ob.data, 'useFlatShading')
  1628. layout.prop(ob.data, 'checkCollisions')
  1629. layout.prop(ob.data, 'castShadows')
  1630. layout.prop(ob.data, 'receiveShadows')
  1631. layout.separator()
  1632. layout.prop(ob.data, 'autoAnimate')
  1633. layout.separator()
  1634. layout.prop(ob.data, 'attachedSound')
  1635. layout.prop(ob.data, 'autoPlaySound')
  1636. layout.prop(ob.data, 'loopSound')
  1637. layout.prop(ob.data, 'maxSoundDistance')
  1638. elif isCamera:
  1639. layout.prop(ob.data, 'CameraType')
  1640. layout.prop(ob.data, 'checkCollisions')
  1641. layout.prop(ob.data, 'applyGravity')
  1642. layout.prop(ob.data, 'ellipsoid')
  1643. layout.separator()
  1644. layout.prop(ob.data, 'anaglyphEyeSpace')
  1645. layout.separator()
  1646. layout.prop(ob.data, 'autoAnimate')
  1647. elif isLight:
  1648. layout.prop(ob.data, 'shadowMap')
  1649. layout.prop(ob.data, 'shadowMapSize')
  1650. layout.separator()
  1651. layout.prop(ob.data, 'autoAnimate')