io_export_babylon.py 81 KB

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