io_export_babylon.py 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403
  1. bl_info = {
  2. 'name': 'Babylon.js',
  3. 'author': 'David Catuhe, Jeff Palmer',
  4. 'version': (3, 0, 3),
  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. else:
  601. bakedMat = BakedMaterial(exporter, object, recipe)
  602. exporter.materials.append(bakedMat)
  603. self.materialId = bakedMat.name
  604. else:
  605. bjs_material_slots = []
  606. for slot in object.material_slots:
  607. # None will be returned when either the first encounter or must be unique due to baked textures
  608. material = exporter.getMaterial(slot.name)
  609. if (material != None):
  610. material.numOfUsers = material.numOfUsers + 1
  611. Main.log('registered as also a user of material: ' + slot.name, 2)
  612. else:
  613. material = StdMaterial(slot, exporter, object)
  614. exporter.materials.append(material)
  615. bjs_material_slots.append(material)
  616. if len(bjs_material_slots) == 1:
  617. self.materialId = bjs_material_slots[0].name
  618. elif len(bjs_material_slots) > 1:
  619. multimat = MultiMaterial(bjs_material_slots, len(exporter.multiMaterials))
  620. self.materialId = multimat.name
  621. exporter.multiMaterials.append(multimat)
  622. maxVerts = MAX_VERTEX_ELEMENTS_32Bit
  623. else:
  624. Main.warn('No materials have been assigned: ', 2)
  625. # Get mesh
  626. mesh = object.to_mesh(scene, True, 'PREVIEW')
  627. # Triangulate mesh if required
  628. Mesh.mesh_triangulate(mesh)
  629. # Getting vertices and indices
  630. self.positions = []
  631. self.normals = []
  632. self.uvs = [] # not always used
  633. self.uvs2 = [] # not always used
  634. self.colors = [] # not always used
  635. self.indices = []
  636. self.subMeshes = []
  637. hasUV = len(mesh.tessface_uv_textures) > 0
  638. if hasUV:
  639. which = len(mesh.tessface_uv_textures) - 1 if recipe.needsBaking else 0
  640. UVmap = mesh.tessface_uv_textures[which].data
  641. hasUV2 = len(mesh.tessface_uv_textures) > 1 and not recipe.needsBaking
  642. if hasUV2:
  643. UV2map = mesh.tessface_uv_textures[1].data
  644. hasVertexColor = len(mesh.vertex_colors) > 0
  645. if hasVertexColor:
  646. Colormap = mesh.tessface_vertex_colors.active.data
  647. if hasSkeleton:
  648. self.skeletonWeights = []
  649. self.skeletonIndicesCompressed = []
  650. # used tracking of vertices as they are received
  651. alreadySavedVertices = []
  652. vertices_UVs = []
  653. vertices_UV2s = []
  654. vertices_Colors = []
  655. vertices_indices = []
  656. self.offsetFace = 0
  657. for v in range(0, len(mesh.vertices)):
  658. alreadySavedVertices.append(False)
  659. vertices_UVs.append([])
  660. vertices_UV2s.append([])
  661. vertices_Colors.append([])
  662. vertices_indices.append([])
  663. materialsCount = 1 if recipe.needsBaking else max(1, len(object.material_slots))
  664. verticesCount = 0
  665. indicesCount = 0
  666. maxInfluencersExceeded = 0
  667. for materialIndex in range(materialsCount):
  668. if self.offsetFace != 0:
  669. break
  670. subMeshVerticesStart = verticesCount
  671. subMeshIndexStart = indicesCount
  672. for faceIndex in range(startFace, len(mesh.tessfaces)): # For each face
  673. face = mesh.tessfaces[faceIndex]
  674. if face.material_index != materialIndex and not recipe.needsBaking:
  675. continue
  676. if verticesCount + 3 > maxVerts:
  677. self.offsetFace = faceIndex
  678. break
  679. for v in range(3): # For each vertex in face
  680. vertex_index = face.vertices[v]
  681. vertex = mesh.vertices[vertex_index]
  682. position = vertex.co
  683. normal = vertex.normal
  684. #skeletons
  685. if hasSkeleton:
  686. matricesWeights = []
  687. matricesWeights.append(0.0)
  688. matricesWeights.append(0.0)
  689. matricesWeights.append(0.0)
  690. matricesWeights.append(0.0)
  691. matricesIndicesCompressed = 0
  692. # Getting influences
  693. i = 0
  694. offset = 0
  695. for group in vertex.groups:
  696. index = group.group
  697. weight = group.weight
  698. for boneIndex, bone in enumerate(objArmature.pose.bones):
  699. if object.vertex_groups[index].name == bone.name:
  700. if (i == MAX_INFLUENCERS_PER_VERTEX):
  701. maxInfluencersExceeded += 1
  702. break
  703. matricesWeights[i] = weight
  704. matricesIndicesCompressed += boneIndex << offset
  705. offset = offset + 8
  706. i = i + 1
  707. # Texture coordinates
  708. if hasUV:
  709. vertex_UV = UVmap[face.index].uv[v]
  710. if hasUV2:
  711. vertex_UV2 = UV2map[face.index].uv[v]
  712. # Vertex color
  713. if hasVertexColor:
  714. if v == 0:
  715. vertex_Color = Colormap[face.index].color1
  716. if v == 1:
  717. vertex_Color = Colormap[face.index].color2
  718. if v == 2:
  719. vertex_Color = Colormap[face.index].color3
  720. # Check if the current vertex is already saved
  721. alreadySaved = alreadySavedVertices[vertex_index] and not (hasSkeleton or scene.export_noVertexOpt)
  722. if alreadySaved:
  723. alreadySaved = False
  724. # UV
  725. index_UV = 0
  726. for savedIndex in vertices_indices[vertex_index]:
  727. if hasUV:
  728. vUV = vertices_UVs[vertex_index][index_UV]
  729. if (vUV[0] != vertex_UV[0] or vUV[1] != vertex_UV[1]):
  730. continue
  731. if hasUV2:
  732. vUV2 = vertices_UV2s[vertex_index][index_UV]
  733. if (vUV2[0] != vertex_UV2[0] or vUV2[1] != vertex_UV2[1]):
  734. continue
  735. if hasVertexColor:
  736. vColor = vertices_Colors[vertex_index][index_UV]
  737. if (vColor.r != vertex_Color.r or vColor.g != vertex_Color.g or vColor.b != vertex_Color.b):
  738. continue
  739. if vertices_indices[vertex_index][index_UV] >= subMeshVerticesStart:
  740. alreadySaved = True
  741. break
  742. index_UV += 1
  743. if (alreadySaved):
  744. # Reuse vertex
  745. index = vertices_indices[vertex_index][index_UV]
  746. else:
  747. # Export new one
  748. index = verticesCount
  749. alreadySavedVertices[vertex_index] = True
  750. if hasUV:
  751. vertices_UVs[vertex_index].append(vertex_UV)
  752. self.uvs.append(vertex_UV[0])
  753. self.uvs.append(vertex_UV[1])
  754. if hasUV2:
  755. vertices_UV2s[vertex_index].append(vertex_UV2)
  756. self.uvs2.append(vertex_UV2[0])
  757. self.uvs2.append(vertex_UV2[1])
  758. if hasVertexColor:
  759. vertices_Colors[vertex_index].append(vertex_Color)
  760. self.colors.append(vertex_Color.r)
  761. self.colors.append(vertex_Color.g)
  762. self.colors.append(vertex_Color.b)
  763. self.colors.append(1.0)
  764. if hasSkeleton:
  765. self.skeletonWeights.append(matricesWeights[0])
  766. self.skeletonWeights.append(matricesWeights[1])
  767. self.skeletonWeights.append(matricesWeights[2])
  768. self.skeletonWeights.append(matricesWeights[3])
  769. self.skeletonIndicesCompressed.append(matricesIndicesCompressed)
  770. vertices_indices[vertex_index].append(index)
  771. self.positions.append(position)
  772. self.normals.append(normal)
  773. verticesCount += 1
  774. self.indices.append(index)
  775. indicesCount += 1
  776. self.subMeshes.append(SubMesh(materialIndex, subMeshVerticesStart, subMeshIndexStart, verticesCount - subMeshVerticesStart, indicesCount - subMeshIndexStart))
  777. if verticesCount > MAX_VERTEX_ELEMENTS:
  778. warn('Due to multi-materials & this meshes size, 32bit indices must be used. This may not run on all hardware.', 2)
  779. if maxInfluencersExceeded > 0:
  780. Main.warn('Maximum # of influencers exceeded for ' + format_int(maxInfluencersExceeded) + ' vertices, extras ignored', 2)
  781. BakedMaterial.meshBakingClean(object)
  782. Main.log('num positions : ' + str(len(self.positions)), 2)
  783. Main.log('num normals : ' + str(len(self.normals )), 2)
  784. Main.log('num uvs : ' + str(len(self.uvs )), 2)
  785. Main.log('num uvs2 : ' + str(len(self.uvs2 )), 2)
  786. Main.log('num colors : ' + str(len(self.colors )), 2)
  787. Main.log('num indices : ' + str(len(self.indices )), 2)
  788. if hasattr(self, 'skeletonWeights'):
  789. Main.log('num skeletonWeights: ' + str(len(self.skeletonWeights)), 2)
  790. Main.log('num skeletonIndices: ' + str(len(self.skeletonIndicesCompressed * 4)), 2)
  791. numZeroAreaFaces = self.find_zero_area_faces()
  792. if numZeroAreaFaces > 0:
  793. Main.warn('# of 0 area faces found: ' + str(numZeroAreaFaces), 2)
  794. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  795. def find_zero_area_faces(self):
  796. nFaces = int(len(self.indices) / 3)
  797. nZeroAreaFaces = 0
  798. for f in range(0, nFaces):
  799. faceOffset = f * 3
  800. p1 = self.positions[self.indices[faceOffset ]]
  801. p2 = self.positions[self.indices[faceOffset + 1]]
  802. p3 = self.positions[self.indices[faceOffset + 2]]
  803. if same_vertex(p1, p2) or same_vertex(p1, p3) or same_vertex(p2, p3): nZeroAreaFaces += 1
  804. return nZeroAreaFaces
  805. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  806. @staticmethod
  807. def mesh_triangulate(mesh):
  808. try:
  809. import bmesh
  810. bm = bmesh.new()
  811. bm.from_mesh(mesh)
  812. bmesh.ops.triangulate(bm, faces = bm.faces)
  813. bm.to_mesh(mesh)
  814. mesh.calc_tessface()
  815. bm.free()
  816. except:
  817. pass
  818. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  819. def to_scene_file(self, file_handler):
  820. file_handler.write('{')
  821. write_string(file_handler, 'name', self.name, True)
  822. write_string(file_handler, 'id', self.name)
  823. if hasattr(self, 'parentId'): write_string(file_handler, 'parentId', self.parentId)
  824. if hasattr(self, 'materialId'): write_string(file_handler, 'materialId', self.materialId)
  825. write_int(file_handler, 'billboardMode', self.billboardMode)
  826. write_vector(file_handler, 'position', self.position)
  827. if hasattr(self, "rotationQuaternion"):
  828. write_quaternion(file_handler, 'rotationQuaternion', self.rotationQuaternion)
  829. else:
  830. write_vector(file_handler, 'rotation', self.rotation)
  831. write_vector(file_handler, 'scaling', self.scaling)
  832. write_bool(file_handler, 'isVisible', self.isVisible)
  833. write_bool(file_handler, 'freezeWorldMatrix', self.freezeWorldMatrix)
  834. write_bool(file_handler, 'isEnabled', self.isEnabled)
  835. write_bool(file_handler, 'useFlatShading', self.useFlatShading)
  836. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  837. write_bool(file_handler, 'receiveShadows', self.receiveShadows)
  838. if hasattr(self, 'physicsImpostor'):
  839. write_int(file_handler, 'physicsImpostor', self.physicsImpostor)
  840. write_float(file_handler, 'physicsMass', self.physicsMass)
  841. write_float(file_handler, 'physicsFriction', self.physicsFriction)
  842. write_float(file_handler, 'physicsRestitution', self.physicsRestitution)
  843. # Geometry
  844. if hasattr(self, 'skeletonId'): write_int(file_handler, 'skeletonId', self.skeletonId)
  845. write_vector_array(file_handler, 'positions', self.positions)
  846. write_vector_array(file_handler, 'normals' , self.normals )
  847. if len(self.uvs) > 0:
  848. write_array(file_handler, 'uvs', self.uvs)
  849. if len(self.uvs2) > 0:
  850. write_array(file_handler, 'uvs2', self.uvs2)
  851. if len(self.colors) > 0:
  852. write_array(file_handler, 'colors', self.colors)
  853. if hasattr(self, 'skeletonWeights'):
  854. write_array(file_handler, 'matricesWeights', self.skeletonWeights)
  855. write_array(file_handler, 'matricesIndices', self.skeletonIndicesCompressed)
  856. write_array(file_handler, 'indices', self.indices)
  857. # Sub meshes
  858. file_handler.write('\n,"subMeshes":[')
  859. first = True
  860. for subMesh in self.subMeshes:
  861. if first == False:
  862. file_handler.write(',')
  863. subMesh.to_scene_file(file_handler)
  864. first = False
  865. file_handler.write(']')
  866. super().to_scene_file(file_handler) # Animations
  867. # Instances
  868. first = True
  869. file_handler.write('\n,"instances":[')
  870. for instance in self.instances:
  871. if first == False:
  872. file_handler.write(',')
  873. instance.to_scene_file(file_handler)
  874. first = False
  875. file_handler.write(']')
  876. # Close mesh
  877. file_handler.write('}\n')
  878. self.alreadyExported = True
  879. #===============================================================================
  880. class MeshInstance:
  881. def __init__(self, name, position, rotation, rotationQuaternion, scaling, freezeWorldMatrix):
  882. self.name = name
  883. self.position = position
  884. if rotation is not None:
  885. self.rotation = rotation
  886. if rotationQuaternion is not None:
  887. self.rotationQuaternion = rotationQuaternion
  888. self.scaling = scaling
  889. self.freezeWorldMatrix = freezeWorldMatrix
  890. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  891. def to_scene_file(self, file_handler):
  892. file_handler.write('{')
  893. write_string(file_handler, 'name', self.name, True)
  894. write_vector(file_handler, 'position', self.position)
  895. if hasattr(self, 'rotation'):
  896. write_vector(file_handler, 'rotation', self.rotation)
  897. else:
  898. write_quaternion(file_handler, 'rotationQuaternion', self.rotationQuaternion)
  899. write_vector(file_handler, 'scaling', self.scaling)
  900. # freeze World Matrix currently ignored for instances
  901. write_bool(file_handler, 'freezeWorldMatrix', self.freezeWorldMatrix)
  902. file_handler.write('}')
  903. #===============================================================================
  904. class Node(FCurveAnimatable):
  905. def __init__(self, node):
  906. super().__init__(node, True, True, True) #Should animations be done when forcedParent
  907. Main.log('processing begun of node: ' + node.name)
  908. self.name = node.name
  909. if node.parent and node.parent.type != 'ARMATURE':
  910. self.parentId = node.parent.name
  911. loc, rot, scale = node.matrix_local.decompose()
  912. self.position = loc
  913. if node.rotation_mode == 'QUATERNION':
  914. self.rotationQuaternion = rot
  915. else:
  916. self.rotation = scale_vector(rot.to_euler('XYZ'), -1)
  917. self.scaling = scale
  918. self.isVisible = False
  919. self.isEnabled = True
  920. self.checkCollisions = False
  921. self.billboardMode = BILLBOARDMODE_NONE
  922. self.castShadows = False
  923. self.receiveShadows = False
  924. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  925. def to_scene_file(self, file_handler, ignored):
  926. file_handler.write('{')
  927. write_string(file_handler, 'name', self.name, True)
  928. write_string(file_handler, 'id', self.name)
  929. if hasattr(self, 'parentId'): write_string(file_handler, 'parentId', self.parentId)
  930. write_vector(file_handler, 'position', self.position)
  931. if hasattr(self, "rotationQuaternion"):
  932. write_quaternion(file_handler, "rotationQuaternion", self.rotationQuaternion)
  933. else:
  934. write_vector(file_handler, 'rotation', self.rotation)
  935. write_vector(file_handler, 'scaling', self.scaling)
  936. write_bool(file_handler, 'isVisible', self.isVisible)
  937. write_bool(file_handler, 'isEnabled', self.isEnabled)
  938. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  939. write_int(file_handler, 'billboardMode', self.billboardMode)
  940. write_bool(file_handler, 'receiveShadows', self.receiveShadows)
  941. super().to_scene_file(file_handler) # Animations
  942. file_handler.write('}')
  943. #===============================================================================
  944. class SubMesh:
  945. def __init__(self, materialIndex, verticesStart, indexStart, verticesCount, indexCount):
  946. self.materialIndex = materialIndex
  947. self.verticesStart = verticesStart
  948. self.indexStart = indexStart
  949. self.verticesCount = verticesCount
  950. self.indexCount = indexCount
  951. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  952. def to_scene_file(self, file_handler):
  953. file_handler.write('{')
  954. write_int(file_handler, 'materialIndex', self.materialIndex, True)
  955. write_int(file_handler, 'verticesStart', self.verticesStart)
  956. write_int(file_handler, 'verticesCount', self.verticesCount)
  957. write_int(file_handler, 'indexStart' , self.indexStart)
  958. write_int(file_handler, 'indexCount' , self.indexCount)
  959. file_handler.write('}')
  960. #===============================================================================
  961. class Bone:
  962. def __init__(self, bone, skeleton, scene, index):
  963. Main.log('processing begun of bone: ' + bone.name + ', index: '+ str(index))
  964. self.name = bone.name
  965. self.index = index
  966. matrix_world = skeleton.matrix_world
  967. self.matrix = Bone.get_matrix(bone, matrix_world)
  968. parentId = -1
  969. if (bone.parent):
  970. for parent in skeleton.pose.bones:
  971. parentId += 1
  972. if parent == bone.parent:
  973. break;
  974. self.parentBoneIndex = parentId
  975. #animation
  976. if (skeleton.animation_data):
  977. Main.log('animation begun of bone: ' + self.name)
  978. self.animation = Animation(ANIMATIONTYPE_MATRIX, scene.render.fps, ANIMATIONLOOPMODE_CYCLE, 'anim', '_matrix')
  979. start_frame = scene.frame_start
  980. end_frame = scene.frame_end
  981. previousBoneMatrix = None
  982. for frame in range(start_frame, end_frame + 1):
  983. bpy.context.scene.frame_set(frame)
  984. currentBoneMatrix = Bone.get_matrix(bone, matrix_world)
  985. if (frame != end_frame and currentBoneMatrix == previousBoneMatrix):
  986. continue
  987. self.animation.frames.append(frame)
  988. self.animation.values.append(Bone.get_matrix(bone, matrix_world))
  989. previousBoneMatrix = currentBoneMatrix
  990. bpy.context.scene.frame_set(start_frame)
  991. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  992. @staticmethod
  993. def get_matrix(bone, matrix_world):
  994. SystemMatrix = mathutils.Matrix.Scale(-1, 4, mathutils.Vector((0, 0, 1))) * mathutils.Matrix.Rotation(math.radians(-90), 4, 'X')
  995. if (bone.parent):
  996. return (SystemMatrix * matrix_world * bone.parent.matrix).inverted() * (SystemMatrix * matrix_world * bone.matrix)
  997. else:
  998. return SystemMatrix * matrix_world * bone.matrix
  999. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1000. def to_scene_file(self, file_handler):
  1001. file_handler.write('\n{')
  1002. write_string(file_handler, 'name', self.name, True)
  1003. write_int(file_handler, 'index', self.index)
  1004. write_matrix4(file_handler, 'matrix', self.matrix)
  1005. write_int(file_handler, 'parentBoneIndex', self.parentBoneIndex)
  1006. #animation
  1007. if hasattr(self, 'animation'):
  1008. file_handler.write(',"animation":')
  1009. self.animation.to_scene_file(file_handler)
  1010. file_handler.write('}')
  1011. #===============================================================================
  1012. class Skeleton:
  1013. def __init__(self, skeleton, scene, id):
  1014. Main.log('processing begun of skeleton: ' + skeleton.name + ', id: '+ str(id))
  1015. self.name = skeleton.name
  1016. self.id = id
  1017. self.bones = []
  1018. bones = skeleton.pose.bones
  1019. j = 0
  1020. for bone in bones:
  1021. self.bones.append(Bone(bone, skeleton, scene, j))
  1022. j = j + 1
  1023. Main.log('processing complete of skeleton: ' + skeleton.name)
  1024. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1025. def to_scene_file(self, file_handler):
  1026. file_handler.write('{')
  1027. write_string(file_handler, 'name', self.name, True)
  1028. write_int(file_handler, 'id', self.id) # keep int for legacy of original exporter
  1029. file_handler.write(',"bones":[')
  1030. first = True
  1031. for bone in self.bones:
  1032. if first != True:
  1033. file_handler.write(',')
  1034. first = False
  1035. bone.to_scene_file(file_handler)
  1036. file_handler.write(']')
  1037. file_handler.write('}')
  1038. #===============================================================================
  1039. class Camera(FCurveAnimatable):
  1040. def __init__(self, camera):
  1041. super().__init__(camera, True, True, False, math.pi / 2)
  1042. if camera.parent and camera.parent.type != 'ARMATURE':
  1043. self.parentId = camera.parent.name
  1044. self.CameraType = camera.data.CameraType
  1045. self.name = camera.name
  1046. Main.log('processing begun of camera (' + self.CameraType + '): ' + self.name)
  1047. self.position = camera.location
  1048. # for quaternions, convert to euler XYZ, otherwise, use the default rotation_euler
  1049. eul = camera.rotation_quaternion.to_euler("XYZ") if camera.rotation_mode == 'QUATERNION' else camera.rotation_euler
  1050. self.rotation = mathutils.Vector((-eul[0] + math.pi / 2, eul[1], -eul[2]))
  1051. self.fov = camera.data.angle
  1052. self.minZ = camera.data.clip_start
  1053. self.maxZ = camera.data.clip_end
  1054. self.speed = 1.0
  1055. self.inertia = 0.9
  1056. self.checkCollisions = camera.data.checkCollisions
  1057. self.applyGravity = camera.data.applyGravity
  1058. self.ellipsoid = camera.data.ellipsoid
  1059. self.Camera3DRig = camera.data.Camera3DRig
  1060. self.interaxialDistance = camera.data.interaxialDistance
  1061. for constraint in camera.constraints:
  1062. if constraint.type == 'TRACK_TO':
  1063. self.lockedTargetId = constraint.target.name
  1064. break
  1065. if self.CameraType == ARC_ROTATE_CAM or self.CameraType == FOLLOW_CAM:
  1066. if not hasattr(self, 'lockedTargetId'):
  1067. Main.warn('Camera type with manditory target specified, but no target to track set. Ignored', 2)
  1068. self.fatalProblem = True
  1069. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1070. def update_for_target_attributes(self, meshesAndNodes):
  1071. if not hasattr(self, 'lockedTargetId'): return
  1072. # find the actual mesh tracking, so properties can be derrived
  1073. targetFound = False
  1074. for mesh in meshesAndNodes:
  1075. if mesh.name == self.lockedTargetId:
  1076. targetMesh = mesh
  1077. targetFound = True
  1078. break;
  1079. xApart = 3 if not targetFound else self.position.x - targetMesh.position.x
  1080. yApart = 3 if not targetFound else self.position.y - targetMesh.position.y
  1081. zApart = 3 if not targetFound else self.position.z - targetMesh.position.z
  1082. distance3D = math.sqrt(xApart * xApart + yApart * yApart + zApart * zApart)
  1083. alpha = math.atan2(yApart, xApart);
  1084. beta = math.atan2(yApart, zApart);
  1085. if self.CameraType == FOLLOW_CAM:
  1086. self.followHeight = zApart
  1087. self.followDistance = distance3D
  1088. self.followRotation = 90 + (alpha * 180 / math.pi)
  1089. elif self.CameraType == self.CameraType == ARC_ROTATE_CAM:
  1090. self.arcRotAlpha = alpha
  1091. self.arcRotBeta = beta
  1092. self.arcRotRadius = distance3D
  1093. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1094. def to_scene_file(self, file_handler):
  1095. file_handler.write('{')
  1096. write_string(file_handler, 'name', self.name, True)
  1097. write_string(file_handler, 'id', self.name)
  1098. write_vector(file_handler, 'position', self.position)
  1099. write_vector(file_handler, 'rotation', self.rotation)
  1100. write_float(file_handler, 'fov', self.fov)
  1101. write_float(file_handler, 'minZ', self.minZ)
  1102. write_float(file_handler, 'maxZ', self.maxZ)
  1103. write_float(file_handler, 'speed', self.speed)
  1104. write_float(file_handler, 'inertia', self.inertia)
  1105. write_bool(file_handler, 'checkCollisions', self.checkCollisions)
  1106. write_bool(file_handler, 'applyGravity', self.applyGravity)
  1107. write_array3(file_handler, 'ellipsoid', self.ellipsoid)
  1108. # always assign rig, even when none, Reason: Could have VR camera with different Rig than default
  1109. write_int(file_handler, 'cameraRigMode', self.Camera3DRig)
  1110. write_float(file_handler, 'interaxial_distance', self.interaxialDistance)
  1111. write_string(file_handler, 'type', self.CameraType)
  1112. if hasattr(self, 'parentId'): write_string(file_handler, 'parentId', self.parentId)
  1113. if self.CameraType == FOLLOW_CAM:
  1114. write_float(file_handler, 'heightOffset', self.followHeight)
  1115. write_float(file_handler, 'radius', self.followDistance)
  1116. write_float(file_handler, 'rotationOffset', self.followRotation)
  1117. elif self.CameraType == ARC_ROTATE_CAM:
  1118. write_float(file_handler, 'alpha', self.arcRotAlpha)
  1119. write_float(file_handler, 'beta', self.arcRotBeta)
  1120. write_float(file_handler, 'radius', self.arcRotRadius)
  1121. if hasattr(self, 'lockedTargetId'):
  1122. write_string(file_handler, 'lockedTargetId', self.lockedTargetId)
  1123. super().to_scene_file(file_handler) # Animations
  1124. file_handler.write('}')
  1125. #===============================================================================
  1126. class Light(FCurveAnimatable):
  1127. def __init__(self, light):
  1128. super().__init__(light, False, True, False)
  1129. if light.parent and light.parent.type != 'ARMATURE':
  1130. self.parentId = light.parent.name
  1131. self.name = light.name
  1132. Main.log('processing begun of light (' + light.data.type + '): ' + self.name)
  1133. light_type_items = {'POINT': POINT_LIGHT, 'SUN': DIRECTIONAL_LIGHT, 'SPOT': SPOT_LIGHT, 'HEMI': HEMI_LIGHT, 'AREA': POINT_LIGHT}
  1134. self.light_type = light_type_items[light.data.type]
  1135. if self.light_type == POINT_LIGHT:
  1136. self.position = light.location
  1137. if hasattr(light.data, 'use_sphere'):
  1138. if light.data.use_sphere:
  1139. self.range = light.data.distance
  1140. elif self.light_type == DIRECTIONAL_LIGHT:
  1141. self.position = light.location
  1142. self.direction = Light.get_direction(light.matrix_local)
  1143. elif self.light_type == SPOT_LIGHT:
  1144. self.position = light.location
  1145. self.direction = Light.get_direction(light.matrix_local)
  1146. self.angle = light.data.spot_size
  1147. self.exponent = light.data.spot_blend * 2
  1148. if light.data.use_sphere:
  1149. self.range = light.data.distance
  1150. else:
  1151. # Hemi
  1152. matrix_local = light.matrix_local.copy()
  1153. matrix_local.translation = mathutils.Vector((0, 0, 0))
  1154. self.direction = (mathutils.Vector((0, 0, -1)) * matrix_local)
  1155. self.direction = scale_vector(self.direction, -1)
  1156. self.groundColor = mathutils.Color((0, 0, 0))
  1157. self.intensity = light.data.energy
  1158. self.diffuse = light.data.color if light.data.use_diffuse else mathutils.Color((0, 0, 0))
  1159. self.specular = light.data.color if light.data.use_specular else mathutils.Color((0, 0, 0))
  1160. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1161. def to_scene_file(self, file_handler):
  1162. file_handler.write('{')
  1163. write_string(file_handler, 'name', self.name, True)
  1164. write_string(file_handler, 'id', self.name)
  1165. write_float(file_handler, 'type', self.light_type)
  1166. if hasattr(self, 'parentId' ): write_string(file_handler, 'parentId' , self.parentId )
  1167. if hasattr(self, 'position' ): write_vector(file_handler, 'position' , self.position )
  1168. if hasattr(self, 'direction' ): write_vector(file_handler, 'direction' , self.direction )
  1169. if hasattr(self, 'angle' ): write_float (file_handler, 'angle' , self.angle )
  1170. if hasattr(self, 'exponent' ): write_float (file_handler, 'exponent' , self.exponent )
  1171. if hasattr(self, 'groundColor'): write_color (file_handler, 'groundColor', self.groundColor)
  1172. if hasattr(self, 'range' ): write_float (file_handler, 'range' , self.range )
  1173. write_float(file_handler, 'intensity', self.intensity)
  1174. write_color(file_handler, 'diffuse', self.diffuse)
  1175. write_color(file_handler, 'specular', self.specular)
  1176. super().to_scene_file(file_handler) # Animations
  1177. file_handler.write('}')
  1178. @staticmethod
  1179. def get_direction(matrix):
  1180. return (matrix.to_3x3() * mathutils.Vector((0.0, 0.0, -1.0))).normalized()
  1181. #===============================================================================
  1182. class ShadowGenerator:
  1183. def __init__(self, lamp, meshesAndNodes, scene):
  1184. Main.log('processing begun of shadows for light: ' + lamp.name)
  1185. self.lightId = lamp.name
  1186. self.mapSize = lamp.data.shadowMapSize
  1187. self.shadowBias = lamp.data.shadowBias
  1188. if lamp.data.shadowMap == VARIANCE_SHADOWS:
  1189. self.useVarianceShadowMap = True
  1190. elif lamp.data.shadowMap == POISSON_SHADOWS:
  1191. self.usePoissonSampling = True
  1192. elif lamp.data.shadowMap == BLUR_VARIANCE_SHADOWS:
  1193. self.useBlurVarianceShadowMap = True
  1194. self.shadowBlurScale = lamp.data.shadowBlurScale
  1195. self.shadowBlurBoxOffset = lamp.data.shadowBlurBoxOffset
  1196. # .babylon specific section
  1197. self.shadowCasters = []
  1198. for mesh in meshesAndNodes:
  1199. if (mesh.castShadows):
  1200. self.shadowCasters.append(mesh.name)
  1201. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1202. def to_scene_file(self, file_handler):
  1203. file_handler.write('{')
  1204. write_int(file_handler, 'mapSize', self.mapSize, True)
  1205. write_string(file_handler, 'lightId', self.lightId)
  1206. write_float(file_handler, 'bias', self.shadowBias)
  1207. if hasattr(self, 'useVarianceShadowMap') :
  1208. write_bool(file_handler, 'useVarianceShadowMap', self.useVarianceShadowMap)
  1209. elif hasattr(self, 'usePoissonSampling'):
  1210. write_bool(file_handler, 'usePoissonSampling', self.usePoissonSampling)
  1211. elif hasattr(self, 'useBlurVarianceShadowMap'):
  1212. write_bool(file_handler, 'useBlurVarianceShadowMap', self.useBlurVarianceShadowMap)
  1213. write_int(file_handler, 'blurScale', self.shadowBlurScale)
  1214. write_int(file_handler, 'blurBoxOffset', self.shadowBlurBoxOffset)
  1215. file_handler.write(',"renderList":[')
  1216. first = True
  1217. for caster in self.shadowCasters:
  1218. if first != True:
  1219. file_handler.write(',')
  1220. first = False
  1221. file_handler.write('"' + caster + '"')
  1222. file_handler.write(']')
  1223. file_handler.write('}')
  1224. #===============================================================================
  1225. class MultiMaterial:
  1226. def __init__(self, material_slots, idx):
  1227. self.name = Main.nameSpace + '.' + 'Multimaterial#' + str(idx)
  1228. Main.log('processing begun of multimaterial: ' + self.name, 2)
  1229. self.material_slots = material_slots
  1230. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1231. def to_scene_file(self, file_handler):
  1232. file_handler.write('{')
  1233. write_string(file_handler, 'name', self.name, True)
  1234. write_string(file_handler, 'id', self.name)
  1235. file_handler.write(',"materials":[')
  1236. first = True
  1237. for material in self.material_slots:
  1238. if first != True:
  1239. file_handler.write(',')
  1240. file_handler.write('"' + material.name +'"')
  1241. first = False
  1242. file_handler.write(']')
  1243. file_handler.write('}')
  1244. #===============================================================================
  1245. class Texture:
  1246. def __init__(self, slot, level, textureOrImage, mesh, exporter):
  1247. wasBaked = not hasattr(textureOrImage, 'uv_layer')
  1248. if wasBaked:
  1249. image = textureOrImage
  1250. texture = None
  1251. repeat = False
  1252. self.hasAlpha = False
  1253. self.coordinatesIndex = 0
  1254. else:
  1255. texture = textureOrImage
  1256. image = texture.texture.image
  1257. repeat = texture.texture.extension == 'REPEAT'
  1258. self.hasAlpha = texture.texture.use_alpha
  1259. usingMap = texture.uv_layer
  1260. if len(usingMap) == 0:
  1261. usingMap = mesh.data.uv_textures[0].name
  1262. Main.log('Image texture found, type: ' + slot + ', mapped using: "' + usingMap + '"', 3)
  1263. if mesh.data.uv_textures[0].name == usingMap:
  1264. self.coordinatesIndex = 0
  1265. elif mesh.data.uv_textures[1].name == usingMap:
  1266. self.coordinatesIndex = 1
  1267. else:
  1268. Main.warn('Texture is not mapped as UV or UV2, assigned 1', 4)
  1269. self.coordinatesIndex = 0
  1270. # always write the file out, since base64 encoding is easiest from a file
  1271. try:
  1272. imageFilepath = os.path.normpath(bpy.path.abspath(image.filepath))
  1273. basename = os.path.basename(imageFilepath)
  1274. targetdir = os.path.dirname(exporter.filepath)
  1275. internalImage = image.packed_file or wasBaked
  1276. # when coming from either a packed image or a baked image, then save_render
  1277. if internalImage:
  1278. if exporter.scene.inlineTextures:
  1279. textureFile = os.path.join(targetdir, basename + "temp")
  1280. else:
  1281. textureFile = os.path.join(targetdir, basename)
  1282. image.save_render(textureFile)
  1283. # when backed by an actual file, copy to target dir, unless inlining
  1284. else:
  1285. textureFile = bpy.path.abspath(image.filepath)
  1286. if not exporter.scene.inlineTextures:
  1287. shutil.copy(textureFile, targetdir)
  1288. except:
  1289. ex = sys.exc_info()
  1290. Main.log('Error encountered processing image file: ' + ', Error: '+ str(ex[1]))
  1291. if exporter.scene.inlineTextures:
  1292. # base64 is easiest from a file, so sometimes a temp file was made above; need to delete those
  1293. with open(textureFile, "rb") as image_file:
  1294. asString = base64.b64encode(image_file.read()).decode()
  1295. self.encoded_URI = 'data:image/' + image.file_format + ';base64,' + asString
  1296. if internalImage:
  1297. os.remove(textureFile)
  1298. # capture texture attributes
  1299. self.slot = slot
  1300. self.name = basename
  1301. self.level = level
  1302. if (texture and texture.mapping == 'CUBE'):
  1303. self.coordinatesMode = CUBIC_MODE
  1304. if (texture and texture.mapping == 'SPHERE'):
  1305. self.coordinatesMode = SPHERICAL_MODE
  1306. else:
  1307. self.coordinatesMode = EXPLICIT_MODE
  1308. self.uOffset = texture.offset.x if texture else 0.0
  1309. self.vOffset = texture.offset.y if texture else 0.0
  1310. self.uScale = texture.scale.x if texture else 1.0
  1311. self.vScale = texture.scale.y if texture else 1.0
  1312. self.uAng = 0
  1313. self.vAng = 0
  1314. self.wAng = 0
  1315. if (repeat):
  1316. if (texture.texture.use_mirror_x):
  1317. self.wrapU = MIRROR_ADDRESSMODE
  1318. else:
  1319. self.wrapU = WRAP_ADDRESSMODE
  1320. if (texture.texture.use_mirror_y):
  1321. self.wrapV = MIRROR_ADDRESSMODE
  1322. else:
  1323. self.wrapV = WRAP_ADDRESSMODE
  1324. else:
  1325. self.wrapU = CLAMP_ADDRESSMODE
  1326. self.wrapV = CLAMP_ADDRESSMODE
  1327. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1328. def to_scene_file(self, file_handler):
  1329. file_handler.write(', \n"' + self.slot + '":{')
  1330. write_string(file_handler, 'name', self.name, True)
  1331. write_float(file_handler, 'level', self.level)
  1332. write_float(file_handler, 'hasAlpha', self.hasAlpha)
  1333. write_int(file_handler, 'coordinatesMode', self.coordinatesMode)
  1334. write_float(file_handler, 'uOffset', self.uOffset)
  1335. write_float(file_handler, 'vOffset', self.vOffset)
  1336. write_float(file_handler, 'uScale', self.uScale)
  1337. write_float(file_handler, 'vScale', self.vScale)
  1338. write_float(file_handler, 'uAng', self.uAng)
  1339. write_float(file_handler, 'vAng', self.vAng)
  1340. write_float(file_handler, 'wAng', self.wAng)
  1341. write_int(file_handler, 'wrapU', self.wrapU)
  1342. write_int(file_handler, 'wrapV', self.wrapV)
  1343. write_int(file_handler, 'coordinatesIndex', self.coordinatesIndex)
  1344. if hasattr(self,'encoded_URI'):
  1345. write_string(file_handler, 'base64String', self.encoded_URI)
  1346. file_handler.write('}')
  1347. #===============================================================================
  1348. # need to evaluate the need to bake a mesh before even starting; class also stores specific types of bakes
  1349. class BakingRecipe:
  1350. def __init__(self, mesh, forceBaking = False):
  1351. # initialize all members
  1352. self.needsBaking = forceBaking
  1353. self.diffuseBaking = forceBaking
  1354. self.ambientBaking = False
  1355. self.opacityBaking = False
  1356. self.reflectionBaking = False
  1357. self.emissiveBaking = False
  1358. self.bumpBaking = False
  1359. self.specularBaking = False
  1360. # need to make sure a single render
  1361. self.cyclesRender = False
  1362. blenderRender = False
  1363. # transfer from Mesh custom properties
  1364. self.bakeSize = mesh.data.bakeSize
  1365. self.bakeQuality = mesh.data.bakeQuality # for lossy compression formats
  1366. # accumulators set by Blender Game
  1367. self.backFaceCulling = True # used only when baking
  1368. self.billboardMode = BILLBOARDMODE_ALL if len(mesh.material_slots) == 1 and mesh.material_slots[0].material.game_settings.face_orientation == 'BILLBOARD' else BILLBOARDMODE_NONE
  1369. # Cycles specific, need to get the node trees of each material
  1370. self.nodeTrees = []
  1371. for material_slot in mesh.material_slots:
  1372. # a material slot is not a reference to an actual material; need to look up
  1373. material = material_slot.material
  1374. self.backFaceCulling &= material.game_settings.use_backface_culling
  1375. # testing for Cycles renderer has to be different
  1376. if material.use_nodes == True:
  1377. self.needsBaking = True
  1378. self.cyclesRender = True
  1379. self.nodeTrees.append(material.node_tree)
  1380. for node in material.node_tree.nodes:
  1381. id = node.bl_idname
  1382. if id == 'ShaderNodeBsdfDiffuse':
  1383. self.diffuseBaking = True
  1384. if id == 'ShaderNodeAmbientOcclusion':
  1385. self.ambientBaking = True
  1386. # there is no opacity baking for Cycles AFAIK
  1387. if id == '':
  1388. self.opacityBaking = True
  1389. if id == 'ShaderNodeEmission':
  1390. self.emissiveBaking = True
  1391. if id == 'ShaderNodeNormal' or id == 'ShaderNodeNormalMap':
  1392. self.bumpBaking = True
  1393. if id == '':
  1394. self.specularBaking = True
  1395. else:
  1396. blenderRender = True
  1397. textures = [mtex for mtex in material.texture_slots if mtex and mtex.texture]
  1398. for mtex in textures:
  1399. if mtex.texture.type == 'IMAGE' or mtex.texture.type == 'NONE':
  1400. continue
  1401. self.needsBaking = True
  1402. if mtex.use_map_diffuse or mtex.use_map_color_diffuse:
  1403. if mtex.texture_coords == 'REFLECTION':
  1404. self.reflectionBaking = True
  1405. else:
  1406. self.diffuseBaking = True
  1407. if mtex.use_map_ambient:
  1408. self.ambientBaking = True
  1409. if mtex.use_map_alpha:
  1410. self.opacityBaking = True
  1411. if mtex.use_map_emit:
  1412. self.emissiveBaking = True
  1413. if mtex.use_map_normal:
  1414. self.bumpBaking = True
  1415. if mtex.use_map_color_spec:
  1416. self.specularBaking = True
  1417. self.multipleRenders = blenderRender and self.cyclesRender
  1418. # check for really old .blend file, eg. 2.49, to ensure that everything requires exists
  1419. if self.needsBaking and bpy.data.screens.find('UV Editing') == -1:
  1420. Main.warn('Contains material requiring baking, but resources not available. Probably .blend very old', 2)
  1421. self.needsBaking = False
  1422. #===============================================================================
  1423. # Not intended to be instanced directly
  1424. class Material:
  1425. def __init__(self):
  1426. # the number of users == 1 will cause the checkReadyOnlyOnce attribute to be set to true
  1427. self.numOfUsers = 1
  1428. # first pass of textures, either appending image type or recording types of bakes to do
  1429. self.textures = []
  1430. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1431. def to_scene_file(self, file_handler):
  1432. file_handler.write('{')
  1433. write_string(file_handler, 'name', self.name, True)
  1434. write_string(file_handler, 'id', self.name)
  1435. write_color(file_handler, 'ambient', self.ambient)
  1436. write_color(file_handler, 'diffuse', self.diffuse)
  1437. write_color(file_handler, 'specular', self.specular)
  1438. write_color(file_handler, 'emissive', self.emissive)
  1439. write_float(file_handler, 'specularPower', self.specularPower)
  1440. write_float(file_handler, 'alpha', self.alpha)
  1441. write_bool(file_handler, 'backFaceCulling', self.backFaceCulling)
  1442. if self.numOfUsers == 1:
  1443. write_bool(file_handler, 'checkReadyOnlyOnce', True)
  1444. for texSlot in self.textures:
  1445. texSlot.to_scene_file(file_handler)
  1446. file_handler.write('}')
  1447. #===============================================================================
  1448. class StdMaterial(Material):
  1449. def __init__(self, material_slot, exporter, mesh):
  1450. super().__init__()
  1451. self.name = Main.nameSpace + '.' + material_slot.name
  1452. Main.log('processing begun of Standard material: ' + material_slot.name, 2)
  1453. # a material slot is not a reference to an actual material; need to look up
  1454. material = material_slot.material
  1455. self.ambient = material.ambient * material.diffuse_color
  1456. self.diffuse = material.diffuse_intensity * material.diffuse_color
  1457. self.specular = material.specular_intensity * material.specular_color
  1458. self.emissive = material.emit * material.diffuse_color
  1459. self.specularPower = material.specular_hardness
  1460. self.alpha = material.alpha
  1461. self.backFaceCulling = material.game_settings.use_backface_culling
  1462. textures = [mtex for mtex in material.texture_slots if mtex and mtex.texture]
  1463. for mtex in textures:
  1464. # test should be un-neccessary, since should be a BakedMaterial; just for completeness
  1465. if (mtex.texture.type != 'IMAGE'):
  1466. continue
  1467. elif not mtex.texture.image:
  1468. Main.warn('Material has un-assigned image texture: "' + mtex.name + '" ignored', 3)
  1469. continue
  1470. elif len(mesh.data.uv_textures) == 0:
  1471. Main.warn('Mesh has no UV maps, material: "' + mtex.name + '" ignored', 3)
  1472. continue
  1473. if mtex.use_map_diffuse or mtex.use_map_color_diffuse:
  1474. if mtex.texture_coords == 'REFLECTION':
  1475. Main.log('Reflection texture found', 2)
  1476. self.textures.append(Texture('reflectionTexture', mtex.diffuse_color_factor, mtex, mesh, exporter))
  1477. else:
  1478. Main.log('Diffuse texture found', 2)
  1479. self.textures.append(Texture('diffuseTexture', mtex.diffuse_color_factor, mtex, mesh, exporter))
  1480. if mtex.use_map_ambient:
  1481. Main.log('Ambient texture found', 2)
  1482. self.textures.append(Texture('ambientTexture', mtex.ambient_factor, mtex, mesh, exporter))
  1483. if mtex.use_map_alpha:
  1484. Main.log('Opacity texture found', 2)
  1485. self.textures.append(Texture('opacityTexture', mtex.alpha_factor, mtex, mesh, exporter))
  1486. if mtex.use_map_emit:
  1487. Main.log('Emissive texture found', 2)
  1488. self.textures.append(Texture('emissiveTexture', mtex.emit_factor, mtex, mesh, exporter))
  1489. if mtex.use_map_normal:
  1490. Main.log('Bump texture found', 2)
  1491. self.textures.append(Texture('bumpTexture', 1.0 / mtex.normal_factor, mtex, mesh, exporter))
  1492. if mtex.use_map_color_spec:
  1493. Main.log('Specular texture found', 2)
  1494. self.textures.append(Texture('specularTexture', mtex.specular_color_factor, mtex, mesh, exporter))
  1495. #===============================================================================
  1496. class BakedMaterial(Material):
  1497. def __init__(self, exporter, mesh, recipe):
  1498. super().__init__()
  1499. self.name = Main.nameSpace + '.' + mesh.name
  1500. Main.log('processing begun of baked material: ' + mesh.name, 2)
  1501. # any baking already took in the values. Do not want to apply them again, but want shadows to show.
  1502. # These are the default values from StandardMaterials
  1503. self.ambient = mathutils.Color((0, 0, 0))
  1504. self.diffuse = mathutils.Color((0.8, 0.8, 0.8)) # needed for shadows, but not change anything else
  1505. self.specular = mathutils.Color((1, 1, 1))
  1506. self.emissive = mathutils.Color((0, 0, 0))
  1507. self.specularPower = 64
  1508. self.alpha = 1.0
  1509. self.backFaceCulling = recipe.backFaceCulling
  1510. # texture is baked from selected mesh(es), need to insure this mesh is only one selected
  1511. bpy.ops.object.select_all(action='DESELECT')
  1512. mesh.select = True
  1513. # store setting to restore
  1514. engine = exporter.scene.render.engine
  1515. # mode_set's only work when there is an active object
  1516. exporter.scene.objects.active = mesh
  1517. # you need UV on a mesh in order to bake image. This is not reqd for procedural textures, so may not exist
  1518. # need to look if it might already be created, as for a mesh with multi-materials
  1519. uv = None
  1520. for uvMap in mesh.data.uv_textures:
  1521. if uvMap.name == 'BakingUV':
  1522. uv = uvMap
  1523. break
  1524. if uv == None:
  1525. mesh.data.uv_textures.new('BakingUV')
  1526. uv = mesh.data.uv_textures['BakingUV']
  1527. uv.active = True
  1528. uv.active_render = True
  1529. # UV unwrap operates on mesh in only edit mode
  1530. # select all verticies of mesh, since smart_project works only with selected verticies
  1531. bpy.ops.object.mode_set(mode='EDIT')
  1532. bpy.ops.mesh.select_all(action='SELECT')
  1533. bpy.ops.uv.smart_project(angle_limit = 66.0, island_margin = 0.0, user_area_weight = 1.0, use_aspect = True)
  1534. # create a temporary image & link it to the UV/Image Editor so bake_image works
  1535. bpy.data.images.new(name = mesh.name + '_BJS_BAKE', width = recipe.bakeSize, height = recipe.bakeSize, alpha = False, float_buffer = False)
  1536. image = bpy.data.images[mesh.name + '_BJS_BAKE']
  1537. image.file_format = 'JPEG'
  1538. image.mapping = 'UV' # default value
  1539. image_settings = exporter.scene.render.image_settings
  1540. image_settings.file_format = 'JPEG'
  1541. image_settings.quality = recipe.bakeQuality # for lossy compression formats
  1542. # 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
  1543. # now go thru all the textures that need to be baked
  1544. if recipe.diffuseBaking:
  1545. self.bake('diffuseTexture', 'DIFFUSE_COLOR', 'TEXTURE', image, mesh, exporter, recipe)
  1546. if recipe.ambientBaking:
  1547. self.bake('ambientTexture', 'AO', 'AO', image, mesh, exporter, recipe)
  1548. if recipe.opacityBaking: # no eqivalent found for cycles
  1549. self.bake('opacityTexture', None, 'ALPHA', image, mesh, exporter, recipe)
  1550. if recipe.reflectionBaking:
  1551. self.bake('reflectionTexture', 'REFLECTION', 'MIRROR_COLOR', image, mesh, exporter, recipe)
  1552. if recipe.emissiveBaking:
  1553. self.bake('emissiveTexture', 'EMIT', 'EMIT', image, mesh, exporter, recipe)
  1554. if recipe.bumpBaking:
  1555. self.bake('bumpTexture', 'NORMAL', 'NORMALS', image, mesh, exporter, recipe)
  1556. if recipe.specularBaking:
  1557. self.bake('specularTexture', 'SPECULAR', 'SPEC_COLOR', image, mesh, exporter, recipe)
  1558. # Toggle vertex selection & mode, if setting changed their value
  1559. bpy.ops.mesh.select_all(action='TOGGLE') # still in edit mode toggle select back to previous
  1560. bpy.ops.object.mode_set(toggle=True) # change back to Object
  1561. bpy.ops.object.select_all(action='TOGGLE') # change scene selection back, not seeming to work
  1562. exporter.scene.render.engine = engine
  1563. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1564. def bake(self, bjs_type, cycles_type, internal_type, image, mesh, exporter, recipe):
  1565. if recipe.cyclesRender:
  1566. if cycles_type is None:
  1567. return
  1568. self.bakeCycles(cycles_type, image, recipe.nodeTrees)
  1569. else:
  1570. self.bakeInternal(internal_type, image)
  1571. self.textures.append(Texture(bjs_type, 1.0, image, mesh, exporter))
  1572. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1573. def bakeInternal(self, bake_type, image):
  1574. Main.log('Internal baking texture, type: ' + bake_type + ', mapped using: BakingUV', 3)
  1575. image.filepath = self.name + '_' + bake_type + '.jpg'
  1576. scene = bpy.context.scene
  1577. scene.render.engine = 'BLENDER_RENDER'
  1578. scene.render.bake_type = bake_type
  1579. # assign the image to the UV Editor, which does not have to shown
  1580. bpy.data.screens['UV Editing'].areas[1].spaces[0].image = image
  1581. renderer = scene.render
  1582. renderer.use_bake_selected_to_active = False
  1583. renderer.use_bake_to_vertex_color = False
  1584. renderer.use_bake_clear = True
  1585. renderer.bake_quad_split = 'AUTO'
  1586. renderer.bake_margin = 5
  1587. renderer.use_file_extension = True
  1588. renderer.use_bake_normalize = True
  1589. renderer.use_bake_antialiasing = True
  1590. bpy.ops.object.bake_image()
  1591. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1592. def bakeCycles(self, bake_type, image, nodeTrees):
  1593. Main.log('Cycles baking texture, type: ' + bake_type + ', mapped using: BakingUV', 3)
  1594. image.filepath = self.name + '_' + bake_type + '.jpg'
  1595. scene = bpy.context.scene
  1596. scene.render.engine = 'CYCLES'
  1597. # create an unlinked temporary node to bake to for each material
  1598. for tree in nodeTrees:
  1599. bakeNode = tree.nodes.new(type='ShaderNodeTexImage')
  1600. bakeNode.image = image
  1601. bakeNode.select = True
  1602. tree.nodes.active = bakeNode
  1603. bpy.ops.object.bake(type = bake_type, use_clear = True, margin = 5, use_selected_to_active = False)
  1604. for tree in nodeTrees:
  1605. tree.nodes.remove(tree.nodes.active)
  1606. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1607. @staticmethod
  1608. def meshBakingClean(mesh):
  1609. for uvMap in mesh.data.uv_textures:
  1610. if uvMap.name == 'BakingUV':
  1611. mesh.data.uv_textures.remove(uvMap)
  1612. break
  1613. # remove an image if it was baked
  1614. for image in bpy.data.images:
  1615. if image.name == mesh.name + '_BJS_BAKE':
  1616. image.user_clear() # cannot remove image unless 0 references
  1617. bpy.data.images.remove(image)
  1618. break
  1619. #===============================================================================
  1620. class Animation:
  1621. def __init__(self, dataType, framePerSecond, loopBehavior, name, propertyInBabylon):
  1622. self.dataType = dataType
  1623. self.framePerSecond = framePerSecond
  1624. self.loopBehavior = loopBehavior
  1625. self.name = name
  1626. self.propertyInBabylon = propertyInBabylon
  1627. #keys
  1628. self.frames = []
  1629. self.values = [] # vector3 for ANIMATIONTYPE_VECTOR3 & matrices for ANIMATIONTYPE_MATRIX
  1630. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1631. # for auto animate
  1632. def get_first_frame(self):
  1633. return self.frames[0] if len(self.frames) > 0 else -1
  1634. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1635. # for auto animate
  1636. def get_last_frame(self):
  1637. return self.frames[len(self.frames) - 1] if len(self.frames) > 0 else -1
  1638. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1639. def to_scene_file(self, file_handler):
  1640. file_handler.write('{')
  1641. write_int(file_handler, 'dataType', self.dataType, True)
  1642. write_int(file_handler, 'framePerSecond', self.framePerSecond)
  1643. file_handler.write(',"keys":[')
  1644. first = True
  1645. for frame_idx in range(len(self.frames)):
  1646. if first != True:
  1647. file_handler.write(',')
  1648. first = False
  1649. file_handler.write('{')
  1650. write_int(file_handler, 'frame', self.frames[frame_idx], True)
  1651. value_idx = self.values[frame_idx]
  1652. if self.dataType == ANIMATIONTYPE_MATRIX:
  1653. write_matrix4(file_handler, 'values', value_idx)
  1654. elif self.dataType == ANIMATIONTYPE_QUATERNION:
  1655. write_quaternion(file_handler, 'values', value_idx)
  1656. else:
  1657. write_vector(file_handler, 'values', value_idx)
  1658. file_handler.write('}')
  1659. file_handler.write(']') # close keys
  1660. # put this at the end to make less crazy looking ]}]]]}}}}}}}]]]],
  1661. # since animation is also at the end of the bone, mesh, camera, or light
  1662. write_int(file_handler, 'loopBehavior', self.loopBehavior)
  1663. write_string(file_handler, 'name', self.name)
  1664. write_string(file_handler, 'property', self.propertyInBabylon)
  1665. file_handler.write('}')
  1666. #===============================================================================
  1667. class VectorAnimation(Animation):
  1668. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1669. super().__init__(ANIMATIONTYPE_VECTOR3, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1670. # capture built up from fcurves
  1671. frames = dict()
  1672. for fcurve in object.animation_data.action.fcurves:
  1673. if fcurve.data_path == attrInBlender:
  1674. for key in fcurve.keyframe_points:
  1675. frame = key.co.x
  1676. frames[frame] = 1
  1677. #for each frame (next step ==> set for key frames)
  1678. for Frame in sorted(frames):
  1679. self.frames.append(Frame)
  1680. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1681. self.values.append(scale_vector(getattr(object, attrInBlender), mult, xOffset))
  1682. #===============================================================================
  1683. class QuaternionAnimation(Animation):
  1684. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1685. super().__init__(ANIMATIONTYPE_QUATERNION, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1686. # capture built up from fcurves
  1687. frames = dict()
  1688. for fcurve in object.animation_data.action.fcurves:
  1689. if fcurve.data_path == attrInBlender:
  1690. for key in fcurve.keyframe_points:
  1691. frame = key.co.x
  1692. frames[frame] = 1
  1693. #for each frame (next step ==> set for key frames)
  1694. for Frame in sorted(frames):
  1695. self.frames.append(Frame)
  1696. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1697. self.values.append(post_rotate_quaternion(getattr(object, attrInBlender), xOffset))
  1698. #===============================================================================
  1699. class QuaternionToEulerAnimation(Animation):
  1700. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1701. super().__init__(ANIMATIONTYPE_VECTOR3, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1702. # capture built up from fcurves
  1703. frames = dict()
  1704. for fcurve in object.animation_data.action.fcurves:
  1705. if fcurve.data_path == attrInBlender:
  1706. for key in fcurve.keyframe_points:
  1707. frame = key.co.x
  1708. frames[frame] = 1
  1709. #for each frame (next step ==> set for key frames)
  1710. for Frame in sorted(frames):
  1711. self.frames.append(Frame)
  1712. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1713. quat = getattr(object, attrInBlender)
  1714. eul = quat.to_euler("XYZ")
  1715. self.values.append(scale_vector(eul, mult, xOffset))
  1716. #===============================================================================
  1717. # module level formatting methods, called from multiple classes
  1718. #===============================================================================
  1719. def legal_js_identifier(input):
  1720. out = ''
  1721. prefix = ''
  1722. for char in input:
  1723. if len(out) == 0:
  1724. if char in '0123456789':
  1725. # cannot take the chance that leading numbers being chopped of cause name conflicts, e.g (01.R & 02.R)
  1726. prefix += char
  1727. continue
  1728. elif char.upper() not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
  1729. continue
  1730. legal = char if char.upper() in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_' else '_'
  1731. out += legal
  1732. if len(prefix) > 0:
  1733. out += '_' + prefix
  1734. return out
  1735. def format_f(num):
  1736. s = MAX_FLOAT_PRECISION % num # rounds to N decimal places while changing to string
  1737. s = s.rstrip('0') # ignore trailing zeroes
  1738. s = s.rstrip('.') # ignore trailing .
  1739. return '0' if s == '-0' else s
  1740. def format_matrix4(matrix):
  1741. tempMatrix = matrix.copy()
  1742. tempMatrix.transpose()
  1743. ret = ''
  1744. first = True
  1745. for vect in tempMatrix:
  1746. if (first != True):
  1747. ret +=','
  1748. first = False;
  1749. ret += format_f(vect[0]) + ',' + format_f(vect[1]) + ',' + format_f(vect[2]) + ',' + format_f(vect[3])
  1750. return ret
  1751. def format_array3(array):
  1752. return format_f(array[0]) + ',' + format_f(array[1]) + ',' + format_f(array[2])
  1753. def format_array(array, max_per_line = MAX_VERTEX_ELEMENTS, indent = ''):
  1754. ret = ''
  1755. first = True
  1756. nOnLine = 0
  1757. for element in array:
  1758. if (first != True):
  1759. ret +=','
  1760. first = False;
  1761. ret += format_f(element)
  1762. nOnLine += 1
  1763. if nOnLine >= max_per_line:
  1764. ret += '\n' + indent
  1765. nOnLine = 0
  1766. return ret
  1767. def format_color(color):
  1768. return format_f(color.r) + ',' + format_f(color.g) + ',' + format_f(color.b)
  1769. def format_vector(vector):
  1770. return format_f(vector.x) + ',' + format_f(vector.z) + ',' + format_f(vector.y)
  1771. def format_vector_array(vectorArray, max_per_line = MAX_VERTEX_ELEMENTS, indent = ''):
  1772. ret = ''
  1773. first = True
  1774. nOnLine = 0
  1775. for vector in vectorArray:
  1776. if (first != True):
  1777. ret +=','
  1778. first = False;
  1779. ret += format_vector(vector)
  1780. nOnLine += 3
  1781. if nOnLine >= max_per_line:
  1782. ret += '\n' + indent
  1783. nOnLine = 0
  1784. return ret
  1785. def format_quaternion(quaternion):
  1786. return format_f(quaternion.x) + ',' + format_f(quaternion.z) + ',' + format_f(quaternion.y) + ',' + format_f(-quaternion.w)
  1787. def format_int(int):
  1788. candidate = str(int) # when int string of an int
  1789. if '.' in candidate:
  1790. return format_f(math.floor(int)) # format_f removes un-neccessary precision
  1791. else:
  1792. return candidate
  1793. def format_bool(bool):
  1794. if bool:
  1795. return 'true'
  1796. else:
  1797. return 'false'
  1798. def scale_vector(vector, mult, xOffset = 0):
  1799. ret = vector.copy()
  1800. ret.x *= mult
  1801. ret.x += xOffset
  1802. ret.z *= mult
  1803. ret.y *= mult
  1804. return ret
  1805. def same_vertex(vertA, vertB):
  1806. return vertA.x == vertB.x and vertA.y == vertB.y and vertA.z == vertB.z
  1807. #===============================================================================
  1808. # module level methods for writing JSON (.babylon) files
  1809. #===============================================================================
  1810. def write_matrix4(file_handler, name, matrix):
  1811. file_handler.write(',"' + name + '":[' + format_matrix4(matrix) + ']')
  1812. def write_array(file_handler, name, array):
  1813. file_handler.write('\n,"' + name + '":[' + format_array(array) + ']')
  1814. def write_array3(file_handler, name, array):
  1815. file_handler.write(',"' + name + '":[' + format_array3(array) + ']')
  1816. def write_color(file_handler, name, color):
  1817. file_handler.write(',"' + name + '":[' + format_color(color) + ']')
  1818. def write_vector(file_handler, name, vector):
  1819. file_handler.write(',"' + name + '":[' + format_vector(vector) + ']')
  1820. def write_vector_array(file_handler, name, vectorArray):
  1821. file_handler.write('\n,"' + name + '":[' + format_vector_array(vectorArray) + ']')
  1822. def write_quaternion(file_handler, name, quaternion):
  1823. file_handler.write(',"' + name +'":[' + format_quaternion(quaternion) + ']')
  1824. def write_string(file_handler, name, string, noComma = False):
  1825. if noComma == False:
  1826. file_handler.write(',')
  1827. file_handler.write('"' + name + '":"' + string + '"')
  1828. def write_float(file_handler, name, float):
  1829. file_handler.write(',"' + name + '":' + format_f(float))
  1830. def write_int(file_handler, name, int, noComma = False):
  1831. if noComma == False:
  1832. file_handler.write(',')
  1833. file_handler.write('"' + name + '":' + format_int(int))
  1834. def write_bool(file_handler, name, bool, noComma = False):
  1835. if noComma == False:
  1836. file_handler.write(',')
  1837. file_handler.write('"' + name + '":' + format_bool(bool))
  1838. #===============================================================================
  1839. # custom properties definition and display
  1840. #===============================================================================
  1841. bpy.types.Mesh.autoAnimate = bpy.props.BoolProperty(
  1842. name='Auto launch animations',
  1843. description='',
  1844. default = False
  1845. )
  1846. bpy.types.Mesh.useFlatShading = bpy.props.BoolProperty(
  1847. name='Use Flat Shading',
  1848. description='',
  1849. default = False
  1850. )
  1851. bpy.types.Mesh.checkCollisions = bpy.props.BoolProperty(
  1852. name='Check Collisions',
  1853. description='Indicates mesh should be checked that it does not run into anything.',
  1854. default = False
  1855. )
  1856. bpy.types.Mesh.castShadows = bpy.props.BoolProperty(
  1857. name='Cast Shadows',
  1858. description='',
  1859. default = False
  1860. )
  1861. bpy.types.Mesh.receiveShadows = bpy.props.BoolProperty(
  1862. name='Receive Shadows',
  1863. description='',
  1864. default = False
  1865. )
  1866. bpy.types.Mesh.bakeSize = bpy.props.IntProperty(
  1867. name='Texture Size',
  1868. description='',
  1869. default = 1024
  1870. )
  1871. bpy.types.Mesh.bakeQuality = bpy.props.IntProperty(
  1872. name='Quality 1-100',
  1873. description='The trade-off between Quality - File size(100 highest quality)',
  1874. default = 50
  1875. )
  1876. bpy.types.Mesh.freezeWorldMatrix = bpy.props.BoolProperty(
  1877. name='Freeze World Matrix',
  1878. description='Indicate the position, rotation, & scale do not change for performance reasons',
  1879. default = False
  1880. )
  1881. bpy.types.Mesh.attachedSound = bpy.props.StringProperty(
  1882. name='Sound',
  1883. description='',
  1884. default = ''
  1885. )
  1886. bpy.types.Mesh.loopSound = bpy.props.BoolProperty(
  1887. name='Loop sound',
  1888. description='',
  1889. default = True
  1890. )
  1891. bpy.types.Mesh.autoPlaySound = bpy.props.BoolProperty(
  1892. name='Auto play sound',
  1893. description='',
  1894. default = True
  1895. )
  1896. bpy.types.Mesh.maxSoundDistance = bpy.props.FloatProperty(
  1897. name='Max sound distance',
  1898. description='',
  1899. default = 100
  1900. )
  1901. #===============================================================================
  1902. bpy.types.Camera.autoAnimate = bpy.props.BoolProperty(
  1903. name='Auto launch animations',
  1904. description='',
  1905. default = False
  1906. )
  1907. bpy.types.Camera.CameraType = bpy.props.EnumProperty(
  1908. name='Camera Type',
  1909. description='',
  1910. # ONLY Append, or existing .blends will have their camera changed
  1911. items = (
  1912. (V_JOYSTICKS_CAM , 'Virtual Joysticks' , 'Use Virtual Joysticks Camera'),
  1913. (TOUCH_CAM , 'Touch' , 'Use Touch Camera'),
  1914. (GAMEPAD_CAM , 'Gamepad' , 'Use Gamepad Camera'),
  1915. (FREE_CAM , 'Free' , 'Use Free Camera'),
  1916. (FOLLOW_CAM , 'Follow' , 'Use Follow Camera'),
  1917. (DEV_ORIENT_CAM , 'Device Orientation' , 'Use Device Orientation Camera'),
  1918. (ARC_ROTATE_CAM , 'Arc Rotate' , 'Use Arc Rotate Camera'),
  1919. (VR_DEV_ORIENT_FREE_CAM , 'VR Dev Orientation Free' , 'Use VR Dev Orientation Free Camera'),
  1920. (WEB_VR_FREE_CAM , 'Web VR Free' , 'Use Web VR Free Camera')
  1921. ),
  1922. default = FREE_CAM
  1923. )
  1924. bpy.types.Camera.checkCollisions = bpy.props.BoolProperty(
  1925. name='Check Collisions',
  1926. description='',
  1927. default = False
  1928. )
  1929. bpy.types.Camera.applyGravity = bpy.props.BoolProperty(
  1930. name='Apply Gravity',
  1931. description='',
  1932. default = False
  1933. )
  1934. bpy.types.Camera.ellipsoid = bpy.props.FloatVectorProperty(
  1935. name='Ellipsoid',
  1936. description='',
  1937. default = mathutils.Vector((0.2, 0.9, 0.2))
  1938. )
  1939. bpy.types.Camera.Camera3DRig = bpy.props.EnumProperty(
  1940. name='Rig',
  1941. description='',
  1942. items = (
  1943. (RIG_MODE_NONE , 'None' , 'No 3D effects'),
  1944. (RIG_MODE_STEREOSCOPIC_ANAGLYPH , 'Anaaglph' , 'Stereoscopic Anagylph'),
  1945. (RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL , 'side-by-side Parallel' , 'Stereoscopic side-by-side parallel'),
  1946. (RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED, 'side-by-side crosseyed', 'Stereoscopic side-by-side crosseyed'),
  1947. (RIG_MODE_STEREOSCOPIC_OVERUNDER , 'over-under' , 'Stereoscopic over-under'),
  1948. (RIG_MODE_VR , 'VR distortion' , 'Use Web VR Free Camera')
  1949. ),
  1950. default = RIG_MODE_NONE
  1951. )
  1952. bpy.types.Camera.interaxialDistance = bpy.props.FloatProperty(
  1953. name='Interaxial Distance',
  1954. description='Distance between cameras. Used by all but VR 3D rigs.',
  1955. default = 0.0637
  1956. )
  1957. #===============================================================================
  1958. bpy.types.Lamp.autoAnimate = bpy.props.BoolProperty(
  1959. name='Auto launch animations',
  1960. description='',
  1961. default = False
  1962. )
  1963. bpy.types.Lamp.shadowMap = bpy.props.EnumProperty(
  1964. name='Shadow Map',
  1965. description='',
  1966. items = ((NO_SHADOWS , 'None' , 'No Shadow Maps'),
  1967. (STD_SHADOWS , 'Standard' , 'Use Standard Shadow Maps'),
  1968. (POISSON_SHADOWS , 'Poisson' , 'Use Poisson Sampling'),
  1969. (VARIANCE_SHADOWS , 'Variance' , 'Use Variance Shadow Maps'),
  1970. (BLUR_VARIANCE_SHADOWS, 'Blur Variance', 'Use Blur Variance Shadow Maps')
  1971. ),
  1972. default = NO_SHADOWS
  1973. )
  1974. bpy.types.Lamp.shadowMapSize = bpy.props.IntProperty(
  1975. name='Shadow Map Size',
  1976. description='',
  1977. default = 512
  1978. )
  1979. bpy.types.Lamp.shadowBias = bpy.props.FloatProperty(
  1980. name='Shadow Bias',
  1981. description='',
  1982. default = 0.00005
  1983. )
  1984. bpy.types.Lamp.shadowBlurScale = bpy.props.IntProperty(
  1985. name='Blur Scale',
  1986. description='',
  1987. default = 2
  1988. )
  1989. bpy.types.Lamp.shadowBlurBoxOffset = bpy.props.IntProperty(
  1990. name='Blur Box Offset',
  1991. description='',
  1992. default = 0
  1993. )
  1994. class ObjectPanel(bpy.types.Panel):
  1995. bl_label = 'Babylon.js'
  1996. bl_space_type = 'PROPERTIES'
  1997. bl_region_type = 'WINDOW'
  1998. bl_context = 'data'
  1999. def draw(self, context):
  2000. ob = context.object
  2001. if not ob or not ob.data:
  2002. return
  2003. layout = self.layout
  2004. isMesh = isinstance(ob.data, bpy.types.Mesh)
  2005. isCamera = isinstance(ob.data, bpy.types.Camera)
  2006. isLight = isinstance(ob.data, bpy.types.Lamp)
  2007. if isMesh:
  2008. layout.prop(ob.data, 'useFlatShading')
  2009. layout.prop(ob.data, 'checkCollisions')
  2010. layout.prop(ob.data, 'castShadows')
  2011. layout.prop(ob.data, 'receiveShadows')
  2012. layout.separator()
  2013. layout.prop(ob.data, 'autoAnimate')
  2014. box = layout.box()
  2015. box.label(text="Procedural Texture / Cycles Baking")
  2016. box.prop(ob.data, 'bakeSize')
  2017. box.prop(ob.data, 'bakeQuality')
  2018. layout.prop(ob.data, 'freezeWorldMatrix')
  2019. box = layout.box()
  2020. box.prop(ob.data, 'attachedSound')
  2021. box.prop(ob.data, 'autoPlaySound')
  2022. box.prop(ob.data, 'loopSound')
  2023. box.prop(ob.data, 'maxSoundDistance')
  2024. elif isCamera:
  2025. layout.prop(ob.data, 'CameraType')
  2026. layout.prop(ob.data, 'checkCollisions')
  2027. layout.prop(ob.data, 'applyGravity')
  2028. layout.prop(ob.data, 'ellipsoid')
  2029. box = layout.box()
  2030. box.label(text="3D Camera Rigs")
  2031. box.prop(ob.data, 'Camera3DRig')
  2032. box.prop(ob.data, 'interaxialDistance')
  2033. layout.prop(ob.data, 'autoAnimate')
  2034. elif isLight:
  2035. layout.prop(ob.data, 'shadowMap')
  2036. layout.prop(ob.data, 'shadowMapSize')
  2037. layout.prop(ob.data, 'shadowBias')
  2038. box = layout.box()
  2039. box.label(text="Blur Variance Shadows")
  2040. box.prop(ob.data, 'shadowBlurScale')
  2041. box.prop(ob.data, 'shadowBlurBoxOffset')
  2042. layout.prop(ob.data, 'autoAnimate')