io_export_babylon.py 80 KB

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