io_export_babylon.py 77 KB

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