io_export_babylon.py 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402
  1. bl_info = {
  2. 'name': 'Babylon.js',
  3. 'author': 'David Catuhe, Jeff Palmer',
  4. 'version': (3, 0, 2),
  5. 'blender': (2, 75, 0),
  6. 'location': 'File > Export > Babylon.js (.babylon)',
  7. 'description': 'Export Babylon.js scenes (.babylon)',
  8. 'wiki_url': 'https://github.com/BabylonJS/Babylon.js/tree/master/Exporters/Blender',
  9. 'tracker_url': '',
  10. 'category': 'Import-Export'}
  11. import base64
  12. import bpy
  13. import bpy_extras.io_utils
  14. import time
  15. import io
  16. import math
  17. import mathutils
  18. import os
  19. import shutil
  20. import sys, traceback # for writing errors to log file
  21. #===============================================================================
  22. # Registration the calling of the INFO_MT_file_export file selector
  23. def menu_func(self, context):
  24. self.layout.operator(Main.bl_idname, text = 'Babylon.js [.babylon]')
  25. def register():
  26. bpy.utils.register_module(__name__)
  27. bpy.types.INFO_MT_file_export.append(menu_func)
  28. def unregister():
  29. bpy.utils.unregister_module(__name__)
  30. bpy.types.INFO_MT_file_export.remove(menu_func)
  31. if __name__ == '__main__':
  32. register()
  33. #===============================================================================
  34. # output related constants
  35. MAX_VERTEX_ELEMENTS = 65535
  36. MAX_VERTEX_ELEMENTS_32Bit = 16777216
  37. VERTEX_OUTPUT_PER_LINE = 1000
  38. MAX_FLOAT_PRECISION = '%.4f'
  39. MAX_INFLUENCERS_PER_VERTEX = 4
  40. # used in World constructor, defined in BABYLON.Scene
  41. #FOGMODE_NONE = 0
  42. #FOGMODE_EXP = 1
  43. #FOGMODE_EXP2 = 2
  44. FOGMODE_LINEAR = 3
  45. # used in Mesh & Node constructors, defined in BABYLON.AbstractMesh
  46. BILLBOARDMODE_NONE = 0
  47. #BILLBOARDMODE_X = 1
  48. #BILLBOARDMODE_Y = 2
  49. #BILLBOARDMODE_Z = 4
  50. BILLBOARDMODE_ALL = 7
  51. # used in Mesh constructor, defined in BABYLON.PhysicsEngine
  52. SPHERE_IMPOSTER = 1
  53. BOX_IMPOSTER = 2
  54. #PLANE_IMPOSTER = 3
  55. MESH_IMPOSTER = 4
  56. CAPSULE_IMPOSTER = 5
  57. CONE_IMPOSTER = 6
  58. CYLINDER_IMPOSTER = 7
  59. CONVEX_HULL_IMPOSTER = 8
  60. # camera class names, never formally defined in Babylon, but used in babylonFileLoader
  61. ARC_ROTATE_CAM = 'ArcRotateCamera'
  62. DEV_ORIENT_CAM = 'DeviceOrientationCamera'
  63. FOLLOW_CAM = 'FollowCamera'
  64. FREE_CAM = 'FreeCamera'
  65. GAMEPAD_CAM = 'GamepadCamera'
  66. TOUCH_CAM = 'TouchCamera'
  67. V_JOYSTICKS_CAM = 'VirtualJoysticksCamera'
  68. VR_DEV_ORIENT_FREE_CAM ='VRDeviceOrientationFreeCamera'
  69. WEB_VR_FREE_CAM = 'WebVRFreeCamera'
  70. # 3D camera rigs, defined in BABYLON.Camera, must be strings to be in 'dropdown'
  71. RIG_MODE_NONE = '0'
  72. RIG_MODE_STEREOSCOPIC_ANAGLYPH = '10'
  73. RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = '11'
  74. RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = '12'
  75. RIG_MODE_STEREOSCOPIC_OVERUNDER = '13'
  76. RIG_MODE_VR = '20'
  77. # used in Light constructor, never formally defined in Babylon, but used in babylonFileLoader
  78. POINT_LIGHT = 0
  79. DIRECTIONAL_LIGHT = 1
  80. SPOT_LIGHT = 2
  81. HEMI_LIGHT = 3
  82. #used in ShadowGenerators
  83. NO_SHADOWS = 'NONE'
  84. STD_SHADOWS = 'STD'
  85. POISSON_SHADOWS = 'POISSON'
  86. VARIANCE_SHADOWS = 'VARIANCE'
  87. BLUR_VARIANCE_SHADOWS = 'BLUR_VARIANCE'
  88. # used in Texture constructor, defined in BABYLON.Texture
  89. CLAMP_ADDRESSMODE = 0
  90. WRAP_ADDRESSMODE = 1
  91. MIRROR_ADDRESSMODE = 2
  92. # used in Texture constructor, defined in BABYLON.Texture
  93. EXPLICIT_MODE = 0
  94. SPHERICAL_MODE = 1
  95. #PLANAR_MODE = 2
  96. CUBIC_MODE = 3
  97. #PROJECTION_MODE = 4
  98. #SKYBOX_MODE = 5
  99. # passed to Animation constructor from animatable objects, defined in BABYLON.Animation
  100. #ANIMATIONTYPE_FLOAT = 0
  101. ANIMATIONTYPE_VECTOR3 = 1
  102. ANIMATIONTYPE_QUATERNION = 2
  103. ANIMATIONTYPE_MATRIX = 3
  104. #ANIMATIONTYPE_COLOR3 = 4
  105. # passed to Animation constructor from animatable objects, defined in BABYLON.Animation
  106. #ANIMATIONLOOPMODE_RELATIVE = 0
  107. ANIMATIONLOOPMODE_CYCLE = 1
  108. #ANIMATIONLOOPMODE_CONSTANT = 2
  109. #===============================================================================
  110. # Panel displayed in Scene Tab of properties, so settings can be saved in a .blend file
  111. class ExporterSettingsPanel(bpy.types.Panel):
  112. bl_label = 'Exporter Settings'
  113. bl_space_type = 'PROPERTIES'
  114. bl_region_type = 'WINDOW'
  115. bl_context = 'scene'
  116. bpy.types.Scene.export_onlySelectedLayer = bpy.props.BoolProperty(
  117. name="Export only selected layers",
  118. description="Export only selected layers",
  119. default = False,
  120. )
  121. bpy.types.Scene.export_noVertexOpt = bpy.props.BoolProperty(
  122. name="No vertex sharing",
  123. description="Turns off an optimization which reduces vertices",
  124. default = False,
  125. )
  126. bpy.types.Scene.attachedSound = bpy.props.StringProperty(
  127. name='Sound',
  128. description='',
  129. default = ''
  130. )
  131. bpy.types.Scene.loopSound = bpy.props.BoolProperty(
  132. name='Loop sound',
  133. description='',
  134. default = True
  135. )
  136. bpy.types.Scene.autoPlaySound = bpy.props.BoolProperty(
  137. name='Auto play sound',
  138. description='',
  139. default = True
  140. )
  141. bpy.types.Scene.inlineTextures = bpy.props.BoolProperty(
  142. name="inline textures",
  143. description="turn textures into encoded strings, for direct inclusion into source code",
  144. default = False,
  145. )
  146. def draw(self, context):
  147. layout = self.layout
  148. scene = context.scene
  149. layout.prop(scene, "export_onlySelectedLayer")
  150. layout.prop(scene, "export_noVertexOpt")
  151. layout.prop(scene, "inlineTextures")
  152. box = layout.box()
  153. box.prop(scene, 'attachedSound')
  154. box.prop(scene, 'autoPlaySound')
  155. box.prop(scene, 'loopSound')
  156. #===============================================================================
  157. class Main(bpy.types.Operator, bpy_extras.io_utils.ExportHelper):
  158. bl_idname = 'scene.babylon' # module will not load with out it, also must have a dot
  159. bl_label = 'Export Babylon.js scene' # used on the label of the actual 'save' button
  160. filename_ext = '.babylon' # required to have one, although not really used
  161. filepath = bpy.props.StringProperty(subtype = 'FILE_PATH') # assigned once the file selector returns
  162. log_handler = None # assigned in execute
  163. nameSpace = None # assigned in execute
  164. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  165. nWarnings = 0
  166. @staticmethod
  167. def warn(msg, numTabIndent = 1, noNewLine = False):
  168. Main.log('WARNING: ' + msg, numTabIndent, noNewLine)
  169. Main.nWarnings += 1
  170. @staticmethod
  171. def log(msg, numTabIndent = 1, noNewLine = False):
  172. for i in range(numTabIndent):
  173. Main.log_handler.write('\t')
  174. Main.log_handler.write(msg)
  175. if not noNewLine: Main.log_handler.write('\n')
  176. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  177. def getMaterial(self, baseMaterialId):
  178. fullName = Main.nameSpace + '.' + baseMaterialId
  179. for material in self.materials:
  180. if material.name == fullName:
  181. return material
  182. return None
  183. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  184. def getSourceMeshInstance(self, dataName):
  185. for mesh in self.meshesAndNodes:
  186. # nodes have no 'dataName', cannot be instanced in any case
  187. if hasattr(mesh, 'dataName') and mesh.dataName == dataName:
  188. return mesh
  189. return None
  190. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  191. def execute(self, context):
  192. scene = context.scene
  193. self.scene = scene # reference for passing
  194. try:
  195. start_time = time.time()
  196. filepathDotExtension = self.filepath.rpartition('.')
  197. self.filepathMinusExtension = filepathDotExtension[0]
  198. # assign nameSpace, based on OS
  199. if self.filepathMinusExtension.find('\\') != -1:
  200. Main.nameSpace = legal_js_identifier(self.filepathMinusExtension.rpartition('\\')[2])
  201. else:
  202. Main.nameSpace = legal_js_identifier(self.filepathMinusExtension.rpartition('/')[2])
  203. # explicitly reset globals, in case there was an earlier export this session
  204. Main.nWarnings = 0
  205. Main.log_handler = io.open(self.filepathMinusExtension + '.log', 'w', encoding='utf8')
  206. version = bl_info['version']
  207. Main.log('Exporter version: ' + str(version[0]) + '.' + str(version[1]) + '.' + str(version[2]) +
  208. ', Blender version: ' + bpy.app.version_string)
  209. if bpy.ops.object.mode_set.poll():
  210. bpy.ops.object.mode_set(mode = 'OBJECT')
  211. Main.log('========= Conversion from Blender to Babylon.js =========', 0)
  212. self.world = World(scene)
  213. bpy.ops.screen.animation_cancel()
  214. currentFrame = bpy.context.scene.frame_current
  215. bpy.context.scene.frame_set(0)
  216. # Active camera
  217. if scene.camera != None:
  218. self.activeCamera = scene.camera.name
  219. else:
  220. Main.warn('No active camera has been assigned, or is not in a currently selected Blender layer')
  221. self.cameras = []
  222. self.lights = []
  223. self.shadowGenerators = []
  224. self.skeletons = []
  225. skeletonId = 0
  226. self.meshesAndNodes = []
  227. self.materials = []
  228. self.multiMaterials = []
  229. self.sounds = []
  230. # Scene level sound
  231. if scene.attachedSound != '':
  232. self.sounds.append(Sound(scene.attachedSound, scene.autoPlaySound, scene.loopSound))
  233. # exclude lamps in this pass, so ShadowGenerator constructor can be passed meshesAnNodes
  234. for object in [object for object in scene.objects]:
  235. if object.type == 'CAMERA':
  236. if object.is_visible(scene): # no isInSelectedLayer() required, is_visible() handles this for them
  237. self.cameras.append(Camera(object))
  238. else:
  239. Main.warn('The following camera not visible in scene thus ignored: ' + object.name)
  240. elif object.type == 'ARMATURE': #skeleton.pose.bones
  241. if object.is_visible(scene):
  242. self.skeletons.append(Skeleton(object, scene, skeletonId))
  243. skeletonId += 1
  244. else:
  245. Main.warn('The following armature not visible in scene thus ignored: ' + object.name)
  246. elif object.type == 'MESH':
  247. forcedParent = None
  248. nameID = ''
  249. nextStartFace = 0
  250. while True and self.isInSelectedLayer(object, scene):
  251. mesh = Mesh(object, scene, nextStartFace, forcedParent, nameID, self)
  252. if hasattr(mesh, 'instances'):
  253. self.meshesAndNodes.append(mesh)
  254. else:
  255. break
  256. if object.data.attachedSound != '':
  257. self.sounds.append(Sound(object.data.attachedSound, object.data.autoPlaySound, object.data.loopSound, object))
  258. nextStartFace = mesh.offsetFace
  259. if nextStartFace == 0:
  260. break
  261. if forcedParent is None:
  262. nameID = 0
  263. forcedParent = object
  264. Main.warn('The following mesh has exceeded the maximum # of vertex elements & will be broken into multiple Babylon meshes: ' + object.name)
  265. nameID = nameID + 1
  266. elif object.type == 'EMPTY':
  267. self.meshesAndNodes.append(Node(object))
  268. elif object.type != 'LAMP':
  269. Main.warn('The following object (type - ' + object.type + ') is not currently exportable thus ignored: ' + object.name)
  270. # Lamp / shadow Generator pass; meshesAnNodes complete & forceParents included
  271. for object in [object for object in scene.objects]:
  272. if object.type == 'LAMP':
  273. if object.is_visible(scene): # no isInSelectedLayer() required, is_visible() handles this for them
  274. bulb = Light(object)
  275. self.lights.append(bulb)
  276. if object.data.shadowMap != 'NONE':
  277. if bulb.light_type == DIRECTIONAL_LIGHT or bulb.light_type == SPOT_LIGHT:
  278. self.shadowGenerators.append(ShadowGenerator(object, self.meshesAndNodes, scene))
  279. else:
  280. Main.warn('Only directional (sun) and spot types of lamp are valid for shadows thus ignored: ' + object.name)
  281. else:
  282. Main.warn('The following lamp not visible in scene thus ignored: ' + object.name)
  283. bpy.context.scene.frame_set(currentFrame)
  284. # output file
  285. self.to_scene_file ()
  286. except:# catch *all* exceptions
  287. ex = sys.exc_info()
  288. Main.log('========= An error was encountered =========', 0)
  289. stack = traceback.format_tb(ex[2])
  290. for line in stack:
  291. Main.log_handler.write(line) # avoid tabs & extra newlines by not calling log() inside catch
  292. Main.log_handler.write('ERROR: ' + str(ex[1]) + '\n')
  293. raise
  294. finally:
  295. Main.log('========= end of processing =========', 0)
  296. elapsed_time = time.time() - start_time
  297. minutes = math.floor(elapsed_time / 60)
  298. seconds = elapsed_time - (minutes * 60)
  299. Main.log('elapsed time: ' + str(minutes) + ' min, ' + format_f(seconds) + ' secs', 0)
  300. Main.log_handler.close()
  301. if (Main.nWarnings > 0):
  302. self.report({'WARNING'}, 'Processing completed, but ' + str(Main.nWarnings) + ' WARNINGS were raised, see log file.')
  303. return {'FINISHED'}
  304. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  305. def to_scene_file(self):
  306. Main.log('========= Writing of scene file started =========', 0)
  307. # Open file
  308. file_handler = io.open(self.filepathMinusExtension + '.babylon', 'w', encoding='utf8')
  309. file_handler.write('{')
  310. self.world.to_scene_file(file_handler)
  311. # Materials
  312. file_handler.write(',\n"materials":[')
  313. first = True
  314. for material in self.materials:
  315. if first != True:
  316. file_handler.write(',\n')
  317. first = False
  318. material.to_scene_file(file_handler)
  319. file_handler.write(']')
  320. # Multi-materials
  321. file_handler.write(',\n"multiMaterials":[')
  322. first = True
  323. for multimaterial in self.multiMaterials:
  324. if first != True:
  325. file_handler.write(',')
  326. first = False
  327. multimaterial.to_scene_file(file_handler)
  328. file_handler.write(']')
  329. # Armatures/Bones
  330. file_handler.write(',\n"skeletons":[')
  331. first = True
  332. for skeleton in self.skeletons:
  333. if first != True:
  334. file_handler.write(',')
  335. first = False
  336. skeleton.to_scene_file(file_handler)
  337. file_handler.write(']')
  338. # Meshes
  339. file_handler.write(',\n"meshes":[')
  340. first = True
  341. for m in range(0, len(self.meshesAndNodes)):
  342. mesh = self.meshesAndNodes[m]
  343. if first != True:
  344. file_handler.write(',')
  345. first = False
  346. mesh.to_scene_file(file_handler)
  347. file_handler.write(']')
  348. # Cameras
  349. file_handler.write(',\n"cameras":[')
  350. first = True
  351. for camera in self.cameras:
  352. if hasattr(camera, 'fatalProblem'): continue
  353. if first != True:
  354. file_handler.write(',')
  355. first = False
  356. camera.update_for_target_attributes(self.meshesAndNodes)
  357. camera.to_scene_file(file_handler)
  358. file_handler.write(']')
  359. # Active camera
  360. if hasattr(self, 'activeCamera'):
  361. write_string(file_handler, 'activeCamera', self.activeCamera)
  362. # Lights
  363. file_handler.write(',\n"lights":[')
  364. first = True
  365. for light in self.lights:
  366. if first != True:
  367. file_handler.write(',')
  368. first = False
  369. light.to_scene_file(file_handler)
  370. file_handler.write(']')
  371. # Shadow generators
  372. file_handler.write(',\n"shadowGenerators":[')
  373. first = True
  374. for shadowGen in self.shadowGenerators:
  375. if first != True:
  376. file_handler.write(',')
  377. first = False
  378. shadowGen.to_scene_file(file_handler)
  379. file_handler.write(']')
  380. # Sounds
  381. if len(self.sounds) > 0:
  382. file_handler.write('\n,"sounds":[')
  383. first = True
  384. for sound in self.sounds:
  385. if first != True:
  386. file_handler.write(',')
  387. first = False
  388. sound.to_scene_file(file_handler)
  389. file_handler.write(']')
  390. # Closing
  391. file_handler.write('\n}')
  392. file_handler.close()
  393. Main.log('========= Writing of scene file completed =========', 0)
  394. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  395. def isInSelectedLayer(self, obj, scene):
  396. if not scene.export_onlySelectedLayer:
  397. return True
  398. for l in range(0, len(scene.layers)):
  399. if obj.layers[l] and scene.layers[l]:
  400. return True
  401. return False
  402. #===============================================================================
  403. class World:
  404. def __init__(self, scene):
  405. self.autoClear = True
  406. world = scene.world
  407. if world:
  408. self.ambient_color = world.ambient_color
  409. self.clear_color = world.horizon_color
  410. else:
  411. self.ambient_color = mathutils.Color((0.2, 0.2, 0.3))
  412. self.clear_color = mathutils.Color((0.0, 0.0, 0.0))
  413. self.gravity = scene.gravity
  414. if world and world.mist_settings.use_mist:
  415. self.fogMode = FOGMODE_LINEAR
  416. self.fogColor = world.horizon_color
  417. self.fogStart = world.mist_settings.start
  418. self.fogEnd = world.mist_settings.depth
  419. self.fogDensity = 0.1
  420. Main.log('Python World class constructor completed')
  421. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  422. def to_scene_file(self, file_handler):
  423. write_bool(file_handler, 'autoClear', self.autoClear, True)
  424. write_color(file_handler, 'clearColor', self.clear_color)
  425. write_color(file_handler, 'ambientColor', self.ambient_color)
  426. write_vector(file_handler, 'gravity', self.gravity)
  427. if hasattr(self, 'fogMode'):
  428. write_int(file_handler, 'fogMode', self.fogMode)
  429. write_color(file_handler, 'fogColor', self.fogColor)
  430. write_float(file_handler, 'fogStart', self.fogStart)
  431. write_float(file_handler, 'fogEnd', self.fogEnd)
  432. write_float(file_handler, 'fogDensity', self.fogDensity)
  433. #===============================================================================
  434. class Sound:
  435. def __init__(self, name, autoplay, loop, connectedMesh = None):
  436. self.name = name;
  437. self.autoplay = autoplay
  438. self.loop = loop
  439. if connectedMesh != None:
  440. self.connectedMeshId = connectedMesh.name
  441. self.maxDistance = connectedMesh.data.maxSoundDistance
  442. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  443. def to_scene_file(self, file_handler):
  444. file_handler.write('{')
  445. write_string(file_handler, 'name', self.name, True)
  446. write_bool(file_handler, 'autoplay', self.autoplay)
  447. write_bool(file_handler, 'loop', self.loop)
  448. if hasattr(self, 'connectedMeshId'):
  449. write_string(file_handler, 'connectedMeshId', self.connectedMeshId)
  450. write_float(file_handler, 'maxDistance', self.maxDistance)
  451. file_handler.write('}')
  452. #===============================================================================
  453. class FCurveAnimatable:
  454. def __init__(self, object, supportsRotation, supportsPosition, supportsScaling, xOffsetForRotation = 0):
  455. # just because a sub-class can be animatable does not mean it is
  456. self.animationsPresent = object.animation_data and object.animation_data.action
  457. rotAnim = False
  458. locAnim = False
  459. scaAnim = False
  460. useQuat = object.rotation_mode=='QUATERNION'
  461. if (self.animationsPresent):
  462. Main.log('FCurve animation processing begun for: ' + object.name, 1)
  463. self.animations = []
  464. for fcurve in object.animation_data.action.fcurves:
  465. if supportsRotation and fcurve.data_path == 'rotation_euler' and rotAnim == False and useQuat == False:
  466. self.animations.append(VectorAnimation(object, 'rotation_euler', 'rotation', -1, xOffsetForRotation))
  467. rotAnim = True
  468. elif supportsRotation and fcurve.data_path == 'rotation_quaternion' and rotAnim == False and useQuat == True:
  469. self.animations.append(QuaternionAnimation(object, 'rotation_quaternion', 'rotationQuaternion', 1, xOffsetForRotation))
  470. rotAnim = True
  471. elif supportsPosition and fcurve.data_path == 'location' and locAnim == False:
  472. self.animations.append(VectorAnimation(object, 'location', 'position', 1))
  473. locAnim = True
  474. elif supportsScaling and fcurve.data_path == 'scale' and scaAnim == False:
  475. self.animations.append(VectorAnimation(object, 'scale', 'scaling', 1))
  476. scaAnim = True
  477. #Set Animations
  478. if (hasattr(object.data, "autoAnimate") and object.data.autoAnimate):
  479. self.autoAnimate = True
  480. self.autoAnimateFrom = bpy.context.scene.frame_end
  481. self.autoAnimateTo = 0
  482. for animation in self.animations:
  483. if self.autoAnimateFrom > animation.get_first_frame():
  484. self.autoAnimateFrom = animation.get_first_frame()
  485. if self.autoAnimateTo < animation.get_last_frame():
  486. self.autoAnimateTo = animation.get_last_frame()
  487. self.autoAnimateLoop = True
  488. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  489. def to_scene_file(self, file_handler):
  490. if (self.animationsPresent):
  491. file_handler.write('\n,"animations":[')
  492. first = True
  493. for animation in self.animations:
  494. if first == False:
  495. file_handler.write(',')
  496. animation.to_scene_file(file_handler)
  497. first = False
  498. file_handler.write(']')
  499. if (hasattr(self, "autoAnimate") and self.autoAnimate):
  500. write_bool(file_handler, 'autoAnimate', self.autoAnimate)
  501. write_int(file_handler, 'autoAnimateFrom', self.autoAnimateFrom)
  502. write_int(file_handler, 'autoAnimateTo', self.autoAnimateTo)
  503. write_bool(file_handler, 'autoAnimateLoop', self.autoAnimateLoop)
  504. #===============================================================================
  505. class Mesh(FCurveAnimatable):
  506. def __init__(self, object, scene, startFace, forcedParent, nameID, exporter):
  507. super().__init__(object, True, True, True) #Should animations be done when forcedParent
  508. self.name = object.name + str(nameID)
  509. Main.log('processing begun of mesh: ' + self.name)
  510. self.isVisible = not object.hide_render
  511. self.isEnabled = True
  512. self.useFlatShading = object.data.useFlatShading
  513. self.checkCollisions = object.data.checkCollisions
  514. self.receiveShadows = object.data.receiveShadows
  515. self.castShadows = object.data.castShadows
  516. self.freezeWorldMatrix = object.data.freezeWorldMatrix
  517. # hasSkeleton detection & skeletonID determination
  518. hasSkeleton = False
  519. objArmature = None # if there's an armature, this will be the one!
  520. if len(object.vertex_groups) > 0:
  521. objArmature = object.find_armature()
  522. if objArmature != None:
  523. hasSkeleton = True
  524. i = 0
  525. for obj in scene.objects:
  526. if obj.type == "ARMATURE":
  527. if obj == objArmature:
  528. self.skeletonId = i
  529. break
  530. else:
  531. i += 1
  532. # determine Position, rotation, & scaling
  533. if forcedParent is None:
  534. # Use local matrix
  535. locMatrix = object.matrix_local
  536. if objArmature != None:
  537. # unless the armature is the parent
  538. if object.parent and object.parent == objArmature:
  539. locMatrix = object.matrix_world * object.parent.matrix_world.inverted()
  540. loc, rot, scale = locMatrix.decompose()
  541. self.position = loc
  542. if object.rotation_mode == 'QUATERNION':
  543. self.rotationQuaternion = rot
  544. else:
  545. self.rotation = scale_vector(rot.to_euler('XYZ'), -1)
  546. self.scaling = scale
  547. else:
  548. # use defaults when not None
  549. self.position = mathutils.Vector((0, 0, 0))
  550. self.rotation = scale_vector(mathutils.Vector((0, 0, 0)), 1) # isn't scaling 0's by 1 same as 0?
  551. self.scaling = mathutils.Vector((1, 1, 1))
  552. # determine parent & dataName
  553. if forcedParent is None:
  554. self.dataName = object.data.name # used to support shared vertex instances in later passed
  555. if object.parent and object.parent.type != 'ARMATURE':
  556. self.parentId = object.parent.name
  557. else:
  558. self.dataName = self.name
  559. self.parentId = forcedParent.name
  560. # Get if this will be an instance of another, before processing materials, to avoid multi-bakes
  561. sourceMesh = exporter.getSourceMeshInstance(self.dataName)
  562. if sourceMesh is not None:
  563. #need to make sure rotation mode matches, since value initially copied in InstancedMesh constructor
  564. if hasattr(sourceMesh, 'rotationQuaternion'):
  565. instRot = None
  566. instRotq = rot
  567. else:
  568. instRot = scale_vector(rot.to_euler('XYZ'), -1)
  569. instRotq = None
  570. instance = MeshInstance(self.name, self.position, instRot, instRotq, self.scaling, self.freezeWorldMatrix)
  571. sourceMesh.instances.append(instance)
  572. Main.log('mesh is an instance of : ' + sourceMesh.name + '. Processing halted.', 2)
  573. return
  574. else:
  575. self.instances = []
  576. # Physics
  577. if object.rigid_body != None:
  578. shape_items = {'SPHERE' : SPHERE_IMPOSTER,
  579. 'BOX' : BOX_IMPOSTER,
  580. 'MESH' : MESH_IMPOSTER,
  581. 'CAPSULE' : CAPSULE_IMPOSTER,
  582. 'CONE' : CONE_IMPOSTER,
  583. 'CYLINDER' : CYLINDER_IMPOSTER,
  584. 'CONVEX_HULL': CONVEX_HULL_IMPOSTER}
  585. shape_type = shape_items[object.rigid_body.collision_shape]
  586. self.physicsImpostor = shape_type
  587. mass = object.rigid_body.mass
  588. if mass < 0.005:
  589. mass = 0
  590. self.physicsMass = mass
  591. self.physicsFriction = object.rigid_body.friction
  592. self.physicsRestitution = object.rigid_body.restitution
  593. # process all of the materials required
  594. maxVerts = MAX_VERTEX_ELEMENTS # change for multi-materials
  595. recipe = BakingRecipe(object)
  596. self.billboardMode = recipe.billboardMode
  597. if recipe.needsBaking:
  598. if recipe.multipleRenders:
  599. Main.warn('Mixing of Cycles & Blender Render in same mesh not supported. No materials exported.', 2)
  600. uvRequired = False
  601. else:
  602. bakedMat = BakedMaterial(exporter, object, recipe)
  603. exporter.materials.append(bakedMat)
  604. uvRequired = True
  605. self.materialId = bakedMat.name
  606. else:
  607. uvRequired = False
  608. bjs_material_slots = []
  609. for slot in object.material_slots:
  610. # None will be returned when either the first encounter or must be unique due to baked textures
  611. material = exporter.getMaterial(slot.name)
  612. if (material != None):
  613. material.numOfUsers = material.numOfUsers + 1
  614. Main.log('registered as also a user of material: ' + slot.name, 2)
  615. else:
  616. material = StdMaterial(slot, exporter, object)
  617. exporter.materials.append(material)
  618. uvRequired |= len(material.textures) > 0
  619. bjs_material_slots.append(material)
  620. if len(bjs_material_slots) == 1:
  621. self.materialId = bjs_material_slots[0].name
  622. elif len(bjs_material_slots) > 1:
  623. multimat = MultiMaterial(bjs_material_slots, len(exporter.multiMaterials))
  624. self.materialId = multimat.name
  625. exporter.multiMaterials.append(multimat)
  626. maxVerts = MAX_VERTEX_ELEMENTS_32Bit
  627. else:
  628. Main.warn('No materials have been assigned: ', 2)
  629. # Get mesh
  630. mesh = object.to_mesh(scene, True, 'PREVIEW')
  631. # Triangulate mesh if required
  632. Mesh.mesh_triangulate(mesh)
  633. # Getting vertices and indices
  634. self.positions = []
  635. self.normals = []
  636. self.uvs = [] # not always used
  637. self.uvs2 = [] # not always used
  638. self.colors = [] # not always used
  639. self.indices = []
  640. self.subMeshes = []
  641. hasUV = len(mesh.tessface_uv_textures) > 0
  642. if hasUV:
  643. which = len(mesh.tessface_uv_textures) - 1 if recipe.needsBaking else 0
  644. UVmap = mesh.tessface_uv_textures[which].data
  645. hasUV2 = len(mesh.tessface_uv_textures) > 1 and not recipe.needsBaking
  646. if hasUV2:
  647. UV2map = mesh.tessface_uv_textures[1].data
  648. hasVertexColor = len(mesh.vertex_colors) > 0
  649. if hasVertexColor:
  650. Colormap = mesh.tessface_vertex_colors.active.data
  651. if hasSkeleton:
  652. self.skeletonWeights = []
  653. self.skeletonIndicesCompressed = []
  654. # used tracking of vertices as they are received
  655. alreadySavedVertices = []
  656. vertices_UVs = []
  657. vertices_UV2s = []
  658. vertices_Colors = []
  659. vertices_indices = []
  660. self.offsetFace = 0
  661. for v in range(0, len(mesh.vertices)):
  662. alreadySavedVertices.append(False)
  663. vertices_UVs.append([])
  664. vertices_UV2s.append([])
  665. vertices_Colors.append([])
  666. vertices_indices.append([])
  667. materialsCount = 1 if recipe.needsBaking else max(1, len(object.material_slots))
  668. verticesCount = 0
  669. indicesCount = 0
  670. for materialIndex in range(materialsCount):
  671. if self.offsetFace != 0:
  672. break
  673. subMeshVerticesStart = verticesCount
  674. subMeshIndexStart = indicesCount
  675. for faceIndex in range(startFace, len(mesh.tessfaces)): # For each face
  676. face = mesh.tessfaces[faceIndex]
  677. if face.material_index != materialIndex and not recipe.needsBaking:
  678. continue
  679. if verticesCount + 3 > maxVerts:
  680. self.offsetFace = faceIndex
  681. break
  682. for v in range(3): # For each vertex in face
  683. vertex_index = face.vertices[v]
  684. vertex = mesh.vertices[vertex_index]
  685. position = vertex.co
  686. normal = vertex.normal
  687. #skeletons
  688. if hasSkeleton:
  689. matricesWeights = []
  690. matricesWeights.append(0.0)
  691. matricesWeights.append(0.0)
  692. matricesWeights.append(0.0)
  693. matricesWeights.append(0.0)
  694. matricesIndicesCompressed = 0
  695. # Getting influences
  696. i = 0
  697. offset = 0
  698. for group in vertex.groups:
  699. index = group.group
  700. weight = group.weight
  701. for boneIndex, bone in enumerate(objArmature.pose.bones):
  702. if object.vertex_groups[index].name == bone.name:
  703. if (i == MAX_INFLUENCERS_PER_VERTEX):
  704. Main.warn('Maximum # of influencers exceeded for a vertex, extras ignored', 2)
  705. break
  706. matricesWeights[i] = weight
  707. matricesIndicesCompressed += boneIndex << offset
  708. offset = offset + 8
  709. i = i + 1
  710. # Texture coordinates
  711. if hasUV:
  712. vertex_UV = UVmap[face.index].uv[v]
  713. if hasUV2:
  714. vertex_UV2 = UV2map[face.index].uv[v]
  715. # Vertex color
  716. if hasVertexColor:
  717. if v == 0:
  718. vertex_Color = Colormap[face.index].color1
  719. if v == 1:
  720. vertex_Color = Colormap[face.index].color2
  721. if v == 2:
  722. vertex_Color = Colormap[face.index].color3
  723. # Check if the current vertex is already saved
  724. alreadySaved = alreadySavedVertices[vertex_index] and not (hasSkeleton or scene.export_noVertexOpt)
  725. if alreadySaved:
  726. alreadySaved = False
  727. # UV
  728. index_UV = 0
  729. for savedIndex in vertices_indices[vertex_index]:
  730. if hasUV:
  731. vUV = vertices_UVs[vertex_index][index_UV]
  732. if (vUV[0] != vertex_UV[0] or vUV[1] != vertex_UV[1]):
  733. continue
  734. if hasUV2:
  735. vUV2 = vertices_UV2s[vertex_index][index_UV]
  736. if (vUV2[0] != vertex_UV2[0] or vUV2[1] != vertex_UV2[1]):
  737. continue
  738. if hasVertexColor:
  739. vColor = vertices_Colors[vertex_index][index_UV]
  740. if (vColor.r != vertex_Color.r or vColor.g != vertex_Color.g or vColor.b != vertex_Color.b):
  741. continue
  742. if vertices_indices[vertex_index][index_UV] >= subMeshVerticesStart:
  743. alreadySaved = True
  744. break
  745. index_UV += 1
  746. if (alreadySaved):
  747. # Reuse vertex
  748. index = vertices_indices[vertex_index][index_UV]
  749. else:
  750. # Export new one
  751. index = verticesCount
  752. alreadySavedVertices[vertex_index] = True
  753. if hasUV:
  754. vertices_UVs[vertex_index].append(vertex_UV)
  755. self.uvs.append(vertex_UV[0])
  756. self.uvs.append(vertex_UV[1])
  757. if hasUV2:
  758. vertices_UV2s[vertex_index].append(vertex_UV2)
  759. self.uvs2.append(vertex_UV2[0])
  760. self.uvs2.append(vertex_UV2[1])
  761. if hasVertexColor:
  762. vertices_Colors[vertex_index].append(vertex_Color)
  763. self.colors.append(vertex_Color.r)
  764. self.colors.append(vertex_Color.g)
  765. self.colors.append(vertex_Color.b)
  766. self.colors.append(1.0)
  767. if hasSkeleton:
  768. self.skeletonWeights.append(matricesWeights[0])
  769. self.skeletonWeights.append(matricesWeights[1])
  770. self.skeletonWeights.append(matricesWeights[2])
  771. self.skeletonWeights.append(matricesWeights[3])
  772. self.skeletonIndicesCompressed.append(matricesIndicesCompressed)
  773. vertices_indices[vertex_index].append(index)
  774. self.positions.append(position)
  775. self.normals.append(normal)
  776. verticesCount += 1
  777. self.indices.append(index)
  778. indicesCount += 1
  779. self.subMeshes.append(SubMesh(materialIndex, subMeshVerticesStart, subMeshIndexStart, verticesCount - subMeshVerticesStart, indicesCount - subMeshIndexStart))
  780. if verticesCount > MAX_VERTEX_ELEMENTS:
  781. warn('Due to multi-materials & this meshes size, 32bit indices must be used. This may not run on all hardware.', 2)
  782. BakedMaterial.meshBakingClean(object)
  783. Main.log('num positions : ' + str(len(self.positions)), 2)
  784. Main.log('num normals : ' + str(len(self.normals )), 2)
  785. Main.log('num uvs : ' + str(len(self.uvs )), 2)
  786. Main.log('num uvs2 : ' + str(len(self.uvs2 )), 2)
  787. Main.log('num colors : ' + str(len(self.colors )), 2)
  788. Main.log('num indices : ' + str(len(self.indices )), 2)
  789. if hasattr(self, 'skeletonWeights'):
  790. Main.log('num skeletonWeights: ' + str(len(self.skeletonWeights)), 2)
  791. Main.log('num skeletonIndices: ' + str(len(self.skeletonIndicesCompressed * 4)), 2)
  792. if uvRequired and len(self.uvs) == 0:
  793. Main.warn('Textures being used, but no UV Map found', 2)
  794. numZeroAreaFaces = self.find_zero_area_faces()
  795. if numZeroAreaFaces > 0:
  796. Main.warn('# of 0 area faces found: ' + str(numZeroAreaFaces), 2)
  797. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  798. def find_zero_area_faces(self):
  799. nFaces = int(len(self.indices) / 3)
  800. nZeroAreaFaces = 0
  801. for f in range(0, nFaces):
  802. faceOffset = f * 3
  803. p1 = self.positions[self.indices[faceOffset ]]
  804. p2 = self.positions[self.indices[faceOffset + 1]]
  805. p3 = self.positions[self.indices[faceOffset + 2]]
  806. if same_vertex(p1, p2) or same_vertex(p1, p3) or same_vertex(p2, p3): nZeroAreaFaces += 1
  807. return nZeroAreaFaces
  808. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  809. @staticmethod
  810. def mesh_triangulate(mesh):
  811. try:
  812. import bmesh
  813. bm = bmesh.new()
  814. bm.from_mesh(mesh)
  815. bmesh.ops.triangulate(bm, faces = bm.faces)
  816. bm.to_mesh(mesh)
  817. mesh.calc_tessface()
  818. bm.free()
  819. except:
  820. pass
  821. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  822. def to_scene_file(self, file_handler):
  823. file_handler.write('{')
  824. write_string(file_handler, 'name', self.name, True)
  825. write_string(file_handler, 'id', self.name)
  826. if hasattr(self, 'parentId'): write_string(file_handler, 'parentId', self.parentId)
  827. if hasattr(self, 'materialId'): write_string(file_handler, 'materialId', self.materialId)
  828. write_int(file_handler, 'billboardMode', self.billboardMode)
  829. write_vector(file_handler, 'position', self.position)
  830. if hasattr(self, "rotationQuaternion"):
  831. write_quaternion(file_handler, 'rotationQuaternion', self.rotationQuaternion)
  832. else:
  833. write_vector(file_handler, 'rotation', self.rotation)
  834. write_vector(file_handler, 'scaling', self.scaling)
  835. write_bool(file_handler, 'isVisible', self.isVisible)
  836. write_bool(file_handler, 'freezeWorldMatrix', self.freezeWorldMatrix)
  837. write_bool(file_handler, 'isEnabled', self.isEnabled)
  838. write_bool(file_handler, 'useFlatShading', self.useFlatShading)
  839. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  840. write_bool(file_handler, 'receiveShadows', self.receiveShadows)
  841. if hasattr(self, 'physicsImpostor'):
  842. write_int(file_handler, 'physicsImpostor', self.physicsImpostor)
  843. write_float(file_handler, 'physicsMass', self.physicsMass)
  844. write_float(file_handler, 'physicsFriction', self.physicsFriction)
  845. write_float(file_handler, 'physicsRestitution', self.physicsRestitution)
  846. # Geometry
  847. if hasattr(self, 'skeletonId'): write_int(file_handler, 'skeletonId', self.skeletonId)
  848. write_vector_array(file_handler, 'positions', self.positions)
  849. write_vector_array(file_handler, 'normals' , self.normals )
  850. if len(self.uvs) > 0:
  851. write_array(file_handler, 'uvs', self.uvs)
  852. if len(self.uvs2) > 0:
  853. write_array(file_handler, 'uvs2', self.uvs2)
  854. if len(self.colors) > 0:
  855. write_array(file_handler, 'colors', self.colors)
  856. if hasattr(self, 'skeletonWeights'):
  857. write_array(file_handler, 'matricesWeights', self.skeletonWeights)
  858. write_array(file_handler, 'matricesIndices', self.skeletonIndicesCompressed)
  859. write_array(file_handler, 'indices', self.indices)
  860. # Sub meshes
  861. file_handler.write('\n,"subMeshes":[')
  862. first = True
  863. for subMesh in self.subMeshes:
  864. if first == False:
  865. file_handler.write(',')
  866. subMesh.to_scene_file(file_handler)
  867. first = False
  868. file_handler.write(']')
  869. super().to_scene_file(file_handler) # Animations
  870. # Instances
  871. first = True
  872. file_handler.write('\n,"instances":[')
  873. for instance in self.instances:
  874. if first == False:
  875. file_handler.write(',')
  876. instance.to_scene_file(file_handler)
  877. first = False
  878. file_handler.write(']')
  879. # Close mesh
  880. file_handler.write('}\n')
  881. self.alreadyExported = True
  882. #===============================================================================
  883. class MeshInstance:
  884. def __init__(self, name, position, rotation, rotationQuaternion, scaling, freezeWorldMatrix):
  885. self.name = name
  886. self.position = position
  887. if rotation is not None:
  888. self.rotation = rotation
  889. if rotationQuaternion is not None:
  890. self.rotationQuaternion = rotationQuaternion
  891. self.scaling = scaling
  892. self.freezeWorldMatrix = freezeWorldMatrix
  893. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  894. def to_scene_file(self, file_handler):
  895. file_handler.write('{')
  896. write_string(file_handler, 'name', self.name, True)
  897. write_vector(file_handler, 'position', self.position)
  898. if hasattr(self, 'rotation'):
  899. write_vector(file_handler, 'rotation', self.rotation)
  900. else:
  901. write_quaternion(file_handler, 'rotationQuaternion', self.rotationQuaternion)
  902. write_vector(file_handler, 'scaling', self.scaling)
  903. # freeze World Matrix currently ignored for instances
  904. write_bool(file_handler, 'freezeWorldMatrix', self.freezeWorldMatrix)
  905. file_handler.write('}')
  906. #===============================================================================
  907. class Node(FCurveAnimatable):
  908. def __init__(self, node):
  909. super().__init__(node, True, True, True) #Should animations be done when forcedParent
  910. Main.log('processing begun of node: ' + node.name)
  911. self.name = node.name
  912. if node.parent and node.parent.type != 'ARMATURE':
  913. self.parentId = node.parent.name
  914. loc, rot, scale = node.matrix_local.decompose()
  915. self.position = loc
  916. if node.rotation_mode == 'QUATERNION':
  917. self.rotationQuaternion = rot
  918. else:
  919. self.rotation = scale_vector(rot.to_euler('XYZ'), -1)
  920. self.scaling = scale
  921. self.isVisible = False
  922. self.isEnabled = True
  923. self.checkCollisions = False
  924. self.billboardMode = BILLBOARDMODE_NONE
  925. self.castShadows = False
  926. self.receiveShadows = False
  927. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  928. def to_scene_file(self, file_handler, ignored):
  929. file_handler.write('{')
  930. write_string(file_handler, 'name', self.name, True)
  931. write_string(file_handler, 'id', self.name)
  932. if hasattr(self, 'parentId'): write_string(file_handler, 'parentId', self.parentId)
  933. write_vector(file_handler, 'position', self.position)
  934. if hasattr(self, "rotationQuaternion"):
  935. write_quaternion(file_handler, "rotationQuaternion", self.rotationQuaternion)
  936. else:
  937. write_vector(file_handler, 'rotation', self.rotation)
  938. write_vector(file_handler, 'scaling', self.scaling)
  939. write_bool(file_handler, 'isVisible', self.isVisible)
  940. write_bool(file_handler, 'isEnabled', self.isEnabled)
  941. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  942. write_int(file_handler, 'billboardMode', self.billboardMode)
  943. write_bool(file_handler, 'receiveShadows', self.receiveShadows)
  944. super().to_scene_file(file_handler) # Animations
  945. file_handler.write('}')
  946. #===============================================================================
  947. class SubMesh:
  948. def __init__(self, materialIndex, verticesStart, indexStart, verticesCount, indexCount):
  949. self.materialIndex = materialIndex
  950. self.verticesStart = verticesStart
  951. self.indexStart = indexStart
  952. self.verticesCount = verticesCount
  953. self.indexCount = indexCount
  954. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  955. def to_scene_file(self, file_handler):
  956. file_handler.write('{')
  957. write_int(file_handler, 'materialIndex', self.materialIndex, True)
  958. write_int(file_handler, 'verticesStart', self.verticesStart)
  959. write_int(file_handler, 'verticesCount', self.verticesCount)
  960. write_int(file_handler, 'indexStart' , self.indexStart)
  961. write_int(file_handler, 'indexCount' , self.indexCount)
  962. file_handler.write('}')
  963. #===============================================================================
  964. class Bone:
  965. def __init__(self, bone, skeleton, scene, index):
  966. Main.log('processing begun of bone: ' + bone.name + ', index: '+ str(index))
  967. self.name = bone.name
  968. self.index = index
  969. matrix_world = skeleton.matrix_world
  970. self.matrix = Bone.get_matrix(bone, matrix_world)
  971. parentId = -1
  972. if (bone.parent):
  973. for parent in skeleton.pose.bones:
  974. parentId += 1
  975. if parent == bone.parent:
  976. break;
  977. self.parentBoneIndex = parentId
  978. #animation
  979. if (skeleton.animation_data):
  980. Main.log('animation begun of bone: ' + self.name)
  981. self.animation = Animation(ANIMATIONTYPE_MATRIX, scene.render.fps, ANIMATIONLOOPMODE_CYCLE, 'anim', '_matrix')
  982. start_frame = scene.frame_start
  983. end_frame = scene.frame_end
  984. previousBoneMatrix = None
  985. for frame in range(start_frame, end_frame + 1):
  986. bpy.context.scene.frame_set(frame)
  987. currentBoneMatrix = Bone.get_matrix(bone, matrix_world)
  988. if (frame != end_frame and currentBoneMatrix == previousBoneMatrix):
  989. continue
  990. self.animation.frames.append(frame)
  991. self.animation.values.append(Bone.get_matrix(bone, matrix_world))
  992. previousBoneMatrix = currentBoneMatrix
  993. bpy.context.scene.frame_set(start_frame)
  994. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  995. @staticmethod
  996. def get_matrix(bone, matrix_world):
  997. SystemMatrix = mathutils.Matrix.Scale(-1, 4, mathutils.Vector((0, 0, 1))) * mathutils.Matrix.Rotation(math.radians(-90), 4, 'X')
  998. if (bone.parent):
  999. return (SystemMatrix * matrix_world * bone.parent.matrix).inverted() * (SystemMatrix * matrix_world * bone.matrix)
  1000. else:
  1001. return SystemMatrix * matrix_world * bone.matrix
  1002. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1003. def to_scene_file(self, file_handler):
  1004. file_handler.write('\n{')
  1005. write_string(file_handler, 'name', self.name, True)
  1006. write_int(file_handler, 'index', self.index)
  1007. write_matrix4(file_handler, 'matrix', self.matrix)
  1008. write_int(file_handler, 'parentBoneIndex', self.parentBoneIndex)
  1009. #animation
  1010. if hasattr(self, 'animation'):
  1011. file_handler.write(',"animation":')
  1012. self.animation.to_scene_file(file_handler)
  1013. file_handler.write('}')
  1014. #===============================================================================
  1015. class Skeleton:
  1016. def __init__(self, skeleton, scene, id):
  1017. Main.log('processing begun of skeleton: ' + skeleton.name + ', id: '+ str(id))
  1018. self.name = skeleton.name
  1019. self.id = id
  1020. self.bones = []
  1021. bones = skeleton.pose.bones
  1022. j = 0
  1023. for bone in bones:
  1024. self.bones.append(Bone(bone, skeleton, scene, j))
  1025. j = j + 1
  1026. Main.log('processing complete of skeleton: ' + skeleton.name)
  1027. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1028. def to_scene_file(self, file_handler):
  1029. file_handler.write('{')
  1030. write_string(file_handler, 'name', self.name, True)
  1031. write_int(file_handler, 'id', self.id) # keep int for legacy of original exporter
  1032. file_handler.write(',"bones":[')
  1033. first = True
  1034. for bone in self.bones:
  1035. if first != True:
  1036. file_handler.write(',')
  1037. first = False
  1038. bone.to_scene_file(file_handler)
  1039. file_handler.write(']')
  1040. file_handler.write('}')
  1041. #===============================================================================
  1042. class Camera(FCurveAnimatable):
  1043. def __init__(self, camera):
  1044. super().__init__(camera, True, True, False, math.pi / 2)
  1045. if camera.parent and camera.parent.type != 'ARMATURE':
  1046. self.parentId = camera.parent.name
  1047. self.CameraType = camera.data.CameraType
  1048. self.name = camera.name
  1049. Main.log('processing begun of camera (' + self.CameraType + '): ' + self.name)
  1050. self.position = camera.location
  1051. # for quaternions, convert to euler XYZ, otherwise, use the default rotation_euler
  1052. eul = camera.rotation_quaternion.to_euler("XYZ") if camera.rotation_mode == 'QUATERNION' else camera.rotation_euler
  1053. self.rotation = mathutils.Vector((-eul[0] + math.pi / 2, eul[1], -eul[2]))
  1054. self.fov = camera.data.angle
  1055. self.minZ = camera.data.clip_start
  1056. self.maxZ = camera.data.clip_end
  1057. self.speed = 1.0
  1058. self.inertia = 0.9
  1059. self.checkCollisions = camera.data.checkCollisions
  1060. self.applyGravity = camera.data.applyGravity
  1061. self.ellipsoid = camera.data.ellipsoid
  1062. self.Camera3DRig = camera.data.Camera3DRig
  1063. self.interaxialDistance = camera.data.interaxialDistance
  1064. for constraint in camera.constraints:
  1065. if constraint.type == 'TRACK_TO':
  1066. self.lockedTargetId = constraint.target.name
  1067. break
  1068. if self.CameraType == ARC_ROTATE_CAM or self.CameraType == FOLLOW_CAM:
  1069. if not hasattr(self, 'lockedTargetId'):
  1070. Main.warn('Camera type with manditory target specified, but no target to track set. Ignored', 2)
  1071. self.fatalProblem = True
  1072. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1073. def update_for_target_attributes(self, meshesAndNodes):
  1074. if not hasattr(self, 'lockedTargetId'): return
  1075. # find the actual mesh tracking, so properties can be derrived
  1076. targetFound = False
  1077. for mesh in meshesAndNodes:
  1078. if mesh.name == self.lockedTargetId:
  1079. targetMesh = mesh
  1080. targetFound = True
  1081. break;
  1082. xApart = 3 if not targetFound else self.position.x - targetMesh.position.x
  1083. yApart = 3 if not targetFound else self.position.y - targetMesh.position.y
  1084. zApart = 3 if not targetFound else self.position.z - targetMesh.position.z
  1085. distance3D = math.sqrt(xApart * xApart + yApart * yApart + zApart * zApart)
  1086. alpha = math.atan2(yApart, xApart);
  1087. beta = math.atan2(yApart, zApart);
  1088. if self.CameraType == FOLLOW_CAM:
  1089. self.followHeight = zApart
  1090. self.followDistance = distance3D
  1091. self.followRotation = 90 + (alpha * 180 / math.pi)
  1092. elif self.CameraType == self.CameraType == ARC_ROTATE_CAM:
  1093. self.arcRotAlpha = alpha
  1094. self.arcRotBeta = beta
  1095. self.arcRotRadius = distance3D
  1096. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1097. def to_scene_file(self, file_handler):
  1098. file_handler.write('{')
  1099. write_string(file_handler, 'name', self.name, True)
  1100. write_string(file_handler, 'id', self.name)
  1101. write_vector(file_handler, 'position', self.position)
  1102. write_vector(file_handler, 'rotation', self.rotation)
  1103. write_float(file_handler, 'fov', self.fov)
  1104. write_float(file_handler, 'minZ', self.minZ)
  1105. write_float(file_handler, 'maxZ', self.maxZ)
  1106. write_float(file_handler, 'speed', self.speed)
  1107. write_float(file_handler, 'inertia', self.inertia)
  1108. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  1109. write_bool(file_handler, 'applyGravity', self.applyGravity)
  1110. write_array3(file_handler, 'ellipsoid', self.ellipsoid)
  1111. # always assign rig, even when none, Reason: Could have VR camera with different Rig than default
  1112. write_int(file_handler, 'cameraRigMode', self.Camera3DRig)
  1113. write_float(file_handler, 'interaxial_distance', self.interaxialDistance)
  1114. write_string(file_handler, 'type', self.CameraType)
  1115. if hasattr(self, 'parentId'): write_string(file_handler, 'parentId', self.parentId)
  1116. if self.CameraType == FOLLOW_CAM:
  1117. write_float(file_handler, 'heightOffset', self.followHeight)
  1118. write_float(file_handler, 'radius', self.followDistance)
  1119. write_float(file_handler, 'rotationOffset', self.followRotation)
  1120. elif self.CameraType == ARC_ROTATE_CAM:
  1121. write_float(file_handler, 'alpha', self.arcRotAlpha)
  1122. write_float(file_handler, 'beta', self.arcRotBeta)
  1123. write_float(file_handler, 'radius', self.arcRotRadius)
  1124. if hasattr(self, 'lockedTargetId'):
  1125. write_string(file_handler, 'lockedTargetId', self.lockedTargetId)
  1126. super().to_scene_file(file_handler) # Animations
  1127. file_handler.write('}')
  1128. #===============================================================================
  1129. class Light(FCurveAnimatable):
  1130. def __init__(self, light):
  1131. super().__init__(light, False, True, False)
  1132. if light.parent and light.parent.type != 'ARMATURE':
  1133. self.parentId = light.parent.name
  1134. self.name = light.name
  1135. Main.log('processing begun of light (' + light.data.type + '): ' + self.name)
  1136. light_type_items = {'POINT': POINT_LIGHT, 'SUN': DIRECTIONAL_LIGHT, 'SPOT': SPOT_LIGHT, 'HEMI': HEMI_LIGHT, 'AREA': POINT_LIGHT}
  1137. self.light_type = light_type_items[light.data.type]
  1138. if self.light_type == POINT_LIGHT:
  1139. self.position = light.location
  1140. if hasattr(light.data, 'use_sphere'):
  1141. if light.data.use_sphere:
  1142. self.range = light.data.distance
  1143. elif self.light_type == DIRECTIONAL_LIGHT:
  1144. self.position = light.location
  1145. self.direction = Light.get_direction(light.matrix_local)
  1146. elif self.light_type == SPOT_LIGHT:
  1147. self.position = light.location
  1148. self.direction = Light.get_direction(light.matrix_local)
  1149. self.angle = light.data.spot_size
  1150. self.exponent = light.data.spot_blend * 2
  1151. if light.data.use_sphere:
  1152. self.range = light.data.distance
  1153. else:
  1154. # Hemi
  1155. matrix_local = light.matrix_local.copy()
  1156. matrix_local.translation = mathutils.Vector((0, 0, 0))
  1157. self.direction = (mathutils.Vector((0, 0, -1)) * matrix_local)
  1158. self.direction = scale_vector(self.direction, -1)
  1159. self.groundColor = mathutils.Color((0, 0, 0))
  1160. self.intensity = light.data.energy
  1161. self.diffuse = light.data.color if light.data.use_diffuse else mathutils.Color((0, 0, 0))
  1162. self.specular = light.data.color if light.data.use_specular else mathutils.Color((0, 0, 0))
  1163. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1164. def to_scene_file(self, file_handler):
  1165. file_handler.write('{')
  1166. write_string(file_handler, 'name', self.name, True)
  1167. write_string(file_handler, 'id', self.name)
  1168. write_float(file_handler, 'type', self.light_type)
  1169. if hasattr(self, 'parentId' ): write_string(file_handler, 'parentId' , self.parentId )
  1170. if hasattr(self, 'position' ): write_vector(file_handler, 'position' , self.position )
  1171. if hasattr(self, 'direction' ): write_vector(file_handler, 'direction' , self.direction )
  1172. if hasattr(self, 'angle' ): write_float (file_handler, 'angle' , self.angle )
  1173. if hasattr(self, 'exponent' ): write_float (file_handler, 'exponent' , self.exponent )
  1174. if hasattr(self, 'groundColor'): write_color (file_handler, 'groundColor', self.groundColor)
  1175. if hasattr(self, 'range' ): write_float (file_handler, 'range' , self.range )
  1176. write_float(file_handler, 'intensity', self.intensity)
  1177. write_color(file_handler, 'diffuse', self.diffuse)
  1178. write_color(file_handler, 'specular', self.specular)
  1179. super().to_scene_file(file_handler) # Animations
  1180. file_handler.write('}')
  1181. @staticmethod
  1182. def get_direction(matrix):
  1183. return (matrix.to_3x3() * mathutils.Vector((0.0, 0.0, -1.0))).normalized()
  1184. #===============================================================================
  1185. class ShadowGenerator:
  1186. def __init__(self, lamp, meshesAndNodes, scene):
  1187. Main.log('processing begun of shadows for light: ' + lamp.name)
  1188. self.lightId = lamp.name
  1189. self.mapSize = lamp.data.shadowMapSize
  1190. self.shadowBias = lamp.data.shadowBias
  1191. if lamp.data.shadowMap == VARIANCE_SHADOWS:
  1192. self.useVarianceShadowMap = True
  1193. elif lamp.data.shadowMap == POISSON_SHADOWS:
  1194. self.usePoissonSampling = True
  1195. elif lamp.data.shadowMap == BLUR_VARIANCE_SHADOWS:
  1196. self.useBlurVarianceShadowMap = True
  1197. self.shadowBlurScale = lamp.data.shadowBlurScale
  1198. self.shadowBlurBoxOffset = lamp.data.shadowBlurBoxOffset
  1199. # .babylon specific section
  1200. self.shadowCasters = []
  1201. for mesh in meshesAndNodes:
  1202. if (mesh.castShadows):
  1203. self.shadowCasters.append(mesh.name)
  1204. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1205. def to_scene_file(self, file_handler):
  1206. file_handler.write('{')
  1207. write_int(file_handler, 'mapSize', self.mapSize, True)
  1208. write_string(file_handler, 'lightId', self.lightId)
  1209. write_float(file_handler, 'bias', self.shadowBias)
  1210. if hasattr(self, 'useVarianceShadowMap') :
  1211. write_bool(file_handler, 'useVarianceShadowMap', self.useVarianceShadowMap)
  1212. elif hasattr(self, 'usePoissonSampling'):
  1213. write_bool(file_handler, 'usePoissonSampling', self.usePoissonSampling)
  1214. elif hasattr(self, 'useBlurVarianceShadowMap'):
  1215. write_bool(file_handler, 'useBlurVarianceShadowMap', self.useBlurVarianceShadowMap)
  1216. write_int(file_handler, 'blurScale', self.shadowBlurScale)
  1217. write_int(file_handler, 'blurBoxOffset', self.shadowBlurBoxOffset)
  1218. file_handler.write(',"renderList":[')
  1219. first = True
  1220. for caster in self.shadowCasters:
  1221. if first != True:
  1222. file_handler.write(',')
  1223. first = False
  1224. file_handler.write('"' + caster + '"')
  1225. file_handler.write(']')
  1226. file_handler.write('}')
  1227. #===============================================================================
  1228. class MultiMaterial:
  1229. def __init__(self, material_slots, idx):
  1230. self.name = Main.nameSpace + '.' + 'Multimaterial#' + str(idx)
  1231. Main.log('processing begun of multimaterial: ' + self.name, 2)
  1232. self.material_slots = material_slots
  1233. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1234. def to_scene_file(self, file_handler):
  1235. file_handler.write('{')
  1236. write_string(file_handler, 'name', self.name, True)
  1237. write_string(file_handler, 'id', self.name)
  1238. file_handler.write(',"materials":[')
  1239. first = True
  1240. for material in self.material_slots:
  1241. if first != True:
  1242. file_handler.write(',')
  1243. file_handler.write('"' + material.name +'"')
  1244. first = False
  1245. file_handler.write(']')
  1246. file_handler.write('}')
  1247. #===============================================================================
  1248. class Texture:
  1249. def __init__(self, slot, level, textureOrImage, mesh, exporter):
  1250. wasBaked = not hasattr(textureOrImage, 'uv_layer')
  1251. if wasBaked:
  1252. image = textureOrImage
  1253. texture = None
  1254. repeat = False
  1255. self.hasAlpha = False
  1256. self.coordinatesIndex = 0
  1257. else:
  1258. texture = textureOrImage
  1259. image = texture.texture.image
  1260. repeat = texture.texture.extension == 'REPEAT'
  1261. self.hasAlpha = texture.texture.use_alpha
  1262. usingMap = texture.uv_layer
  1263. Main.log('Image texture found, type: ' + slot + ', mapped using: ' + usingMap, 3)
  1264. if mesh.data.uv_textures[0].name == usingMap:
  1265. self.coordinatesIndex = 0
  1266. elif mesh.data.uv_textures[1].name == usingMap:
  1267. self.coordinatesIndex = 1
  1268. else:
  1269. Main.warn('Texture is not mapped as UV or UV2, assigned 1', 4)
  1270. self.coordinatesIndex = 0
  1271. # always write the file out, since base64 encoding is easiest from a file
  1272. try:
  1273. imageFilepath = os.path.normpath(bpy.path.abspath(image.filepath))
  1274. basename = os.path.basename(imageFilepath)
  1275. targetdir = os.path.dirname(exporter.filepath)
  1276. internalImage = image.packed_file or wasBaked
  1277. # when coming from either a packed image or a baked image, then save_render
  1278. if internalImage:
  1279. if exporter.scene.inlineTextures:
  1280. textureFile = os.path.join(targetdir, basename + "temp")
  1281. else:
  1282. textureFile = os.path.join(targetdir, basename)
  1283. image.save_render(textureFile)
  1284. # when backed by an actual file, copy to target dir, unless inlining
  1285. else:
  1286. textureFile = bpy.path.abspath(image.filepath)
  1287. if not exporter.scene.inlineTextures:
  1288. shutil.copy(textureFile, targetdir)
  1289. except:
  1290. ex = sys.exc_info()
  1291. Main.log('Error encountered processing image file: ' + ', Error: '+ str(ex[1]))
  1292. if exporter.scene.inlineTextures:
  1293. # base64 is easiest from a file, so sometimes a temp file was made above; need to delete those
  1294. with open(textureFile, "rb") as image_file:
  1295. asString = base64.b64encode(image_file.read()).decode()
  1296. self.encoded_URI = 'data:image/' + image.file_format + ';base64,' + asString
  1297. if internalImage:
  1298. os.remove(textureFile)
  1299. # capture texture attributes
  1300. self.slot = slot
  1301. self.name = basename
  1302. self.level = level
  1303. if (texture and texture.mapping == 'CUBE'):
  1304. self.coordinatesMode = CUBIC_MODE
  1305. if (texture and texture.mapping == 'SPHERE'):
  1306. self.coordinatesMode = SPHERICAL_MODE
  1307. else:
  1308. self.coordinatesMode = EXPLICIT_MODE
  1309. self.uOffset = texture.offset.x if texture else 0.0
  1310. self.vOffset = texture.offset.y if texture else 0.0
  1311. self.uScale = texture.scale.x if texture else 1.0
  1312. self.vScale = texture.scale.y if texture else 1.0
  1313. self.uAng = 0
  1314. self.vAng = 0
  1315. self.wAng = 0
  1316. if (repeat):
  1317. if (texture.texture.use_mirror_x):
  1318. self.wrapU = MIRROR_ADDRESSMODE
  1319. else:
  1320. self.wrapU = WRAP_ADDRESSMODE
  1321. if (texture.texture.use_mirror_y):
  1322. self.wrapV = MIRROR_ADDRESSMODE
  1323. else:
  1324. self.wrapV = WRAP_ADDRESSMODE
  1325. else:
  1326. self.wrapU = CLAMP_ADDRESSMODE
  1327. self.wrapV = CLAMP_ADDRESSMODE
  1328. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1329. def to_scene_file(self, file_handler):
  1330. file_handler.write(', \n"' + self.slot + '":{')
  1331. write_string(file_handler, 'name', self.name, True)
  1332. write_float(file_handler, 'level', self.level)
  1333. write_float(file_handler, 'hasAlpha', self.hasAlpha)
  1334. write_int(file_handler, 'coordinatesMode', self.coordinatesMode)
  1335. write_float(file_handler, 'uOffset', self.uOffset)
  1336. write_float(file_handler, 'vOffset', self.vOffset)
  1337. write_float(file_handler, 'uScale', self.uScale)
  1338. write_float(file_handler, 'vScale', self.vScale)
  1339. write_float(file_handler, 'uAng', self.uAng)
  1340. write_float(file_handler, 'vAng', self.vAng)
  1341. write_float(file_handler, 'wAng', self.wAng)
  1342. write_int(file_handler, 'wrapU', self.wrapU)
  1343. write_int(file_handler, 'wrapV', self.wrapV)
  1344. write_int(file_handler, 'coordinatesIndex', self.coordinatesIndex)
  1345. if hasattr(self,'encoded_URI'):
  1346. write_string(file_handler, 'base64String', self.encoded_URI)
  1347. file_handler.write('}')
  1348. #===============================================================================
  1349. # need to evaluate the need to bake a mesh before even starting; class also stores specific types of bakes
  1350. class BakingRecipe:
  1351. def __init__(self, mesh, forceBaking = False):
  1352. # initialize all members
  1353. self.needsBaking = forceBaking
  1354. self.diffuseBaking = forceBaking
  1355. self.ambientBaking = False
  1356. self.opacityBaking = False
  1357. self.reflectionBaking = False
  1358. self.emissiveBaking = False
  1359. self.bumpBaking = False
  1360. self.specularBaking = False
  1361. # need to make sure a single render
  1362. self.cyclesRender = False
  1363. blenderRender = False
  1364. # transfer from Mesh custom properties
  1365. self.bakeSize = mesh.data.bakeSize
  1366. self.bakeQuality = mesh.data.bakeQuality # for lossy compression formats
  1367. # accumulators set by Blender Game
  1368. self.backFaceCulling = True # used only when baking
  1369. self.billboardMode = BILLBOARDMODE_ALL if len(mesh.material_slots) == 1 and mesh.material_slots[0].material.game_settings.face_orientation == 'BILLBOARD' else BILLBOARDMODE_NONE
  1370. # Cycles specific, need to get the node trees of each material
  1371. self.nodeTrees = []
  1372. for material_slot in mesh.material_slots:
  1373. # a material slot is not a reference to an actual material; need to look up
  1374. material = material_slot.material
  1375. self.backFaceCulling &= material.game_settings.use_backface_culling
  1376. # testing for Cycles renderer has to be different
  1377. if material.use_nodes == True:
  1378. self.needsBaking = True
  1379. self.cyclesRender = True
  1380. self.nodeTrees.append(material.node_tree)
  1381. for node in material.node_tree.nodes:
  1382. id = node.bl_idname
  1383. if id == 'ShaderNodeBsdfDiffuse':
  1384. self.diffuseBaking = True
  1385. if id == 'ShaderNodeAmbientOcclusion':
  1386. self.ambientBaking = True
  1387. # there is no opacity baking for Cycles AFAIK
  1388. if id == '':
  1389. self.opacityBaking = True
  1390. if id == 'ShaderNodeEmission':
  1391. self.emissiveBaking = True
  1392. if id == 'ShaderNodeNormal' or id == 'ShaderNodeNormalMap':
  1393. self.bumpBaking = True
  1394. if id == '':
  1395. self.specularBaking = True
  1396. else:
  1397. blenderRender = True
  1398. textures = [mtex for mtex in material.texture_slots if mtex and mtex.texture]
  1399. for mtex in textures:
  1400. if mtex.texture.type == 'IMAGE' or mtex.texture.type == 'NONE':
  1401. continue
  1402. self.needsBaking = True
  1403. if mtex.use_map_diffuse or mtex.use_map_color_diffuse:
  1404. if mtex.texture_coords == 'REFLECTION':
  1405. self.reflectionBaking = True
  1406. else:
  1407. self.diffuseBaking = True
  1408. if mtex.use_map_ambient:
  1409. self.ambientBaking = True
  1410. if mtex.use_map_alpha:
  1411. self.opacityBaking = True
  1412. if mtex.use_map_emit:
  1413. self.emissiveBaking = True
  1414. if mtex.use_map_normal:
  1415. self.bumpBaking = True
  1416. if mtex.use_map_color_spec:
  1417. self.specularBaking = True
  1418. self.multipleRenders = blenderRender and self.cyclesRender
  1419. # check for really old .blend file, eg. 2.49, to ensure that everything requires exists
  1420. if self.needsBaking and bpy.data.screens.find('UV Editing') == -1:
  1421. Main.warn('Contains material requiring baking, but resources not available. Probably .blend very old', 2)
  1422. self.needsBaking = False
  1423. #===============================================================================
  1424. # Not intended to be instanced directly
  1425. class Material:
  1426. def __init__(self):
  1427. # the number of users == 1 will cause the checkReadyOnlyOnce attribute to be set to true
  1428. self.numOfUsers = 1
  1429. # first pass of textures, either appending image type or recording types of bakes to do
  1430. self.textures = []
  1431. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1432. def to_scene_file(self, file_handler):
  1433. file_handler.write('{')
  1434. write_string(file_handler, 'name', self.name, True)
  1435. write_string(file_handler, 'id', self.name)
  1436. write_color(file_handler, 'ambient', self.ambient)
  1437. write_color(file_handler, 'diffuse', self.diffuse)
  1438. write_color(file_handler, 'specular', self.specular)
  1439. write_color(file_handler, 'emissive', self.emissive)
  1440. write_float(file_handler, 'specularPower', self.specularPower)
  1441. write_float(file_handler, 'alpha', self.alpha)
  1442. write_bool(file_handler, 'backFaceCulling', self.backFaceCulling)
  1443. if self.numOfUsers == 1:
  1444. write_bool(file_handler, 'checkReadyOnlyOnce', True)
  1445. for texSlot in self.textures:
  1446. texSlot.to_scene_file(file_handler)
  1447. file_handler.write('}')
  1448. #===============================================================================
  1449. class StdMaterial(Material):
  1450. def __init__(self, material_slot, exporter, mesh):
  1451. super().__init__()
  1452. self.name = Main.nameSpace + '.' + material_slot.name
  1453. Main.log('processing begun of Standard material: ' + material_slot.name, 2)
  1454. # a material slot is not a reference to an actual material; need to look up
  1455. material = material_slot.material
  1456. self.ambient = material.ambient * material.diffuse_color
  1457. self.diffuse = material.diffuse_intensity * material.diffuse_color
  1458. self.specular = material.specular_intensity * material.specular_color
  1459. self.emissive = material.emit * material.diffuse_color
  1460. self.specularPower = material.specular_hardness
  1461. self.alpha = material.alpha
  1462. self.backFaceCulling = material.game_settings.use_backface_culling
  1463. textures = [mtex for mtex in material.texture_slots if mtex and mtex.texture]
  1464. for mtex in textures:
  1465. # test should be un-neccessary, since should be a BakedMaterial; just for completeness
  1466. if (mtex.texture.type != 'IMAGE'):
  1467. continue
  1468. elif not mtex.texture.image:
  1469. Main.warn('Material has un-assigned image texture: "' + mtex.name + '" ignored', 3)
  1470. continue
  1471. elif len(mtex.uv_layer) == 0:
  1472. Main.warn('Material has image texture with no UV map assigned: "' + mtex.name + '" ignored', 3)
  1473. continue
  1474. if mtex.use_map_diffuse or mtex.use_map_color_diffuse:
  1475. if mtex.texture_coords == 'REFLECTION':
  1476. Main.log('Reflection texture found', 2)
  1477. self.textures.append(Texture('reflectionTexture', mtex.diffuse_color_factor, mtex, mesh, exporter))
  1478. else:
  1479. Main.log('Diffuse texture found', 2)
  1480. self.textures.append(Texture('diffuseTexture', mtex.diffuse_color_factor, mtex, mesh, exporter))
  1481. if mtex.use_map_ambient:
  1482. Main.log('Ambient texture found', 2)
  1483. self.textures.append(Texture('ambientTexture', mtex.ambient_factor, mtex, mesh, exporter))
  1484. if mtex.use_map_alpha:
  1485. Main.log('Opacity texture found', 2)
  1486. self.textures.append(Texture('opacityTexture', mtex.alpha_factor, mtex, mesh, exporter))
  1487. if mtex.use_map_emit:
  1488. Main.log('Emissive texture found', 2)
  1489. self.textures.append(Texture('emissiveTexture', mtex.emit_factor, mtex, mesh, exporter))
  1490. if mtex.use_map_normal:
  1491. Main.log('Bump texture found', 2)
  1492. self.textures.append(Texture('bumpTexture', 1.0 / mtex.normal_factor, mtex, mesh, exporter))
  1493. if mtex.use_map_color_spec:
  1494. Main.log('Specular texture found', 2)
  1495. self.textures.append(Texture('specularTexture', mtex.specular_color_factor, mtex, mesh, exporter))
  1496. #===============================================================================
  1497. class BakedMaterial(Material):
  1498. def __init__(self, exporter, mesh, recipe):
  1499. super().__init__()
  1500. self.name = Main.nameSpace + '.' + mesh.name
  1501. Main.log('processing begun of baked material: ' + mesh.name, 2)
  1502. # any baking already took in the values. Do not want to apply them again, but want shadows to show.
  1503. # These are the default values from StandardMaterials
  1504. self.ambient = mathutils.Color((0, 0, 0))
  1505. self.diffuse = mathutils.Color((0.8, 0.8, 0.8)) # needed for shadows, but not change anything else
  1506. self.specular = mathutils.Color((1, 1, 1))
  1507. self.emissive = mathutils.Color((0, 0, 0))
  1508. self.specularPower = 64
  1509. self.alpha = 1.0
  1510. self.backFaceCulling = recipe.backFaceCulling
  1511. # texture is baked from selected mesh(es), need to insure this mesh is only one selected
  1512. bpy.ops.object.select_all(action='DESELECT')
  1513. mesh.select = True
  1514. # store setting to restore
  1515. engine = exporter.scene.render.engine
  1516. # mode_set's only work when there is an active object
  1517. exporter.scene.objects.active = mesh
  1518. # you need UV on a mesh in order to bake image. This is not reqd for procedural textures, so may not exist
  1519. # need to look if it might already be created, as for a mesh with multi-materials
  1520. uv = None
  1521. for uvMap in mesh.data.uv_textures:
  1522. if uvMap.name == 'BakingUV':
  1523. uv = uvMap
  1524. break
  1525. if uv == None:
  1526. mesh.data.uv_textures.new('BakingUV')
  1527. uv = mesh.data.uv_textures['BakingUV']
  1528. uv.active = True
  1529. uv.active_render = True
  1530. # UV unwrap operates on mesh in only edit mode
  1531. # select all verticies of mesh, since smart_project works only with selected verticies
  1532. bpy.ops.object.mode_set(mode='EDIT')
  1533. bpy.ops.mesh.select_all(action='SELECT')
  1534. bpy.ops.uv.smart_project(angle_limit = 66.0, island_margin = 0.0, user_area_weight = 1.0, use_aspect = True)
  1535. # create a temporary image & link it to the UV/Image Editor so bake_image works
  1536. bpy.data.images.new(name = mesh.name + '_BJS_BAKE', width = recipe.bakeSize, height = recipe.bakeSize, alpha = False, float_buffer = False)
  1537. image = bpy.data.images[mesh.name + '_BJS_BAKE']
  1538. image.file_format = 'JPEG'
  1539. image.mapping = 'UV' # default value
  1540. image_settings = exporter.scene.render.image_settings
  1541. image_settings.file_format = 'JPEG'
  1542. image_settings.quality = recipe.bakeQuality # for lossy compression formats
  1543. # image_settings.compression = 100 # Amount of time to determine best compression: 0 = no compression with fast file output, 100 = maximum lossless compression with slow file output
  1544. # now go thru all the textures that need to be baked
  1545. if recipe.diffuseBaking:
  1546. self.bake('diffuseTexture', 'DIFFUSE_COLOR', 'TEXTURE', image, mesh, exporter, recipe)
  1547. if recipe.ambientBaking:
  1548. self.bake('ambientTexture', 'AO', 'AO', image, mesh, exporter, recipe)
  1549. if recipe.opacityBaking: # no eqivalent found for cycles
  1550. self.bake('opacityTexture', None, 'ALPHA', image, mesh, exporter, recipe)
  1551. if recipe.reflectionBaking:
  1552. self.bake('reflectionTexture', 'REFLECTION', 'MIRROR_COLOR', image, mesh, exporter, recipe)
  1553. if recipe.emissiveBaking:
  1554. self.bake('emissiveTexture', 'EMIT', 'EMIT', image, mesh, exporter, recipe)
  1555. if recipe.bumpBaking:
  1556. self.bake('bumpTexture', 'NORMAL', 'NORMALS', image, mesh, exporter, recipe)
  1557. if recipe.specularBaking:
  1558. self.bake('specularTexture', 'SPECULAR', 'SPEC_COLOR', image, mesh, exporter, recipe)
  1559. # Toggle vertex selection & mode, if setting changed their value
  1560. bpy.ops.mesh.select_all(action='TOGGLE') # still in edit mode toggle select back to previous
  1561. bpy.ops.object.mode_set(toggle=True) # change back to Object
  1562. bpy.ops.object.select_all(action='TOGGLE') # change scene selection back, not seeming to work
  1563. exporter.scene.render.engine = engine
  1564. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1565. def bake(self, bjs_type, cycles_type, internal_type, image, mesh, exporter, recipe):
  1566. if recipe.cyclesRender:
  1567. if cycles_type is None:
  1568. return
  1569. self.bakeCycles(cycles_type, image, recipe.nodeTrees)
  1570. else:
  1571. self.bakeInternal(internal_type, image)
  1572. self.textures.append(Texture(bjs_type, 1.0, image, mesh, exporter))
  1573. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1574. def bakeInternal(self, bake_type, image):
  1575. Main.log('Internal baking texture, type: ' + bake_type + ', mapped using: BakingUV', 3)
  1576. image.filepath = self.name + '_' + bake_type + '.jpg'
  1577. scene = bpy.context.scene
  1578. scene.render.engine = 'BLENDER_RENDER'
  1579. scene.render.bake_type = bake_type
  1580. # assign the image to the UV Editor, which does not have to shown
  1581. bpy.data.screens['UV Editing'].areas[1].spaces[0].image = image
  1582. renderer = scene.render
  1583. renderer.use_bake_selected_to_active = False
  1584. renderer.use_bake_to_vertex_color = False
  1585. renderer.use_bake_clear = True
  1586. renderer.bake_quad_split = 'AUTO'
  1587. renderer.bake_margin = 5
  1588. renderer.use_file_extension = True
  1589. renderer.use_bake_normalize = True
  1590. renderer.use_bake_antialiasing = True
  1591. bpy.ops.object.bake_image()
  1592. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1593. def bakeCycles(self, bake_type, image, nodeTrees):
  1594. Main.log('Cycles baking texture, type: ' + bake_type + ', mapped using: BakingUV', 3)
  1595. image.filepath = self.name + '_' + bake_type + '.jpg'
  1596. scene = bpy.context.scene
  1597. scene.render.engine = 'CYCLES'
  1598. # create an unlinked temporary node to bake to for each material
  1599. for tree in nodeTrees:
  1600. bakeNode = tree.nodes.new(type='ShaderNodeTexImage')
  1601. bakeNode.image = image
  1602. bakeNode.select = True
  1603. tree.nodes.active = bakeNode
  1604. bpy.ops.object.bake(type = bake_type, use_clear = True, margin = 5, use_selected_to_active = False)
  1605. for tree in nodeTrees:
  1606. tree.nodes.remove(tree.nodes.active)
  1607. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1608. @staticmethod
  1609. def meshBakingClean(mesh):
  1610. for uvMap in mesh.data.uv_textures:
  1611. if uvMap.name == 'BakingUV':
  1612. mesh.data.uv_textures.remove(uvMap)
  1613. break
  1614. # remove an image if it was baked
  1615. for image in bpy.data.images:
  1616. if image.name == mesh.name + '_BJS_BAKE':
  1617. image.user_clear() # cannot remove image unless 0 references
  1618. bpy.data.images.remove(image)
  1619. break
  1620. #===============================================================================
  1621. class Animation:
  1622. def __init__(self, dataType, framePerSecond, loopBehavior, name, propertyInBabylon):
  1623. self.dataType = dataType
  1624. self.framePerSecond = framePerSecond
  1625. self.loopBehavior = loopBehavior
  1626. self.name = name
  1627. self.propertyInBabylon = propertyInBabylon
  1628. #keys
  1629. self.frames = []
  1630. self.values = [] # vector3 for ANIMATIONTYPE_VECTOR3 & matrices for ANIMATIONTYPE_MATRIX
  1631. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1632. # for auto animate
  1633. def get_first_frame(self):
  1634. return self.frames[0] if len(self.frames) > 0 else -1
  1635. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1636. # for auto animate
  1637. def get_last_frame(self):
  1638. return self.frames[len(self.frames) - 1] if len(self.frames) > 0 else -1
  1639. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1640. def to_scene_file(self, file_handler):
  1641. file_handler.write('{')
  1642. write_int(file_handler, 'dataType', self.dataType, True)
  1643. write_int(file_handler, 'framePerSecond', self.framePerSecond)
  1644. file_handler.write(',"keys":[')
  1645. first = True
  1646. for frame_idx in range(len(self.frames)):
  1647. if first != True:
  1648. file_handler.write(',')
  1649. first = False
  1650. file_handler.write('{')
  1651. write_int(file_handler, 'frame', self.frames[frame_idx], True)
  1652. value_idx = self.values[frame_idx]
  1653. if self.dataType == ANIMATIONTYPE_MATRIX:
  1654. write_matrix4(file_handler, 'values', value_idx)
  1655. elif self.dataType == ANIMATIONTYPE_QUATERNION:
  1656. write_quaternion(file_handler, 'values', value_idx)
  1657. else:
  1658. write_vector(file_handler, 'values', value_idx)
  1659. file_handler.write('}')
  1660. file_handler.write(']') # close keys
  1661. # put this at the end to make less crazy looking ]}]]]}}}}}}}]]]],
  1662. # since animation is also at the end of the bone, mesh, camera, or light
  1663. write_int(file_handler, 'loopBehavior', self.loopBehavior)
  1664. write_string(file_handler, 'name', self.name)
  1665. write_string(file_handler, 'property', self.propertyInBabylon)
  1666. file_handler.write('}')
  1667. #===============================================================================
  1668. class VectorAnimation(Animation):
  1669. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1670. super().__init__(ANIMATIONTYPE_VECTOR3, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1671. # capture built up from fcurves
  1672. frames = dict()
  1673. for fcurve in object.animation_data.action.fcurves:
  1674. if fcurve.data_path == attrInBlender:
  1675. for key in fcurve.keyframe_points:
  1676. frame = key.co.x
  1677. frames[frame] = 1
  1678. #for each frame (next step ==> set for key frames)
  1679. for Frame in sorted(frames):
  1680. self.frames.append(Frame)
  1681. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1682. self.values.append(scale_vector(getattr(object, attrInBlender), mult, xOffset))
  1683. #===============================================================================
  1684. class QuaternionAnimation(Animation):
  1685. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1686. super().__init__(ANIMATIONTYPE_QUATERNION, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1687. # capture built up from fcurves
  1688. frames = dict()
  1689. for fcurve in object.animation_data.action.fcurves:
  1690. if fcurve.data_path == attrInBlender:
  1691. for key in fcurve.keyframe_points:
  1692. frame = key.co.x
  1693. frames[frame] = 1
  1694. #for each frame (next step ==> set for key frames)
  1695. for Frame in sorted(frames):
  1696. self.frames.append(Frame)
  1697. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1698. self.values.append(post_rotate_quaternion(getattr(object, attrInBlender), xOffset))
  1699. #===============================================================================
  1700. class QuaternionToEulerAnimation(Animation):
  1701. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1702. super().__init__(ANIMATIONTYPE_VECTOR3, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1703. # capture built up from fcurves
  1704. frames = dict()
  1705. for fcurve in object.animation_data.action.fcurves:
  1706. if fcurve.data_path == attrInBlender:
  1707. for key in fcurve.keyframe_points:
  1708. frame = key.co.x
  1709. frames[frame] = 1
  1710. #for each frame (next step ==> set for key frames)
  1711. for Frame in sorted(frames):
  1712. self.frames.append(Frame)
  1713. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1714. quat = getattr(object, attrInBlender)
  1715. eul = quat.to_euler("XYZ")
  1716. self.values.append(scale_vector(eul, mult, xOffset))
  1717. #===============================================================================
  1718. # module level formatting methods, called from multiple classes
  1719. #===============================================================================
  1720. def legal_js_identifier(input):
  1721. out = ''
  1722. prefix = ''
  1723. for char in input:
  1724. if len(out) == 0:
  1725. if char in '0123456789':
  1726. # cannot take the chance that leading numbers being chopped of cause name conflicts, e.g (01.R & 02.R)
  1727. prefix += char
  1728. continue
  1729. elif char.upper() not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
  1730. continue
  1731. legal = char if char.upper() in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_' else '_'
  1732. out += legal
  1733. if len(prefix) > 0:
  1734. out += '_' + prefix
  1735. return out
  1736. def format_f(num):
  1737. s = MAX_FLOAT_PRECISION % num # rounds to N decimal places while changing to string
  1738. s = s.rstrip('0') # ignore trailing zeroes
  1739. s = s.rstrip('.') # ignore trailing .
  1740. return '0' if s == '-0' else s
  1741. def format_matrix4(matrix):
  1742. tempMatrix = matrix.copy()
  1743. tempMatrix.transpose()
  1744. ret = ''
  1745. first = True
  1746. for vect in tempMatrix:
  1747. if (first != True):
  1748. ret +=','
  1749. first = False;
  1750. ret += format_f(vect[0]) + ',' + format_f(vect[1]) + ',' + format_f(vect[2]) + ',' + format_f(vect[3])
  1751. return ret
  1752. def format_array3(array):
  1753. return format_f(array[0]) + ',' + format_f(array[1]) + ',' + format_f(array[2])
  1754. def format_array(array, max_per_line = MAX_VERTEX_ELEMENTS, indent = ''):
  1755. ret = ''
  1756. first = True
  1757. nOnLine = 0
  1758. for element in array:
  1759. if (first != True):
  1760. ret +=','
  1761. first = False;
  1762. ret += format_f(element)
  1763. nOnLine += 1
  1764. if nOnLine >= max_per_line:
  1765. ret += '\n' + indent
  1766. nOnLine = 0
  1767. return ret
  1768. def format_color(color):
  1769. return format_f(color.r) + ',' + format_f(color.g) + ',' + format_f(color.b)
  1770. def format_vector(vector):
  1771. return format_f(vector.x) + ',' + format_f(vector.z) + ',' + format_f(vector.y)
  1772. def format_vector_array(vectorArray, max_per_line = MAX_VERTEX_ELEMENTS, indent = ''):
  1773. ret = ''
  1774. first = True
  1775. nOnLine = 0
  1776. for vector in vectorArray:
  1777. if (first != True):
  1778. ret +=','
  1779. first = False;
  1780. ret += format_vector(vector)
  1781. nOnLine += 3
  1782. if nOnLine >= max_per_line:
  1783. ret += '\n' + indent
  1784. nOnLine = 0
  1785. return ret
  1786. def format_quaternion(quaternion):
  1787. return format_f(quaternion.x) + ',' + format_f(quaternion.z) + ',' + format_f(quaternion.y) + ',' + format_f(-quaternion.w)
  1788. def format_int(int):
  1789. candidate = str(int) # when int string of an int
  1790. if '.' in candidate:
  1791. return format_f(math.floor(int)) # format_f removes un-neccessary precision
  1792. else:
  1793. return candidate
  1794. def format_bool(bool):
  1795. if bool:
  1796. return 'true'
  1797. else:
  1798. return 'false'
  1799. def scale_vector(vector, mult, xOffset = 0):
  1800. ret = vector.copy()
  1801. ret.x *= mult
  1802. ret.x += xOffset
  1803. ret.z *= mult
  1804. ret.y *= mult
  1805. return ret
  1806. def same_vertex(vertA, vertB):
  1807. return vertA.x == vertB.x and vertA.y == vertB.y and vertA.z == vertB.z
  1808. #===============================================================================
  1809. # module level methods for writing JSON (.babylon) files
  1810. #===============================================================================
  1811. def write_matrix4(file_handler, name, matrix):
  1812. file_handler.write(',"' + name + '":[' + format_matrix4(matrix) + ']')
  1813. def write_array(file_handler, name, array):
  1814. file_handler.write('\n,"' + name + '":[' + format_array(array) + ']')
  1815. def write_array3(file_handler, name, array):
  1816. file_handler.write(',"' + name + '":[' + format_array3(array) + ']')
  1817. def write_color(file_handler, name, color):
  1818. file_handler.write(',"' + name + '":[' + format_color(color) + ']')
  1819. def write_vector(file_handler, name, vector):
  1820. file_handler.write(',"' + name + '":[' + format_vector(vector) + ']')
  1821. def write_vector_array(file_handler, name, vectorArray):
  1822. file_handler.write('\n,"' + name + '":[' + format_vector_array(vectorArray) + ']')
  1823. def write_quaternion(file_handler, name, quaternion):
  1824. file_handler.write(',"' + name +'":[' + format_quaternion(quaternion) + ']')
  1825. def write_string(file_handler, name, string, noComma = False):
  1826. if noComma == False:
  1827. file_handler.write(',')
  1828. file_handler.write('"' + name + '":"' + string + '"')
  1829. def write_float(file_handler, name, float):
  1830. file_handler.write(',"' + name + '":' + format_f(float))
  1831. def write_int(file_handler, name, int, noComma = False):
  1832. if noComma == False:
  1833. file_handler.write(',')
  1834. file_handler.write('"' + name + '":' + format_int(int))
  1835. def write_bool(file_handler, name, bool, noComma = False):
  1836. if noComma == False:
  1837. file_handler.write(',')
  1838. file_handler.write('"' + name + '":' + format_bool(bool))
  1839. #===============================================================================
  1840. # custom properties definition and display
  1841. #===============================================================================
  1842. bpy.types.Mesh.autoAnimate = bpy.props.BoolProperty(
  1843. name='Auto launch animations',
  1844. description='',
  1845. default = False
  1846. )
  1847. bpy.types.Mesh.useFlatShading = bpy.props.BoolProperty(
  1848. name='Use Flat Shading',
  1849. description='',
  1850. default = False
  1851. )
  1852. bpy.types.Mesh.checkCollisions = bpy.props.BoolProperty(
  1853. name='Check Collisions',
  1854. description='Indicates mesh should be checked that it does not run into anything.',
  1855. default = False
  1856. )
  1857. bpy.types.Mesh.castShadows = bpy.props.BoolProperty(
  1858. name='Cast Shadows',
  1859. description='',
  1860. default = False
  1861. )
  1862. bpy.types.Mesh.receiveShadows = bpy.props.BoolProperty(
  1863. name='Receive Shadows',
  1864. description='',
  1865. default = False
  1866. )
  1867. bpy.types.Mesh.bakeSize = bpy.props.IntProperty(
  1868. name='Texture Size',
  1869. description='',
  1870. default = 1024
  1871. )
  1872. bpy.types.Mesh.bakeQuality = bpy.props.IntProperty(
  1873. name='Quality 1-100',
  1874. description='The trade-off between Quality - File size(100 highest quality)',
  1875. default = 50
  1876. )
  1877. bpy.types.Mesh.freezeWorldMatrix = bpy.props.BoolProperty(
  1878. name='Freeze World Matrix',
  1879. description='Indicate the position, rotation, & scale do not change for performance reasons',
  1880. default = False
  1881. )
  1882. bpy.types.Mesh.attachedSound = bpy.props.StringProperty(
  1883. name='Sound',
  1884. description='',
  1885. default = ''
  1886. )
  1887. bpy.types.Mesh.loopSound = bpy.props.BoolProperty(
  1888. name='Loop sound',
  1889. description='',
  1890. default = True
  1891. )
  1892. bpy.types.Mesh.autoPlaySound = bpy.props.BoolProperty(
  1893. name='Auto play sound',
  1894. description='',
  1895. default = True
  1896. )
  1897. bpy.types.Mesh.maxSoundDistance = bpy.props.FloatProperty(
  1898. name='Max sound distance',
  1899. description='',
  1900. default = 100
  1901. )
  1902. #===============================================================================
  1903. bpy.types.Camera.autoAnimate = bpy.props.BoolProperty(
  1904. name='Auto launch animations',
  1905. description='',
  1906. default = False
  1907. )
  1908. bpy.types.Camera.CameraType = bpy.props.EnumProperty(
  1909. name='Camera Type',
  1910. description='',
  1911. # ONLY Append, or existing .blends will have their camera changed
  1912. items = (
  1913. (V_JOYSTICKS_CAM , 'Virtual Joysticks' , 'Use Virtual Joysticks Camera'),
  1914. (TOUCH_CAM , 'Touch' , 'Use Touch Camera'),
  1915. (GAMEPAD_CAM , 'Gamepad' , 'Use Gamepad Camera'),
  1916. (FREE_CAM , 'Free' , 'Use Free Camera'),
  1917. (FOLLOW_CAM , 'Follow' , 'Use Follow Camera'),
  1918. (DEV_ORIENT_CAM , 'Device Orientation' , 'Use Device Orientation Camera'),
  1919. (ARC_ROTATE_CAM , 'Arc Rotate' , 'Use Arc Rotate Camera'),
  1920. (VR_DEV_ORIENT_FREE_CAM , 'VR Dev Orientation Free' , 'Use VR Dev Orientation Free Camera'),
  1921. (WEB_VR_FREE_CAM , 'Web VR Free' , 'Use Web VR Free Camera')
  1922. ),
  1923. default = FREE_CAM
  1924. )
  1925. bpy.types.Camera.checkCollisions = bpy.props.BoolProperty(
  1926. name='Check Collisions',
  1927. description='',
  1928. default = False
  1929. )
  1930. bpy.types.Camera.applyGravity = bpy.props.BoolProperty(
  1931. name='Apply Gravity',
  1932. description='',
  1933. default = False
  1934. )
  1935. bpy.types.Camera.ellipsoid = bpy.props.FloatVectorProperty(
  1936. name='Ellipsoid',
  1937. description='',
  1938. default = mathutils.Vector((0.2, 0.9, 0.2))
  1939. )
  1940. bpy.types.Camera.Camera3DRig = bpy.props.EnumProperty(
  1941. name='Rig',
  1942. description='',
  1943. items = (
  1944. (RIG_MODE_NONE , 'None' , 'No 3D effects'),
  1945. (RIG_MODE_STEREOSCOPIC_ANAGLYPH , 'Anaaglph' , 'Stereoscopic Anagylph'),
  1946. (RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL , 'side-by-side Parallel' , 'Stereoscopic side-by-side parallel'),
  1947. (RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED, 'side-by-side crosseyed', 'Stereoscopic side-by-side crosseyed'),
  1948. (RIG_MODE_STEREOSCOPIC_OVERUNDER , 'over-under' , 'Stereoscopic over-under'),
  1949. (RIG_MODE_VR , 'VR distortion' , 'Use Web VR Free Camera')
  1950. ),
  1951. default = RIG_MODE_NONE
  1952. )
  1953. bpy.types.Camera.interaxialDistance = bpy.props.FloatProperty(
  1954. name='Interaxial Distance',
  1955. description='Distance between cameras. Used by all but VR 3D rigs.',
  1956. default = 0.0637
  1957. )
  1958. #===============================================================================
  1959. bpy.types.Lamp.autoAnimate = bpy.props.BoolProperty(
  1960. name='Auto launch animations',
  1961. description='',
  1962. default = False
  1963. )
  1964. bpy.types.Lamp.shadowMap = bpy.props.EnumProperty(
  1965. name='Shadow Map',
  1966. description='',
  1967. items = ((NO_SHADOWS , 'None' , 'No Shadow Maps'),
  1968. (STD_SHADOWS , 'Standard' , 'Use Standard Shadow Maps'),
  1969. (POISSON_SHADOWS , 'Poisson' , 'Use Poisson Sampling'),
  1970. (VARIANCE_SHADOWS , 'Variance' , 'Use Variance Shadow Maps'),
  1971. (BLUR_VARIANCE_SHADOWS, 'Blur Variance', 'Use Blur Variance Shadow Maps')
  1972. ),
  1973. default = NO_SHADOWS
  1974. )
  1975. bpy.types.Lamp.shadowMapSize = bpy.props.IntProperty(
  1976. name='Shadow Map Size',
  1977. description='',
  1978. default = 512
  1979. )
  1980. bpy.types.Lamp.shadowBias = bpy.props.FloatProperty(
  1981. name='Shadow Bias',
  1982. description='',
  1983. default = 0.00005
  1984. )
  1985. bpy.types.Lamp.shadowBlurScale = bpy.props.IntProperty(
  1986. name='Blur Scale',
  1987. description='',
  1988. default = 2
  1989. )
  1990. bpy.types.Lamp.shadowBlurBoxOffset = bpy.props.IntProperty(
  1991. name='Blur Box Offset',
  1992. description='',
  1993. default = 0
  1994. )
  1995. class ObjectPanel(bpy.types.Panel):
  1996. bl_label = 'Babylon.js'
  1997. bl_space_type = 'PROPERTIES'
  1998. bl_region_type = 'WINDOW'
  1999. bl_context = 'data'
  2000. def draw(self, context):
  2001. ob = context.object
  2002. if not ob or not ob.data:
  2003. return
  2004. layout = self.layout
  2005. isMesh = isinstance(ob.data, bpy.types.Mesh)
  2006. isCamera = isinstance(ob.data, bpy.types.Camera)
  2007. isLight = isinstance(ob.data, bpy.types.Lamp)
  2008. if isMesh:
  2009. layout.prop(ob.data, 'useFlatShading')
  2010. layout.prop(ob.data, 'checkCollisions')
  2011. layout.prop(ob.data, 'castShadows')
  2012. layout.prop(ob.data, 'receiveShadows')
  2013. layout.separator()
  2014. layout.prop(ob.data, 'autoAnimate')
  2015. box = layout.box()
  2016. box.label(text="Procedural Texture / Cycles Baking")
  2017. box.prop(ob.data, 'bakeSize')
  2018. box.prop(ob.data, 'bakeQuality')
  2019. layout.prop(ob.data, 'freezeWorldMatrix')
  2020. box = layout.box()
  2021. box.prop(ob.data, 'attachedSound')
  2022. box.prop(ob.data, 'autoPlaySound')
  2023. box.prop(ob.data, 'loopSound')
  2024. box.prop(ob.data, 'maxSoundDistance')
  2025. elif isCamera:
  2026. layout.prop(ob.data, 'CameraType')
  2027. layout.prop(ob.data, 'checkCollisions')
  2028. layout.prop(ob.data, 'applyGravity')
  2029. layout.prop(ob.data, 'ellipsoid')
  2030. box = layout.box()
  2031. box.label(text="3D Camera Rigs")
  2032. box.prop(ob.data, 'Camera3DRig')
  2033. box.prop(ob.data, 'interaxialDistance')
  2034. layout.prop(ob.data, 'autoAnimate')
  2035. elif isLight:
  2036. layout.prop(ob.data, 'shadowMap')
  2037. layout.prop(ob.data, 'shadowMapSize')
  2038. layout.prop(ob.data, 'shadowBias')
  2039. box = layout.box()
  2040. box.label(text="Blur Variance Shadows")
  2041. box.prop(ob.data, 'shadowBlurScale')
  2042. box.prop(ob.data, 'shadowBlurBoxOffset')
  2043. layout.prop(ob.data, 'autoAnimate')