io_export_babylon.py 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931
  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.world_ambient = world.ambient_color
  395. else:
  396. self.world_ambient = mathutils.Color((0.2, 0.2, 0.3))
  397. self.gravity = scene.gravity
  398. if world and world.mist_settings.use_mist:
  399. self.fogMode = FOGMODE_LINEAR
  400. self.fogColor = world.horizon_color
  401. self.fogStart = world.mist_settings.start
  402. self.fogEnd = world.mist_settings.depth
  403. self.fogDensity = 0.1
  404. BabylonExporter.log('Python World class constructor completed')
  405. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  406. def to_scene_file(self, file_handler):
  407. write_bool(file_handler, 'autoClear', self.autoClear, True)
  408. write_color(file_handler, 'clearColor', self.world_ambient)
  409. write_color(file_handler, 'ambientColor', self.world_ambient)
  410. write_vector(file_handler, 'gravity', self.gravity)
  411. if hasattr(self, 'fogMode'):
  412. write_int(file_handler, 'fogMode', self.fogMode)
  413. write_color(file_handler, 'fogColor', self.fogColor)
  414. write_float(file_handler, 'fogStart', self.fogStart)
  415. write_float(file_handler, 'fogEnd', self.fogEnd)
  416. write_float(file_handler, 'fogDensity', self.fogDensity)
  417. #===============================================================================
  418. class FCurveAnimatable:
  419. def __init__(self, object, supportsRotation, supportsPosition, supportsScaling, xOffsetForRotation = 0):
  420. # just because a sub-class can be animatable does not mean it is
  421. self.animationsPresent = object.animation_data and object.animation_data.action
  422. rotAnim = False
  423. locAnim = False
  424. scaAnim = False
  425. useQuat = object.rotation_mode=='QUATERNION'
  426. if (self.animationsPresent):
  427. BabylonExporter.log('FCurve animation processing begun for: ' + object.name, 1)
  428. self.animations = []
  429. for fcurve in object.animation_data.action.fcurves:
  430. if supportsRotation and fcurve.data_path == 'rotation_euler' and rotAnim == False and useQuat == False:
  431. self.animations.append(VectorAnimation(object, 'rotation_euler', 'rotation', -1, xOffsetForRotation))
  432. rotAnim = True
  433. elif supportsRotation and fcurve.data_path == 'rotation_quaternion' and rotAnim == False and useQuat == True:
  434. anim = None
  435. if object.type == 'CAMERA':
  436. # if it's a camera, convert quaternions to euler XYZ
  437. anim = QuaternionToEulerAnimation(object, 'rotation_quaternion', 'rotation', -1, xOffsetForRotation)
  438. else:
  439. anim = QuaternionAnimation(object, 'rotation_quaternion', 'rotationQuaternion', 1, xOffsetForRotation)
  440. self.animations.append(anim)
  441. rotAnim = True
  442. elif supportsPosition and fcurve.data_path == 'location' and locAnim == False:
  443. self.animations.append(VectorAnimation(object, 'location', 'position', 1))
  444. locAnim = True
  445. elif supportsScaling and fcurve.data_path == 'scale' and scaAnim == False:
  446. self.animations.append(VectorAnimation(object, 'scale', 'scaling', 1))
  447. scaAnim = True
  448. #Set Animations
  449. if (hasattr(object.data, "autoAnimate") and object.data.autoAnimate):
  450. self.autoAnimate = True
  451. self.autoAnimateFrom = bpy.context.scene.frame_end
  452. self.autoAnimateTo = 0
  453. for animation in self.animations:
  454. if self.autoAnimateFrom > animation.get_first_frame():
  455. self.autoAnimateFrom = animation.get_first_frame()
  456. if self.autoAnimateTo < animation.get_last_frame():
  457. self.autoAnimateTo = animation.get_last_frame()
  458. self.autoAnimateLoop = True
  459. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  460. def to_scene_file(self, file_handler):
  461. if (self.animationsPresent):
  462. file_handler.write('\n,"animations":[')
  463. first = True
  464. for animation in self.animations:
  465. if first == False:
  466. file_handler.write(',')
  467. animation.to_scene_file(file_handler)
  468. first = False
  469. file_handler.write(']')
  470. if (hasattr(self, "autoAnimate") and self.autoAnimate):
  471. write_bool(file_handler, 'autoAnimate', self.autoAnimate)
  472. write_int(file_handler, 'autoAnimateFrom', self.autoAnimateFrom)
  473. write_int(file_handler, 'autoAnimateTo', self.autoAnimateTo)
  474. write_bool(file_handler, 'autoAnimateLoop', self.autoAnimateLoop)
  475. #===============================================================================
  476. class Mesh(FCurveAnimatable):
  477. def __init__(self, object, scene, multiMaterials, startFace, forcedParent, nameID, noVertexOpt):
  478. super().__init__(object, True, True, True) #Should animations be done when forcedParent
  479. self.name = object.name + str(nameID)
  480. BabylonExporter.log('processing begun of mesh: ' + self.name)
  481. self.isVisible = not object.hide_render
  482. self.isEnabled = True
  483. self.useFlatShading = object.data.useFlatShading
  484. self.checkCollisions = object.data.checkCollisions
  485. self.receiveShadows = object.data.receiveShadows
  486. self.castShadows = object.data.castShadows
  487. if forcedParent is None:
  488. self.dataName = object.data.name # used to support shared vertex instances in later passed
  489. if object.parent and object.parent.type != 'ARMATURE':
  490. self.parentId = object.parent.name
  491. else:
  492. self.dataName = self.name
  493. self.parentId = forcedParent.name
  494. # Physics
  495. if object.rigid_body != None:
  496. shape_items = {'SPHERE' : SPHERE_IMPOSTER,
  497. 'BOX' : BOX_IMPOSTER,
  498. 'MESH' : MESH_IMPOSTER,
  499. 'CAPSULE' : CAPSULE_IMPOSTER,
  500. 'CONE' : CONE_IMPOSTER,
  501. 'CYLINDER' : CYLINDER_IMPOSTER,
  502. 'CONVEX_HULL': CONVEX_HULL_IMPOSTER}
  503. shape_type = shape_items[object.rigid_body.collision_shape]
  504. self.physicsImpostor = shape_type
  505. mass = object.rigid_body.mass
  506. if mass < 0.005:
  507. mass = 0
  508. self.physicsMass = mass
  509. self.physicsFriction = object.rigid_body.friction
  510. self.physicsRestitution = object.rigid_body.restitution
  511. # hasSkeleton detection & skeletonID determination
  512. hasSkeleton = False
  513. objArmature = None # if there's an armature, this will be the one!
  514. if len(object.vertex_groups) > 0:
  515. objArmature = object.find_armature()
  516. if objArmature != None:
  517. hasSkeleton = True
  518. i = 0
  519. for obj in scene.objects:
  520. if obj.type == "ARMATURE":
  521. if obj == objArmature:
  522. self.skeletonId = i
  523. break
  524. else:
  525. i += 1
  526. # detect if any textures in the material slots, which would mean UV mapping is required
  527. uvRequired = False
  528. for slot in object.material_slots:
  529. uvRequired |= BabylonExporter.uvRequiredForMaterial(slot.name)
  530. if len(object.material_slots) == 1:
  531. self.materialId = BabylonExporter.nameSpace + '.' + object.material_slots[0].name
  532. self.billboardMode = BILLBOARDMODE_ALL if object.material_slots[0].material.game_settings.face_orientation == 'BILLBOARD' else BILLBOARDMODE_NONE;
  533. elif len(object.material_slots) > 1:
  534. multimat = MultiMaterial(object.material_slots, len(multiMaterials))
  535. self.materialId = multimat.name
  536. multiMaterials.append(multimat)
  537. self.billboardMode = BILLBOARDMODE_NONE
  538. else:
  539. self.billboardMode = BILLBOARDMODE_NONE
  540. BabylonExporter.warn('WARNING: No materials have been assigned: ', 2)
  541. # Get mesh
  542. mesh = object.to_mesh(scene, True, 'PREVIEW')
  543. # use defaults when not None
  544. if forcedParent is None:
  545. # Use local matrix
  546. locMatrix = object.matrix_local
  547. if objArmature != None:
  548. # unless the armature is the parent
  549. if object.parent and object.parent == objArmature:
  550. locMatrix = object.matrix_world * object.parent.matrix_world.inverted()
  551. loc, rot, scale = locMatrix.decompose()
  552. self.position = loc
  553. if object.rotation_mode == 'QUATERNION':
  554. self.rotationQuaternion = rot
  555. else:
  556. self.rotation = scale_vector(rot.to_euler('XYZ'), -1)
  557. self.scaling = scale
  558. else:
  559. self.position = mathutils.Vector((0, 0, 0))
  560. self.rotation = scale_vector(mathutils.Vector((0, 0, 0)), 1) # isn't scaling 0's by 1 same as 0?
  561. self.scaling = mathutils.Vector((1, 1, 1))
  562. # Triangulate mesh if required
  563. Mesh.mesh_triangulate(mesh)
  564. # Getting vertices and indices
  565. self.positions = []
  566. self.normals = []
  567. self.uvs = [] # not always used
  568. self.uvs2 = [] # not always used
  569. self.colors = [] # not always used
  570. self.indices = []
  571. self.subMeshes = []
  572. hasUV = len(mesh.tessface_uv_textures) > 0
  573. if hasUV:
  574. UVmap = mesh.tessface_uv_textures[0].data
  575. hasUV2 = len(mesh.tessface_uv_textures) > 1
  576. if hasUV2:
  577. UV2map = mesh.tessface_uv_textures[1].data
  578. hasVertexColor = len(mesh.vertex_colors) > 0
  579. if hasVertexColor:
  580. Colormap = mesh.tessface_vertex_colors.active.data
  581. if hasSkeleton:
  582. self.skeletonWeights = []
  583. self.skeletonIndicesCompressed = []
  584. # used tracking of vertices as they are received
  585. alreadySavedVertices = []
  586. vertices_UVs = []
  587. vertices_UV2s = []
  588. vertices_Colors = []
  589. vertices_indices = []
  590. self.offsetFace = 0
  591. for v in range(0, len(mesh.vertices)):
  592. alreadySavedVertices.append(False)
  593. vertices_UVs.append([])
  594. vertices_UV2s.append([])
  595. vertices_Colors.append([])
  596. vertices_indices.append([])
  597. materialsCount = max(1, len(object.material_slots))
  598. verticesCount = 0
  599. indicesCount = 0
  600. for materialIndex in range(materialsCount):
  601. if self.offsetFace != 0:
  602. break
  603. subMeshVerticesStart = verticesCount
  604. subMeshIndexStart = indicesCount
  605. for faceIndex in range(startFace, len(mesh.tessfaces)): # For each face
  606. face = mesh.tessfaces[faceIndex]
  607. if face.material_index != materialIndex:
  608. continue
  609. if verticesCount + 3 > MAX_VERTEX_ELEMENTS:
  610. self.offsetFace = faceIndex
  611. break
  612. for v in range(3): # For each vertex in face
  613. vertex_index = face.vertices[v]
  614. vertex = mesh.vertices[vertex_index]
  615. position = vertex.co
  616. normal = vertex.normal
  617. #skeletons
  618. if hasSkeleton:
  619. matricesWeights = []
  620. matricesWeights.append(0.0)
  621. matricesWeights.append(0.0)
  622. matricesWeights.append(0.0)
  623. matricesWeights.append(0.0)
  624. matricesIndicesCompressed = 0
  625. # Getting influences
  626. i = 0
  627. offset = 0
  628. for group in vertex.groups:
  629. index = group.group
  630. weight = group.weight
  631. for boneIndex, bone in enumerate(objArmature.pose.bones):
  632. if object.vertex_groups[index].name == bone.name:
  633. if (i == MAX_INFLUENCERS_PER_VERTEX):
  634. BabylonExporter.warn('WARNING: Maximum # of influencers exceeded for a vertex, extras ignored', 2)
  635. break
  636. matricesWeights[i] = weight
  637. matricesIndicesCompressed += boneIndex << offset
  638. offset = offset + 8
  639. i = i + 1
  640. # Texture coordinates
  641. if hasUV:
  642. vertex_UV = UVmap[face.index].uv[v]
  643. if hasUV2:
  644. vertex_UV2 = UV2map[face.index].uv[v]
  645. # Vertex color
  646. if hasVertexColor:
  647. if v == 0:
  648. vertex_Color = Colormap[face.index].color1
  649. if v == 1:
  650. vertex_Color = Colormap[face.index].color2
  651. if v == 2:
  652. vertex_Color = Colormap[face.index].color3
  653. # Check if the current vertex is already saved
  654. alreadySaved = alreadySavedVertices[vertex_index] and not (hasSkeleton or noVertexOpt)
  655. if alreadySaved:
  656. alreadySaved = False
  657. # UV
  658. index_UV = 0
  659. for savedIndex in vertices_indices[vertex_index]:
  660. if hasUV:
  661. vUV = vertices_UVs[vertex_index][index_UV]
  662. if (vUV[0] != vertex_UV[0] or vUV[1] != vertex_UV[1]):
  663. continue
  664. if hasUV2:
  665. vUV2 = vertices_UV2s[vertex_index][index_UV]
  666. if (vUV2[0] != vertex_UV2[0] or vUV2[1] != vertex_UV2[1]):
  667. continue
  668. if hasVertexColor:
  669. vColor = vertices_Colors[vertex_index][index_UV]
  670. if (vColor.r != vertex_Color.r or vColor.g != vertex_Color.g or vColor.b != vertex_Color.b):
  671. continue
  672. if vertices_indices[vertex_index][index_UV] >= subMeshVerticesStart:
  673. alreadySaved = True
  674. break
  675. index_UV += 1
  676. if (alreadySaved):
  677. # Reuse vertex
  678. index = vertices_indices[vertex_index][index_UV]
  679. else:
  680. # Export new one
  681. index = verticesCount
  682. alreadySavedVertices[vertex_index] = True
  683. if hasUV:
  684. vertices_UVs[vertex_index].append(vertex_UV)
  685. self.uvs.append(vertex_UV[0])
  686. self.uvs.append(vertex_UV[1])
  687. if hasUV2:
  688. vertices_UV2s[vertex_index].append(vertex_UV2)
  689. self.uvs2.append(vertex_UV2[0])
  690. self.uvs2.append(vertex_UV2[1])
  691. if hasVertexColor:
  692. vertices_Colors[vertex_index].append(vertex_Color)
  693. self.colors.append(vertex_Color.r)
  694. self.colors.append(vertex_Color.g)
  695. self.colors.append(vertex_Color.b)
  696. self.colors.append(1.0)
  697. if hasSkeleton:
  698. self.skeletonWeights.append(matricesWeights[0])
  699. self.skeletonWeights.append(matricesWeights[1])
  700. self.skeletonWeights.append(matricesWeights[2])
  701. self.skeletonWeights.append(matricesWeights[3])
  702. self.skeletonIndicesCompressed.append(matricesIndicesCompressed)
  703. vertices_indices[vertex_index].append(index)
  704. self.positions.append(position)
  705. self.normals.append(normal)
  706. verticesCount += 1
  707. self.indices.append(index)
  708. indicesCount += 1
  709. self.subMeshes.append(SubMesh(materialIndex, subMeshVerticesStart, subMeshIndexStart, verticesCount - subMeshVerticesStart, indicesCount - subMeshIndexStart))
  710. BabylonExporter.log('num positions : ' + str(len(self.positions)), 2)
  711. BabylonExporter.log('num normals : ' + str(len(self.normals )), 2)
  712. BabylonExporter.log('num uvs : ' + str(len(self.uvs )), 2)
  713. BabylonExporter.log('num uvs2 : ' + str(len(self.uvs2 )), 2)
  714. BabylonExporter.log('num colors : ' + str(len(self.colors )), 2)
  715. BabylonExporter.log('num indices : ' + str(len(self.indices )), 2)
  716. if hasattr(self, 'skeletonWeights'):
  717. BabylonExporter.log('num skeletonWeights: ' + str(len(self.skeletonWeights)), 2)
  718. BabylonExporter.log('num skeletonIndices: ' + str(len(self.skeletonIndicesCompressed * 4)), 2)
  719. if uvRequired and len(self.uvs) == 0:
  720. BabylonExporter.warn('WARNING: textures being used, but no UV Map found', 2)
  721. numZeroAreaFaces = self.find_zero_area_faces()
  722. if numZeroAreaFaces > 0:
  723. BabylonExporter.warn('WARNING: # of 0 area faces found: ' + str(numZeroAreaFaces), 2)
  724. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  725. def find_zero_area_faces(self):
  726. nFaces = int(len(self.indices) / 3)
  727. nZeroAreaFaces = 0
  728. for f in range(0, nFaces):
  729. faceOffset = f * 3
  730. p1 = self.positions[self.indices[faceOffset ]]
  731. p2 = self.positions[self.indices[faceOffset + 1]]
  732. p3 = self.positions[self.indices[faceOffset + 2]]
  733. if same_vertex(p1, p2) or same_vertex(p1, p3) or same_vertex(p2, p3): nZeroAreaFaces += 1
  734. return nZeroAreaFaces
  735. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  736. @staticmethod
  737. def mesh_triangulate(mesh):
  738. try:
  739. import bmesh
  740. bm = bmesh.new()
  741. bm.from_mesh(mesh)
  742. bmesh.ops.triangulate(bm, faces = bm.faces)
  743. bm.to_mesh(mesh)
  744. mesh.calc_tessface()
  745. bm.free()
  746. except:
  747. pass
  748. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  749. def to_scene_file(self, file_handler, meshesAndNodes):
  750. file_handler.write('{')
  751. write_string(file_handler, 'name', self.name, True)
  752. write_string(file_handler, 'id', self.name)
  753. if hasattr(self, 'parentId'): write_string(file_handler, 'parentId', self.parentId)
  754. if hasattr(self, 'materialId'): write_string(file_handler, 'materialId', self.materialId)
  755. write_int(file_handler, 'billboardMode', self.billboardMode)
  756. write_vector(file_handler, 'position', self.position)
  757. if hasattr(self, "rotationQuaternion"):
  758. write_quaternion(file_handler, 'rotationQuaternion', self.rotationQuaternion)
  759. else:
  760. write_vector(file_handler, 'rotation', self.rotation)
  761. write_vector(file_handler, 'scaling', self.scaling)
  762. write_bool(file_handler, 'isVisible', self.isVisible)
  763. write_bool(file_handler, 'isEnabled', self.isEnabled)
  764. write_bool(file_handler, 'useFlatShading', self.useFlatShading)
  765. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  766. write_bool(file_handler, 'receiveShadows', self.receiveShadows)
  767. if hasattr(self, 'physicsImpostor'):
  768. write_int(file_handler, 'physicsImpostor', self.physicsImpostor)
  769. write_float(file_handler, 'physicsMass', self.physicsMass)
  770. write_float(file_handler, 'physicsFriction', self.physicsFriction)
  771. write_float(file_handler, 'physicsRestitution', self.physicsRestitution)
  772. # Geometry
  773. if hasattr(self, 'skeletonId'): write_int(file_handler, 'skeletonId', self.skeletonId)
  774. write_vector_array(file_handler, 'positions', self.positions)
  775. write_vector_array(file_handler, 'normals' , self.normals )
  776. if len(self.uvs) > 0:
  777. write_array(file_handler, 'uvs', self.uvs)
  778. if len(self.uvs2) > 0:
  779. write_array(file_handler, 'uvs2', self.uvs2)
  780. if len(self.colors) > 0:
  781. write_array(file_handler, 'colors', self.colors)
  782. if hasattr(self, 'skeletonWeights'):
  783. write_array(file_handler, 'matricesWeights', self.skeletonWeights)
  784. write_array(file_handler, 'matricesIndices', self.skeletonIndicesCompressed)
  785. write_array(file_handler, 'indices', self.indices)
  786. # Sub meshes
  787. file_handler.write('\n,"subMeshes":[')
  788. first = True
  789. for subMesh in self.subMeshes:
  790. if first == False:
  791. file_handler.write(',')
  792. subMesh.to_scene_file(file_handler)
  793. first = False
  794. file_handler.write(']')
  795. super().to_scene_file(file_handler) # Animations
  796. # Instances
  797. first = True
  798. file_handler.write('\n,"instances":[')
  799. for mesh in meshesAndNodes:
  800. if hasattr(mesh, "dataName") and mesh.dataName == self.dataName and mesh != self: # nodes have no dataname, so no need to check for
  801. if first == False:
  802. file_handler.write(',')
  803. file_handler.write('{')
  804. write_string(file_handler, 'name', mesh.name, True)
  805. write_vector(file_handler, 'position', mesh.position)
  806. write_vector(file_handler, 'rotation', mesh.rotation)
  807. write_vector(file_handler, 'scaling', mesh.scaling)
  808. file_handler.write('}')
  809. first = False
  810. file_handler.write(']')
  811. # Close mesh
  812. file_handler.write('}\n')
  813. self.alreadyExported = True
  814. #===============================================================================
  815. class Node(FCurveAnimatable):
  816. def __init__(self, node):
  817. super().__init__(node, True, True, True) #Should animations be done when foredParent
  818. BabylonExporter.log('processing begun of node: ' + node.name)
  819. self.name = node.name
  820. if node.parent and node.parent.type != 'ARMATURE':
  821. self.parentId = node.parent.name
  822. loc, rot, scale = node.matrix_local.decompose()
  823. if node.parent != None:
  824. self.parentId = node.parent.name
  825. self.position = loc
  826. if node.rotation_mode == 'QUATERNION':
  827. self.rotationQuaternion = rot
  828. else:
  829. self.rotation = scale_vector(rot.to_euler('XYZ'), -1)
  830. self.scaling = scale
  831. self.isVisible = False
  832. self.isEnabled = True
  833. self.checkCollisions = False
  834. self.billboardMode = BILLBOARDMODE_NONE
  835. self.castShadows = False
  836. self.receiveShadows = False
  837. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  838. def get_proper_name(self):
  839. return legal_js_identifier(self.name)
  840. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  841. def to_scene_file(self, file_handler, ignored):
  842. file_handler.write('{')
  843. write_string(file_handler, 'name', self.name, True)
  844. write_string(file_handler, 'id', self.name)
  845. if hasattr(self, 'parentId'): write_string(file_handler, 'parentId', self.parentId)
  846. write_vector(file_handler, 'position', self.position)
  847. if hasattr(self, "rotationQuaternion"):
  848. write_quaternion(file_handler, "rotationQuaternion", self.rotationQuaternion)
  849. else:
  850. write_vector(file_handler, 'rotation', self.rotation)
  851. write_vector(file_handler, 'scaling', self.scaling)
  852. write_bool(file_handler, 'isVisible', self.isVisible)
  853. write_bool(file_handler, 'isEnabled', self.isEnabled)
  854. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  855. write_int(file_handler, 'billboardMode', self.billboardMode)
  856. write_bool(file_handler, 'receiveShadows', self.receiveShadows)
  857. super().to_scene_file(file_handler) # Animations
  858. file_handler.write('}')
  859. #===============================================================================
  860. class SubMesh:
  861. def __init__(self, materialIndex, verticesStart, indexStart, verticesCount, indexCount):
  862. self.materialIndex = materialIndex
  863. self.verticesStart = verticesStart
  864. self.indexStart = indexStart
  865. self.verticesCount = verticesCount
  866. self.indexCount = indexCount
  867. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  868. def to_scene_file(self, file_handler):
  869. file_handler.write('{')
  870. write_int(file_handler, 'materialIndex', self.materialIndex, True)
  871. write_int(file_handler, 'verticesStart', self.verticesStart)
  872. write_int(file_handler, 'verticesCount', self.verticesCount)
  873. write_int(file_handler, 'indexStart' , self.indexStart)
  874. write_int(file_handler, 'indexCount' , self.indexCount)
  875. file_handler.write('}')
  876. #===============================================================================
  877. class Bone:
  878. def __init__(self, bone, skeleton, scene, index):
  879. BabylonExporter.log('processing begun of bone: ' + bone.name + ', index: '+ str(index))
  880. self.name = bone.name
  881. self.index = index
  882. matrix_world = skeleton.matrix_world
  883. self.matrix = Bone.get_matrix(bone, matrix_world)
  884. parentId = -1
  885. if (bone.parent):
  886. for parent in skeleton.pose.bones:
  887. parentId += 1
  888. if parent == bone.parent:
  889. break;
  890. self.parentBoneIndex = parentId
  891. #animation
  892. if (skeleton.animation_data):
  893. BabylonExporter.log('animation begun of bone: ' + self.name)
  894. self.animation = Animation(ANIMATIONTYPE_MATRIX, scene.render.fps, ANIMATIONLOOPMODE_CYCLE, 'anim', '_matrix')
  895. start_frame = scene.frame_start
  896. end_frame = scene.frame_end
  897. previousBoneMatrix = None
  898. for frame in range(start_frame, end_frame + 1):
  899. bpy.context.scene.frame_set(frame)
  900. currentBoneMatrix = Bone.get_matrix(bone, matrix_world)
  901. if (frame != end_frame and currentBoneMatrix == previousBoneMatrix):
  902. continue
  903. self.animation.frames.append(frame)
  904. self.animation.values.append(Bone.get_matrix(bone, matrix_world))
  905. previousBoneMatrix = currentBoneMatrix
  906. bpy.context.scene.frame_set(start_frame)
  907. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  908. @staticmethod
  909. def get_matrix(bone, matrix_world):
  910. SystemMatrix = mathutils.Matrix.Scale(-1, 4, mathutils.Vector((0, 0, 1))) * mathutils.Matrix.Rotation(math.radians(-90), 4, 'X')
  911. if (bone.parent):
  912. return (SystemMatrix * matrix_world * bone.parent.matrix).inverted() * (SystemMatrix * matrix_world * bone.matrix)
  913. else:
  914. return SystemMatrix * matrix_world * bone.matrix
  915. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  916. def to_scene_file(self, file_handler):
  917. file_handler.write('\n{')
  918. write_string(file_handler, 'name', self.name, True)
  919. write_int(file_handler, 'index', self.index)
  920. write_matrix4(file_handler, 'matrix', self.matrix)
  921. write_int(file_handler, 'parentBoneIndex', self.parentBoneIndex)
  922. #animation
  923. if hasattr(self, 'animation'):
  924. file_handler.write(',"animation":')
  925. self.animation.to_scene_file(file_handler)
  926. file_handler.write('}')
  927. #===============================================================================
  928. class Skeleton:
  929. def __init__(self, skeleton, scene, id):
  930. BabylonExporter.log('processing begun of skeleton: ' + skeleton.name + ', id: '+ str(id))
  931. self.name = skeleton.name
  932. self.id = id
  933. self.bones = []
  934. bones = skeleton.pose.bones
  935. j = 0
  936. for bone in bones:
  937. self.bones.append(Bone(bone, skeleton, scene, j))
  938. j = j + 1
  939. BabylonExporter.log('processing complete of skeleton: ' + skeleton.name)
  940. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  941. def to_scene_file(self, file_handler):
  942. file_handler.write('{')
  943. write_string(file_handler, 'name', self.name, True)
  944. write_int(file_handler, 'id', self.id) # keep int for legacy of original exporter
  945. file_handler.write(',"bones":[')
  946. first = True
  947. for bone in self.bones:
  948. if first != True:
  949. file_handler.write(',')
  950. first = False
  951. bone.to_scene_file(file_handler)
  952. file_handler.write(']')
  953. file_handler.write('}')
  954. #===============================================================================
  955. class Camera(FCurveAnimatable):
  956. def __init__(self, camera):
  957. super().__init__(camera, True, True, False, math.pi / 2)
  958. if camera.parent and camera.parent.type != 'ARMATURE':
  959. self.parentId = camera.parent.name
  960. self.CameraType = camera.data.CameraType
  961. self.name = camera.name
  962. BabylonExporter.log('processing begun of camera (' + self.CameraType + '): ' + self.name)
  963. self.position = camera.location
  964. # for quaternions, convert to euler XYZ, otherwise, use the default rotation_euler
  965. eul = camera.rotation_quaternion.to_euler("XYZ") if camera.rotation_mode == 'QUATERNION' else camera.rotation_euler
  966. self.rotation = mathutils.Vector((-eul[0] + math.pi / 2, eul[1], -eul[2]))
  967. self.fov = camera.data.angle
  968. self.minZ = camera.data.clip_start
  969. self.maxZ = camera.data.clip_end
  970. self.speed = 1.0
  971. self.inertia = 0.9
  972. self.checkCollisions = camera.data.checkCollisions
  973. self.applyGravity = camera.data.applyGravity
  974. self.ellipsoid = camera.data.ellipsoid
  975. for constraint in camera.constraints:
  976. if constraint.type == 'TRACK_TO':
  977. self.lockedTargetId = constraint.target.name
  978. break
  979. if self.CameraType == ANAGLYPH_ARC_CAM or self.CameraType == ANAGLYPH_FREE_CAM:
  980. self.anaglyphEyeSpace = camera.data.anaglyphEyeSpace
  981. if self.CameraType == ANAGLYPH_ARC_CAM or self.CameraType == ARC_ROTATE_CAM or self.CameraType == FOLLOW_CAM:
  982. if not hasattr(self, 'lockedTargetId'):
  983. BabylonExporter.warn('ERROR: Camera type with manditory target specified, but no target to track set', 2)
  984. self.fatalProblem = True
  985. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  986. def update_for_target_attributes(self, meshesAndNodes):
  987. if not hasattr(self, 'lockedTargetId'): return
  988. # find the actual mesh tracking, so properties can be derrived
  989. targetFound = False
  990. for mesh in meshesAndNodes:
  991. if mesh.name == self.lockedTargetId:
  992. targetMesh = mesh
  993. targetFound = True
  994. break;
  995. xApart = 3 if not targetFound else self.position.x - targetMesh.position.x
  996. yApart = 3 if not targetFound else self.position.y - targetMesh.position.y
  997. zApart = 3 if not targetFound else self.position.z - targetMesh.position.z
  998. distance3D = math.sqrt(xApart * xApart + yApart * yApart + zApart * zApart)
  999. alpha = math.atan2(yApart, xApart);
  1000. beta = math.atan2(yApart, zApart);
  1001. if self.CameraType == FOLLOW_CAM:
  1002. self.followHeight = zApart
  1003. self.followDistance = distance3D
  1004. self.followRotation = 90 + (alpha * 180 / math.pi)
  1005. elif self.CameraType == ANAGLYPH_ARC_CAM or self.CameraType == ARC_ROTATE_CAM:
  1006. self.arcRotAlpha = alpha
  1007. self.arcRotBeta = beta
  1008. self.arcRotRadius = distance3D
  1009. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1010. def to_scene_file(self, file_handler):
  1011. file_handler.write('{')
  1012. write_string(file_handler, 'name', self.name, True)
  1013. write_string(file_handler, 'id', self.name)
  1014. write_vector(file_handler, 'position', self.position)
  1015. write_vector(file_handler, 'rotation', self.rotation)
  1016. write_float(file_handler, 'fov', self.fov)
  1017. write_float(file_handler, 'minZ', self.minZ)
  1018. write_float(file_handler, 'maxZ', self.maxZ)
  1019. write_float(file_handler, 'speed', self.speed)
  1020. write_float(file_handler, 'inertia', self.inertia)
  1021. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  1022. write_bool(file_handler, 'applyGravity', self.applyGravity)
  1023. write_array3(file_handler, 'ellipsoid', self.ellipsoid)
  1024. write_string(file_handler, 'type', self.CameraType)
  1025. if hasattr(self, 'parentId'): write_string(file_handler, 'parentId', self.parentId)
  1026. if self.CameraType == FOLLOW_CAM:
  1027. write_float(file_handler, 'heightOffset', self.followHeight)
  1028. write_float(file_handler, 'radius', self.followDistance)
  1029. write_float(file_handler, 'rotationOffset', self.followRotation)
  1030. elif self.CameraType == ANAGLYPH_ARC_CAM or self.CameraType == ARC_ROTATE_CAM:
  1031. write_float(file_handler, 'alpha', self.arcRotAlpha)
  1032. write_float(file_handler, 'beta', self.arcRotBeta)
  1033. write_float(file_handler, 'radius', self.arcRotRadius)
  1034. if self.CameraType == ANAGLYPH_ARC_CAM:
  1035. write_float(file_handler, 'eye_space', self.anaglyphEyeSpace)
  1036. elif self.CameraType == ANAGLYPH_FREE_CAM:
  1037. write_float(file_handler, 'eye_space', self.anaglyphEyeSpace)
  1038. if hasattr(self, 'lockedTargetId'):
  1039. write_string(file_handler, 'lockedTargetId', self.lockedTargetId)
  1040. super().to_scene_file(file_handler) # Animations
  1041. file_handler.write('}')
  1042. #===============================================================================
  1043. class Light(FCurveAnimatable):
  1044. def __init__(self, light):
  1045. super().__init__(light, False, True, False)
  1046. if light.parent and light.parent.type != 'ARMATURE':
  1047. self.parentId = light.parent.name
  1048. self.name = light.name
  1049. BabylonExporter.log('processing begun of light (' + light.data.type + '): ' + self.name)
  1050. light_type_items = {'POINT': POINT_LIGHT, 'SUN': DIRECTIONAL_LIGHT, 'SPOT': SPOT_LIGHT, 'HEMI': HEMI_LIGHT, 'AREA': 0}
  1051. self.light_type = light_type_items[light.data.type]
  1052. if self.light_type == POINT_LIGHT:
  1053. self.position = light.location
  1054. if hasattr(light.data, 'use_sphere'):
  1055. if light.data.use_sphere:
  1056. self.range = light.data.distance
  1057. elif self.light_type == DIRECTIONAL_LIGHT:
  1058. self.position = light.location
  1059. self.direction = Light.get_direction(light.matrix_local)
  1060. elif self.light_type == SPOT_LIGHT:
  1061. self.position = light.location
  1062. self.direction = Light.get_direction(light.matrix_local)
  1063. self.angle = light.data.spot_size
  1064. self.exponent = light.data.spot_blend * 2
  1065. if light.data.use_sphere:
  1066. self.range = light.data.distance
  1067. else:
  1068. # Hemi & Area
  1069. matrix_local = light.matrix_local.copy()
  1070. matrix_local.translation = mathutils.Vector((0, 0, 0))
  1071. self.direction = (mathutils.Vector((0, 0, -1)) * matrix_local)
  1072. self.direction = scale_vector(self.direction, -1)
  1073. self.groundColor = mathutils.Color((0, 0, 0))
  1074. self.intensity = light.data.energy
  1075. self.diffuse = light.data.color if light.data.use_diffuse else mathutils.Color((0, 0, 0))
  1076. self.specular = light.data.color if light.data.use_specular else mathutils.Color((0, 0, 0))
  1077. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1078. def to_scene_file(self, file_handler):
  1079. file_handler.write('{')
  1080. write_string(file_handler, 'name', self.name, True)
  1081. write_string(file_handler, 'id', self.name)
  1082. write_float(file_handler, 'type', self.light_type)
  1083. if hasattr(self, 'parentId' ): write_string(file_handler, 'parentId', self.parentId)
  1084. if hasattr(self, 'position' ): write_vector(file_handler, 'position' , self.position )
  1085. if hasattr(self, 'direction' ): write_vector(file_handler, 'direction' , self.direction )
  1086. if hasattr(self, 'angle' ): write_float (file_handler, 'angle' , self.angle )
  1087. if hasattr(self, 'exponent' ): write_float (file_handler, 'exponent' , self.exponent )
  1088. if hasattr(self, 'groundColor'): write_color (file_handler, 'groundColor', self.groundColor)
  1089. if hasattr(self, 'range' ): write_float (file_handler, 'range' , self.range )
  1090. write_float(file_handler, 'intensity', self.intensity)
  1091. write_color(file_handler, 'diffuse', self.diffuse)
  1092. write_color(file_handler, 'specular', self.specular)
  1093. super().to_scene_file(file_handler) # Animations
  1094. file_handler.write('}')
  1095. @staticmethod
  1096. def get_direction(matrix):
  1097. return (matrix.to_3x3() * mathutils.Vector((0.0, 0.0, -1.0))).normalized()
  1098. #===============================================================================
  1099. class ShadowGenerator:
  1100. def __init__(self, lamp, meshesAndNodes, scene):
  1101. BabylonExporter.log('processing begun of shadows for light: ' + lamp.name)
  1102. self.useVarianceShadowMap = lamp.data.shadowMap == 'VAR' if True else False
  1103. self.mapSize = lamp.data.shadowMapSize
  1104. self.lightId = lamp.name
  1105. self.shadowCasters = []
  1106. for mesh in meshesAndNodes:
  1107. if (mesh.castShadows):
  1108. self.shadowCasters.append(mesh.name)
  1109. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1110. def to_scene_file(self, file_handler):
  1111. file_handler.write('{')
  1112. write_bool(file_handler, 'useVarianceShadowMap', self.useVarianceShadowMap, True)
  1113. write_int(file_handler, 'mapSize', self.mapSize)
  1114. write_string(file_handler, 'lightId', self.lightId)
  1115. file_handler.write(',"renderList":[')
  1116. first = True
  1117. for caster in self.shadowCasters:
  1118. if first != True:
  1119. file_handler.write(',')
  1120. first = False
  1121. file_handler.write('"' + caster + '"')
  1122. file_handler.write(']')
  1123. file_handler.write('}')
  1124. #===============================================================================
  1125. class MultiMaterial:
  1126. def __init__(self, material_slots, idx):
  1127. self.name = BabylonExporter.nameSpace + '.' + 'Multimaterial#' + str(idx)
  1128. BabylonExporter.log('processing begun of multimaterial: ' + self.name, 2)
  1129. self.materials = []
  1130. for mat in material_slots:
  1131. self.materials.append(BabylonExporter.nameSpace + '.' + mat.name)
  1132. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1133. def to_scene_file(self, file_handler):
  1134. file_handler.write('{')
  1135. write_string(file_handler, 'name', self.name, True)
  1136. write_string(file_handler, 'id', self.name)
  1137. file_handler.write(',"materials":[')
  1138. first = True
  1139. for materialName in self.materials:
  1140. if first != True:
  1141. file_handler.write(',')
  1142. file_handler.write('"' + materialName +'"')
  1143. first = False
  1144. file_handler.write(']')
  1145. file_handler.write('}')
  1146. #===============================================================================
  1147. class Texture:
  1148. def __init__(self, slot, level, texture, filepath):
  1149. # Copy image to output
  1150. try:
  1151. image = texture.texture.image
  1152. imageFilepath = os.path.normpath(bpy.path.abspath(image.filepath))
  1153. basename = os.path.basename(imageFilepath)
  1154. targetdir = os.path.dirname(filepath)
  1155. targetpath = os.path.join(targetdir, basename)
  1156. if image.packed_file:
  1157. image.save_render(targetpath)
  1158. else:
  1159. sourcepath = bpy.path.abspath(image.filepath)
  1160. shutil.copy(sourcepath, targetdir)
  1161. except:
  1162. ex = sys.exc_info()
  1163. BabylonExporter.log_handler.write('Error encountered processing image file: ' + imageFilepath + ', Error: '+ str(ex[1]) + '\n')
  1164. #pass
  1165. # Export
  1166. self.slot = slot
  1167. self.name = basename
  1168. self.level = level
  1169. self.hasAlpha = texture.texture.use_alpha
  1170. if (texture.mapping == 'CUBE'):
  1171. self.coordinatesMode = CUBIC_MODE
  1172. if (texture.mapping == 'SPHERE'):
  1173. self.coordinatesMode = SPHERICAL_MODE
  1174. else:
  1175. self.coordinatesMode = EXPLICIT_MODE
  1176. self.uOffset = texture.offset.x
  1177. self.vOffset = texture.offset.y
  1178. self.uScale = texture.scale.x
  1179. self.vScale = texture.scale.y
  1180. self.uAng = 0
  1181. self.vAng = 0
  1182. self.wAng = 0
  1183. if (texture.texture.extension == 'REPEAT'):
  1184. if (texture.texture.use_mirror_x):
  1185. self.wrapU = MIRROR_ADDRESSMODE
  1186. else:
  1187. self.wrapU = WRAP_ADDRESSMODE
  1188. if (texture.texture.use_mirror_y):
  1189. self.wrapV = MIRROR_ADDRESSMODE
  1190. else:
  1191. self.wrapV = WRAP_ADDRESSMODE
  1192. else:
  1193. self.wrapU = CLAMP_ADDRESSMODE
  1194. self.wrapV = CLAMP_ADDRESSMODE
  1195. self.coordinatesIndex = 0
  1196. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1197. def to_scene_file(self, file_handler):
  1198. file_handler.write(', "' + self.slot + '":{')
  1199. write_string(file_handler, 'name', self.name, True)
  1200. write_float(file_handler, 'level', self.level)
  1201. write_float(file_handler, 'hasAlpha', self.hasAlpha)
  1202. write_int(file_handler, 'coordinatesMode', self.coordinatesMode)
  1203. write_float(file_handler, 'uOffset', self.uOffset)
  1204. write_float(file_handler, 'vOffset', self.vOffset)
  1205. write_float(file_handler, 'uScale', self.uScale)
  1206. write_float(file_handler, 'vScale', self.vScale)
  1207. write_float(file_handler, 'uAng', self.uAng)
  1208. write_float(file_handler, 'vAng', self.vAng)
  1209. write_float(file_handler, 'wAng', self.wAng)
  1210. write_int(file_handler, 'wrapU', self.wrapU)
  1211. write_int(file_handler, 'wrapV', self.wrapV)
  1212. write_int(file_handler, 'coordinatesIndex', self.coordinatesIndex)
  1213. file_handler.write('}')
  1214. #===============================================================================
  1215. class Material:
  1216. def __init__(self, material, scene, filepath):
  1217. self.name = BabylonExporter.nameSpace + '.' + material.name
  1218. BabylonExporter.log('processing begun of material: ' + self.name)
  1219. self.ambient = material.ambient * material.diffuse_color
  1220. self.diffuse = material.diffuse_intensity * material.diffuse_color
  1221. self.specular = material.specular_intensity * material.specular_color
  1222. self.emissive = material.emit * material.diffuse_color
  1223. self.specularPower = material.specular_hardness
  1224. self.alpha = material.alpha
  1225. self.backFaceCulling = material.game_settings.use_backface_culling
  1226. # Textures
  1227. self.textures = []
  1228. textures = [mtex for mtex in material.texture_slots if mtex and mtex.texture]
  1229. for mtex in textures:
  1230. if mtex.texture.type == 'IMAGE':
  1231. if mtex.texture.image:
  1232. if (mtex.use_map_color_diffuse and (mtex.texture_coords != 'REFLECTION')):
  1233. # Diffuse
  1234. BabylonExporter.log('Diffuse texture found');
  1235. self.textures.append(Texture('diffuseTexture', mtex.diffuse_color_factor, mtex, filepath))
  1236. if mtex.use_map_ambient:
  1237. # Ambient
  1238. BabylonExporter.log('Ambient texture found');
  1239. self.textures.append(Texture('ambientTexture', mtex.ambient_factor, mtex, filepath))
  1240. if mtex.use_map_alpha:
  1241. # Opacity
  1242. BabylonExporter.log('Opacity texture found');
  1243. self.textures.append(Texture('opacityTexture', mtex.alpha_factor, mtex, filepath))
  1244. if mtex.use_map_color_diffuse and (mtex.texture_coords == 'REFLECTION'):
  1245. # Reflection
  1246. BabylonExporter.log('Reflection texture found');
  1247. self.textures.append(Texture('reflectionTexture', mtex.diffuse_color_factor, mtex, filepath))
  1248. if mtex.use_map_emit:
  1249. # Emissive
  1250. BabylonExporter.log('Emissive texture found');
  1251. self.textures.append(Texture('emissiveTexture', mtex.emit_factor, mtex, filepath))
  1252. if mtex.use_map_normal:
  1253. # Bump
  1254. BabylonExporter.log('Bump texture found');
  1255. self.textures.append(Texture('bumpTexture', mtex.normal_factor, mtex, filepath))
  1256. elif mtex.use_map_color_spec:
  1257. # Specular
  1258. BabylonExporter.log('Specular texture found');
  1259. self.textures.append(Texture('specularTexture', mtex.specular_color_factor, mtex, filepath))
  1260. else:
  1261. BabylonExporter.warn('WARNING texture type not currently supported: ' + mtex.texture.type + ', ignored.')
  1262. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1263. def to_scene_file(self, file_handler):
  1264. file_handler.write('{')
  1265. write_string(file_handler, 'name', self.name, True)
  1266. write_string(file_handler, 'id', self.name)
  1267. write_color(file_handler, 'ambient', self.ambient)
  1268. write_color(file_handler, 'diffuse', self.diffuse)
  1269. write_color(file_handler, 'specular', self.specular)
  1270. write_color(file_handler, 'emissive', self.emissive)
  1271. write_float(file_handler, 'specularPower', self.specularPower)
  1272. write_float(file_handler, 'alpha', self.alpha)
  1273. write_bool(file_handler, 'backFaceCulling', self.backFaceCulling)
  1274. for texSlot in self.textures:
  1275. texSlot.to_scene_file(file_handler)
  1276. file_handler.write('}')
  1277. #===============================================================================
  1278. class Animation:
  1279. def __init__(self, dataType, framePerSecond, loopBehavior, name, propertyInBabylon):
  1280. self.dataType = dataType
  1281. self.framePerSecond = framePerSecond
  1282. self.loopBehavior = loopBehavior
  1283. self.name = name
  1284. self.propertyInBabylon = propertyInBabylon
  1285. #keys
  1286. self.frames = []
  1287. self.values = [] # vector3 for ANIMATIONTYPE_VECTOR3 & matrices for ANIMATIONTYPE_MATRIX
  1288. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1289. # for auto animate
  1290. def get_first_frame(self):
  1291. return self.frames[0] if len(self.frames) > 0 else -1
  1292. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1293. # for auto animate
  1294. def get_last_frame(self):
  1295. return self.frames[len(self.frames) - 1] if len(self.frames) > 0 else -1
  1296. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1297. def to_scene_file(self, file_handler):
  1298. file_handler.write('{')
  1299. write_int(file_handler, 'dataType', self.dataType, True)
  1300. write_int(file_handler, 'framePerSecond', self.framePerSecond)
  1301. file_handler.write(',"keys":[')
  1302. first = True
  1303. for frame_idx in range(len(self.frames)):
  1304. if first != True:
  1305. file_handler.write(',')
  1306. first = False
  1307. file_handler.write('{')
  1308. write_int(file_handler, 'frame', self.frames[frame_idx], True)
  1309. value_idx = self.values[frame_idx]
  1310. if self.dataType == ANIMATIONTYPE_MATRIX:
  1311. write_matrix4(file_handler, 'values', value_idx)
  1312. elif self.dataType == ANIMATIONTYPE_QUATERNION:
  1313. write_quaternion(file_handler, 'values', value_idx)
  1314. else:
  1315. write_vector(file_handler, 'values', value_idx)
  1316. file_handler.write('}')
  1317. file_handler.write(']') # close keys
  1318. # put this at the end to make less crazy looking ]}]]]}}}}}}}]]]],
  1319. # since animation is also at the end of the bone, mesh, camera, or light
  1320. write_int(file_handler, 'loopBehavior', self.loopBehavior)
  1321. write_string(file_handler, 'name', self.name)
  1322. write_string(file_handler, 'property', self.propertyInBabylon)
  1323. file_handler.write('}')
  1324. #===============================================================================
  1325. class VectorAnimation(Animation):
  1326. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1327. super().__init__(ANIMATIONTYPE_VECTOR3, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1328. # capture built up from fcurves
  1329. frames = dict()
  1330. for fcurve in object.animation_data.action.fcurves:
  1331. if fcurve.data_path == attrInBlender:
  1332. for key in fcurve.keyframe_points:
  1333. frame = key.co.x
  1334. frames[frame] = 1
  1335. #for each frame (next step ==> set for key frames)
  1336. for Frame in sorted(frames):
  1337. self.frames.append(Frame)
  1338. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1339. self.values.append(scale_vector(getattr(object, attrInBlender), mult, xOffset))
  1340. #===============================================================================
  1341. class QuaternionAnimation(Animation):
  1342. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1343. super().__init__(ANIMATIONTYPE_QUATERNION, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1344. # capture built up from fcurves
  1345. frames = dict()
  1346. for fcurve in object.animation_data.action.fcurves:
  1347. if fcurve.data_path == attrInBlender:
  1348. for key in fcurve.keyframe_points:
  1349. frame = key.co.x
  1350. frames[frame] = 1
  1351. #for each frame (next step ==> set for key frames)
  1352. for Frame in sorted(frames):
  1353. self.frames.append(Frame)
  1354. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1355. self.values.append(post_rotate_quaternion(getattr(object, attrInBlender), xOffset))
  1356. #===============================================================================
  1357. class QuaternionToEulerAnimation(Animation):
  1358. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1359. super().__init__(ANIMATIONTYPE_VECTOR3, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1360. # capture built up from fcurves
  1361. frames = dict()
  1362. for fcurve in object.animation_data.action.fcurves:
  1363. if fcurve.data_path == attrInBlender:
  1364. for key in fcurve.keyframe_points:
  1365. frame = key.co.x
  1366. frames[frame] = 1
  1367. #for each frame (next step ==> set for key frames)
  1368. for Frame in sorted(frames):
  1369. self.frames.append(Frame)
  1370. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1371. quat = getattr(object, attrInBlender)
  1372. eul = quat.to_euler("XYZ")
  1373. self.values.append(scale_vector(eul, mult, xOffset))
  1374. #===============================================================================
  1375. # module level formatting methods, called from multiple classes
  1376. #===============================================================================
  1377. def legal_js_identifier(input):
  1378. out = ''
  1379. prefix = ''
  1380. for char in input:
  1381. if len(out) == 0:
  1382. if char in '0123456789':
  1383. # cannot take the chance that leading numbers being chopped of cause name conflicts, e.g (01.R & 02.R)
  1384. prefix += char
  1385. continue
  1386. elif char.upper() not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
  1387. continue
  1388. legal = char if char.upper() in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_' else '_'
  1389. out += legal
  1390. if len(prefix) > 0:
  1391. out += '_' + prefix
  1392. return out
  1393. def format_f(num):
  1394. s = MAX_FLOAT_PRECISION % num # rounds to N decimal places while changing to string
  1395. s = s.rstrip('0') # ignore trailing zeroes
  1396. s = s.rstrip('.') # ignore trailing .
  1397. return '0' if s == '-0' else s
  1398. def format_matrix4(matrix):
  1399. tempMatrix = matrix.copy()
  1400. tempMatrix.transpose()
  1401. ret = ''
  1402. first = True
  1403. for vect in tempMatrix:
  1404. if (first != True):
  1405. ret +=','
  1406. first = False;
  1407. ret += format_f(vect[0]) + ',' + format_f(vect[1]) + ',' + format_f(vect[2]) + ',' + format_f(vect[3])
  1408. return ret
  1409. def format_array3(array):
  1410. return format_f(array[0]) + ',' + format_f(array[1]) + ',' + format_f(array[2])
  1411. def format_array(array, max_per_line = MAX_VERTEX_ELEMENTS, indent = ''):
  1412. ret = ''
  1413. first = True
  1414. nOnLine = 0
  1415. for element in array:
  1416. if (first != True):
  1417. ret +=','
  1418. first = False;
  1419. ret += format_f(element)
  1420. nOnLine += 1
  1421. if nOnLine >= max_per_line:
  1422. ret += '\n' + indent
  1423. nOnLine = 0
  1424. return ret
  1425. def format_color(color):
  1426. return format_f(color.r) + ',' + format_f(color.g) + ',' + format_f(color.b)
  1427. def format_vector(vector):
  1428. return format_f(vector.x) + ',' + format_f(vector.z) + ',' + format_f(vector.y)
  1429. def format_vector_array(vectorArray, max_per_line = MAX_VERTEX_ELEMENTS, indent = ''):
  1430. ret = ''
  1431. first = True
  1432. nOnLine = 0
  1433. for vector in vectorArray:
  1434. if (first != True):
  1435. ret +=','
  1436. first = False;
  1437. ret += format_vector(vector)
  1438. nOnLine += 3
  1439. if nOnLine >= max_per_line:
  1440. ret += '\n' + indent
  1441. nOnLine = 0
  1442. return ret
  1443. def format_quaternion(quaternion):
  1444. return format_f(quaternion.x) + ',' + format_f(quaternion.z) + ',' + format_f(quaternion.y) + ',' + format_f(-quaternion.w)
  1445. def format_int(int):
  1446. candidate = str(int) # when int string of an int
  1447. if '.' in candidate:
  1448. return format_f(math.floor(int)) # format_f removes un-neccessary precision
  1449. else:
  1450. return candidate
  1451. def format_bool(bool):
  1452. if bool:
  1453. return 'true'
  1454. else:
  1455. return 'false'
  1456. def scale_vector(vector, mult, xOffset = 0):
  1457. ret = vector.copy()
  1458. ret.x *= mult
  1459. ret.x += xOffset
  1460. ret.z *= mult
  1461. ret.y *= mult
  1462. return ret
  1463. def same_vertex(vertA, vertB):
  1464. return vertA.x == vertB.x and vertA.y == vertB.y and vertA.z == vertB.z
  1465. def post_rotate_quaternion(quat, angle):
  1466. post = mathutils.Euler((angle, 0.0, 0.0)).to_matrix()
  1467. mqtn = quat.to_matrix()
  1468. quat = (mqtn*post).to_quaternion()
  1469. return quat
  1470. #===============================================================================
  1471. # module level methods for writing JSON (.babylon) files
  1472. #===============================================================================
  1473. def write_matrix4(file_handler, name, matrix):
  1474. file_handler.write(',"' + name + '":[' + format_matrix4(matrix) + ']')
  1475. def write_array(file_handler, name, array):
  1476. file_handler.write('\n,"' + name + '":[' + format_array(array) + ']')
  1477. def write_array3(file_handler, name, array):
  1478. file_handler.write(',"' + name + '":[' + format_array3(array) + ']')
  1479. def write_color(file_handler, name, color):
  1480. file_handler.write(',"' + name + '":[' + format_color(color) + ']')
  1481. def write_vector(file_handler, name, vector):
  1482. file_handler.write(',"' + name + '":[' + format_vector(vector) + ']')
  1483. def write_vector_array(file_handler, name, vectorArray):
  1484. file_handler.write('\n,"' + name + '":[' + format_vector_array(vectorArray) + ']')
  1485. def write_quaternion(file_handler, name, quaternion):
  1486. file_handler.write(',"' + name +'":[' + format_quaternion(quaternion) + ']')
  1487. def write_string(file_handler, name, string, noComma = False):
  1488. if noComma == False:
  1489. file_handler.write(',')
  1490. file_handler.write('"' + name + '":"' + string + '"')
  1491. def write_float(file_handler, name, float):
  1492. file_handler.write(',"' + name + '":' + format_f(float))
  1493. def write_int(file_handler, name, int, noComma = False):
  1494. if noComma == False:
  1495. file_handler.write(',')
  1496. file_handler.write('"' + name + '":' + format_int(int))
  1497. def write_bool(file_handler, name, bool, noComma = False):
  1498. if noComma == False:
  1499. file_handler.write(',')
  1500. file_handler.write('"' + name + '":' + format_bool(bool))
  1501. #===============================================================================
  1502. # custom properties definition and display
  1503. #===============================================================================
  1504. bpy.types.Mesh.autoAnimate = bpy.props.BoolProperty(
  1505. name='Automatically launch animations',
  1506. description='',
  1507. default = False
  1508. )
  1509. bpy.types.Mesh.useFlatShading = bpy.props.BoolProperty(
  1510. name='Use Flat Shading',
  1511. description='',
  1512. default = False
  1513. )
  1514. bpy.types.Mesh.checkCollisions = bpy.props.BoolProperty(
  1515. name='Check Collisions',
  1516. description='Indicates mesh should be checked that it does not run into anything.',
  1517. default = False
  1518. )
  1519. bpy.types.Mesh.castShadows = bpy.props.BoolProperty(
  1520. name='Cast Shadows',
  1521. description='',
  1522. default = False
  1523. )
  1524. bpy.types.Mesh.receiveShadows = bpy.props.BoolProperty(
  1525. name='Receive Shadows',
  1526. description='',
  1527. default = False
  1528. )
  1529. bpy.types.Mesh.attachedSound = bpy.props.StringProperty(
  1530. name='Sound',
  1531. description='',
  1532. default = ''
  1533. )
  1534. bpy.types.Mesh.loopSound = bpy.props.BoolProperty(
  1535. name='Loop sound',
  1536. description='',
  1537. default = True
  1538. )
  1539. bpy.types.Mesh.autoPlaySound = bpy.props.BoolProperty(
  1540. name='Auto play sound',
  1541. description='',
  1542. default = True
  1543. )
  1544. bpy.types.Mesh.maxSoundDistance = bpy.props.FloatProperty(
  1545. name='Max sound distance',
  1546. description='',
  1547. default = 100
  1548. )
  1549. #===============================================================================
  1550. bpy.types.Camera.autoAnimate = bpy.props.BoolProperty(
  1551. name='Automatically launch animations',
  1552. description='',
  1553. default = False
  1554. )
  1555. bpy.types.Camera.CameraType = bpy.props.EnumProperty(
  1556. name='Camera Type',
  1557. description='',
  1558. # ONLY Append, or existing .blends will have their camera changed
  1559. items = (
  1560. (V_JOYSTICKS_CAM , 'Virtual Joysticks' , 'Use Virtual Joysticks Camera'),
  1561. (TOUCH_CAM , 'Touch' , 'Use Touch Camera'),
  1562. (GAMEPAD_CAM , 'Gamepad' , 'Use Gamepad Camera'),
  1563. (FREE_CAM , 'Free' , 'Use Free Camera'),
  1564. (FOLLOW_CAM , 'Follow' , 'Use Follow Camera'),
  1565. (DEV_ORIENT_CAM , 'Device Orientation' , 'Use Device Orientation Camera'),
  1566. (ARC_ROTATE_CAM , 'Arc Rotate' , 'Use Arc Rotate Camera'),
  1567. (ANAGLYPH_FREE_CAM , 'Anaglyph Free' , 'Use Anaglyph Free Camera'),
  1568. (ANAGLYPH_ARC_CAM , 'Anaglyph Arc Rotate' , 'Use Anaglyph Arc Rotate Camera'),
  1569. (VR_DEV_ORIENT_FREE_CAM , 'VR Dev Orientation Free' , 'Use VR Dev Orientation Free Camera'),
  1570. (WEB_VR_FREE_CAM , 'Web VR Free' , 'Use Web VR Free Camera')
  1571. ),
  1572. default = FREE_CAM
  1573. )
  1574. bpy.types.Camera.checkCollisions = bpy.props.BoolProperty(
  1575. name='Check Collisions',
  1576. description='',
  1577. default = False
  1578. )
  1579. bpy.types.Camera.applyGravity = bpy.props.BoolProperty(
  1580. name='Apply Gravity',
  1581. description='',
  1582. default = False
  1583. )
  1584. bpy.types.Camera.ellipsoid = bpy.props.FloatVectorProperty(
  1585. name='Ellipsoid',
  1586. description='',
  1587. default = mathutils.Vector((0.2, 0.9, 0.2))
  1588. )
  1589. bpy.types.Camera.anaglyphEyeSpace = bpy.props.IntProperty(
  1590. name='Anaglyph Eye space',
  1591. description='Used by the Anaglyph Arc Rotate camera',
  1592. default = 1
  1593. )
  1594. #===============================================================================
  1595. bpy.types.Lamp.autoAnimate = bpy.props.BoolProperty(
  1596. name='Automatically launch animations',
  1597. description='',
  1598. default = False
  1599. )
  1600. bpy.types.Lamp.shadowMap = bpy.props.EnumProperty(
  1601. name='Shadow Map Type',
  1602. description='',
  1603. items = (('NONE', 'None', 'No Shadow Maps'), ('STD', 'Standard', 'Use Standard Shadow Maps'), ('VAR', 'Variance', 'Use Variance Shadow Maps')),
  1604. default = 'NONE'
  1605. )
  1606. bpy.types.Lamp.shadowMapSize = bpy.props.IntProperty(
  1607. name='Shadow Map Size',
  1608. description='',
  1609. default = 512
  1610. )
  1611. class ObjectPanel(bpy.types.Panel):
  1612. bl_label = 'Babylon.js'
  1613. bl_space_type = 'PROPERTIES'
  1614. bl_region_type = 'WINDOW'
  1615. bl_context = 'data'
  1616. def draw(self, context):
  1617. ob = context.object
  1618. if not ob or not ob.data:
  1619. return
  1620. layout = self.layout
  1621. isMesh = isinstance(ob.data, bpy.types.Mesh)
  1622. isCamera = isinstance(ob.data, bpy.types.Camera)
  1623. isLight = isinstance(ob.data, bpy.types.Lamp)
  1624. if isMesh:
  1625. layout.prop(ob.data, 'useFlatShading')
  1626. layout.prop(ob.data, 'checkCollisions')
  1627. layout.prop(ob.data, 'castShadows')
  1628. layout.prop(ob.data, 'receiveShadows')
  1629. layout.separator()
  1630. layout.prop(ob.data, 'autoAnimate')
  1631. layout.separator()
  1632. layout.prop(ob.data, 'attachedSound')
  1633. layout.prop(ob.data, 'autoPlaySound')
  1634. layout.prop(ob.data, 'loopSound')
  1635. layout.prop(ob.data, 'maxSoundDistance')
  1636. elif isCamera:
  1637. layout.prop(ob.data, 'CameraType')
  1638. layout.prop(ob.data, 'checkCollisions')
  1639. layout.prop(ob.data, 'applyGravity')
  1640. layout.prop(ob.data, 'ellipsoid')
  1641. layout.separator()
  1642. layout.prop(ob.data, 'anaglyphEyeSpace')
  1643. layout.separator()
  1644. layout.prop(ob.data, 'autoAnimate')
  1645. elif isLight:
  1646. layout.prop(ob.data, 'shadowMap')
  1647. layout.prop(ob.data, 'shadowMapSize')
  1648. layout.separator()
  1649. layout.prop(ob.data, 'autoAnimate')