io_export_babylon.py 77 KB

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