io_export_babylon.py 80 KB

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