io_export_babylon.py 80 KB

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