io_export_babylon.py 112 KB

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