io_export_babylon.py 77 KB

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