io_export_babylon.py 104 KB

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