io_export_babylon.py 81 KB

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