io_export_babylon.py 78 KB

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