io_export_babylon.py 112 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610
  1. bl_info = {
  2. 'name': 'Babylon.js',
  3. 'author': 'David Catuhe, Jeff Palmer',
  4. 'version': (4, 0, 1),
  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. # UV unwrap operates on mesh in only edit mode, procedurals can also give error of 'no images to be found' when not done
  1657. # select all verticies of mesh, since smart_project works only with selected verticies
  1658. bpy.ops.object.mode_set(mode='EDIT')
  1659. bpy.ops.mesh.select_all(action='SELECT')
  1660. # you need UV on a mesh in order to bake image. This is not reqd for procedural textures, so may not exist
  1661. # need to look if it might already be created, if so use the first one
  1662. uv = mesh.data.uv_textures[0] if len(mesh.data.uv_textures) > 0 else None
  1663. if uv == None:
  1664. mesh.data.uv_textures.new('BakingUV')
  1665. uv = mesh.data.uv_textures['BakingUV']
  1666. uv.active = True
  1667. uv.active_render = True
  1668. bpy.ops.uv.smart_project(angle_limit = 66.0, island_margin = 0.0, user_area_weight = 1.0, use_aspect = True)
  1669. uvName = 'BakingUV' # issues with cycles when not done this way
  1670. else:
  1671. uvName = uv.name
  1672. # create a temporary image & link it to the UV/Image Editor so bake_image works
  1673. bpy.data.images.new(name = mesh.name + '_BJS_BAKE', width = recipe.bakeSize, height = recipe.bakeSize, alpha = False, float_buffer = False)
  1674. image = bpy.data.images[mesh.name + '_BJS_BAKE']
  1675. image.file_format = 'JPEG'
  1676. image.mapping = 'UV' # default value
  1677. image_settings = exporter.scene.render.image_settings
  1678. image_settings.file_format = 'JPEG'
  1679. image_settings.quality = recipe.bakeQuality # for lossy compression formats
  1680. # 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
  1681. # now go thru all the textures that need to be baked
  1682. if recipe.diffuseBaking:
  1683. self.bake('diffuseTexture', 'DIFFUSE_COLOR', 'TEXTURE', image, mesh, uvName, exporter, recipe)
  1684. if recipe.ambientBaking:
  1685. self.bake('ambientTexture', 'AO', 'AO', image, mesh, uvName, exporter, recipe)
  1686. if recipe.opacityBaking: # no eqivalent found for cycles
  1687. self.bake('opacityTexture', None, 'ALPHA', image, mesh, uvName, exporter, recipe)
  1688. if recipe.reflectionBaking:
  1689. self.bake('reflectionTexture', 'REFLECTION', 'MIRROR_COLOR', image, mesh, uvName, exporter, recipe)
  1690. if recipe.emissiveBaking:
  1691. self.bake('emissiveTexture', 'EMIT', 'EMIT', image, mesh, uvName, exporter, recipe)
  1692. if recipe.bumpBaking:
  1693. self.bake('bumpTexture', 'NORMAL', 'NORMALS', image, mesh, uvName, exporter, recipe)
  1694. if recipe.specularBaking:
  1695. self.bake('specularTexture', 'SPECULAR', 'SPEC_COLOR', image, mesh, uvName, exporter, recipe)
  1696. # Toggle vertex selection & mode, if setting changed their value
  1697. bpy.ops.mesh.select_all(action='TOGGLE') # still in edit mode toggle select back to previous
  1698. bpy.ops.object.mode_set(toggle=True) # change back to Object
  1699. bpy.ops.object.select_all(action='TOGGLE') # change scene selection back, not seeming to work
  1700. exporter.scene.render.engine = engine
  1701. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1702. def bake(self, bjs_type, cycles_type, internal_type, image, mesh, uvName, exporter, recipe):
  1703. if recipe.cyclesRender:
  1704. if cycles_type is None:
  1705. return
  1706. self.bakeCycles(cycles_type, image, uvName, recipe.nodeTrees)
  1707. else:
  1708. self.bakeInternal(internal_type, image, uvName)
  1709. self.textures.append(Texture(bjs_type, 1.0, image, mesh, exporter))
  1710. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1711. def bakeInternal(self, bake_type, image, uvName):
  1712. Main.log('Internal baking texture, type: ' + bake_type + ', mapped using: ' + uvName, 3)
  1713. # need to use the legal name, since this will become the file name, chars like ':' not legal
  1714. legalName = legal_js_identifier(self.name)
  1715. image.filepath = legalName + '_' + bake_type + '.jpg'
  1716. scene = bpy.context.scene
  1717. scene.render.engine = 'BLENDER_RENDER'
  1718. scene.render.bake_type = bake_type
  1719. # assign the image to the UV Editor, which does not have to shown
  1720. bpy.data.screens['UV Editing'].areas[1].spaces[0].image = image
  1721. renderer = scene.render
  1722. renderer.use_bake_selected_to_active = False
  1723. renderer.use_bake_to_vertex_color = False
  1724. renderer.use_bake_clear = True
  1725. renderer.bake_quad_split = 'AUTO'
  1726. renderer.bake_margin = 5
  1727. renderer.use_file_extension = True
  1728. renderer.use_bake_normalize = True
  1729. renderer.use_bake_antialiasing = True
  1730. bpy.ops.object.bake_image()
  1731. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1732. def bakeCycles(self, bake_type, image, uvName, nodeTrees):
  1733. Main.log('Cycles baking texture, type: ' + bake_type + ', mapped using: ' + uvName, 3)
  1734. legalName = legal_js_identifier(self.name)
  1735. image.filepath = legalName + '_' + bake_type + '.jpg'
  1736. scene = bpy.context.scene
  1737. scene.render.engine = 'CYCLES'
  1738. # create an unlinked temporary node to bake to for each material
  1739. for tree in nodeTrees:
  1740. bakeNode = tree.nodes.new(type='ShaderNodeTexImage')
  1741. bakeNode.image = image
  1742. bakeNode.select = True
  1743. tree.nodes.active = bakeNode
  1744. bpy.ops.object.bake(type = bake_type, use_clear = True, margin = 5, use_selected_to_active = False)
  1745. for tree in nodeTrees:
  1746. tree.nodes.remove(tree.nodes.active)
  1747. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1748. @staticmethod
  1749. def meshBakingClean(mesh):
  1750. for uvMap in mesh.data.uv_textures:
  1751. if uvMap.name == 'BakingUV':
  1752. mesh.data.uv_textures.remove(uvMap)
  1753. break
  1754. # remove an image if it was baked
  1755. for image in bpy.data.images:
  1756. if image.name == mesh.name + '_BJS_BAKE':
  1757. image.user_clear() # cannot remove image unless 0 references
  1758. bpy.data.images.remove(image)
  1759. break
  1760. #===============================================================================
  1761. class Animation:
  1762. def __init__(self, dataType, framePerSecond, loopBehavior, name, propertyInBabylon):
  1763. self.dataType = dataType
  1764. self.framePerSecond = framePerSecond
  1765. self.loopBehavior = loopBehavior
  1766. self.name = name
  1767. self.propertyInBabylon = propertyInBabylon
  1768. #keys
  1769. self.frames = []
  1770. self.values = [] # vector3 for ANIMATIONTYPE_VECTOR3 & matrices for ANIMATIONTYPE_MATRIX
  1771. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1772. # for auto animate
  1773. def get_first_frame(self):
  1774. return self.frames[0] if len(self.frames) > 0 else -1
  1775. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1776. # for auto animate
  1777. def get_last_frame(self):
  1778. return self.frames[len(self.frames) - 1] if len(self.frames) > 0 else -1
  1779. # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1780. def to_scene_file(self, file_handler):
  1781. file_handler.write('{')
  1782. write_int(file_handler, 'dataType', self.dataType, True)
  1783. write_int(file_handler, 'framePerSecond', self.framePerSecond)
  1784. file_handler.write(',"keys":[')
  1785. first = True
  1786. for frame_idx in range(len(self.frames)):
  1787. if first != True:
  1788. file_handler.write(',')
  1789. first = False
  1790. file_handler.write('{')
  1791. write_int(file_handler, 'frame', self.frames[frame_idx], True)
  1792. value_idx = self.values[frame_idx]
  1793. if self.dataType == ANIMATIONTYPE_MATRIX:
  1794. write_matrix4(file_handler, 'values', value_idx)
  1795. elif self.dataType == ANIMATIONTYPE_QUATERNION:
  1796. write_quaternion(file_handler, 'values', value_idx)
  1797. else:
  1798. write_vector(file_handler, 'values', value_idx)
  1799. file_handler.write('}')
  1800. file_handler.write(']') # close keys
  1801. # put this at the end to make less crazy looking ]}]]]}}}}}}}]]]],
  1802. # since animation is also at the end of the bone, mesh, camera, or light
  1803. write_int(file_handler, 'loopBehavior', self.loopBehavior)
  1804. write_string(file_handler, 'name', self.name)
  1805. write_string(file_handler, 'property', self.propertyInBabylon)
  1806. file_handler.write('}')
  1807. #===============================================================================
  1808. class VectorAnimation(Animation):
  1809. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1810. super().__init__(ANIMATIONTYPE_VECTOR3, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1811. # capture built up from fcurves
  1812. frames = dict()
  1813. for fcurve in object.animation_data.action.fcurves:
  1814. if fcurve.data_path == attrInBlender:
  1815. for key in fcurve.keyframe_points:
  1816. frame = key.co.x
  1817. frames[frame] = 1
  1818. #for each frame (next step ==> set for key frames)
  1819. for Frame in sorted(frames):
  1820. self.frames.append(Frame)
  1821. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1822. self.values.append(scale_vector(getattr(object, attrInBlender), mult, xOffset))
  1823. #===============================================================================
  1824. class QuaternionAnimation(Animation):
  1825. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1826. super().__init__(ANIMATIONTYPE_QUATERNION, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1827. # capture built up from fcurves
  1828. frames = dict()
  1829. for fcurve in object.animation_data.action.fcurves:
  1830. if fcurve.data_path == attrInBlender:
  1831. for key in fcurve.keyframe_points:
  1832. frame = key.co.x
  1833. frames[frame] = 1
  1834. #for each frame (next step ==> set for key frames)
  1835. for Frame in sorted(frames):
  1836. self.frames.append(Frame)
  1837. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1838. self.values.append(post_rotate_quaternion(getattr(object, attrInBlender), xOffset))
  1839. #===============================================================================
  1840. class QuaternionToEulerAnimation(Animation):
  1841. def __init__(self, object, attrInBlender, propertyInBabylon, mult, xOffset = 0):
  1842. super().__init__(ANIMATIONTYPE_VECTOR3, 30, ANIMATIONLOOPMODE_CYCLE, propertyInBabylon + ' animation', propertyInBabylon)
  1843. # capture built up from fcurves
  1844. frames = dict()
  1845. for fcurve in object.animation_data.action.fcurves:
  1846. if fcurve.data_path == attrInBlender:
  1847. for key in fcurve.keyframe_points:
  1848. frame = key.co.x
  1849. frames[frame] = 1
  1850. #for each frame (next step ==> set for key frames)
  1851. for Frame in sorted(frames):
  1852. self.frames.append(Frame)
  1853. bpy.context.scene.frame_set(int(Frame + bpy.context.scene.frame_start))
  1854. quat = getattr(object, attrInBlender)
  1855. eul = quat.to_euler("XYZ")
  1856. self.values.append(scale_vector(eul, mult, xOffset))
  1857. #===============================================================================
  1858. # module level formatting methods, called from multiple classes
  1859. #===============================================================================
  1860. def legal_js_identifier(input):
  1861. out = ''
  1862. prefix = ''
  1863. for char in input:
  1864. if len(out) == 0:
  1865. if char in '0123456789':
  1866. # cannot take the chance that leading numbers being chopped of cause name conflicts, e.g (01.R & 02.R)
  1867. prefix += char
  1868. continue
  1869. elif char.upper() not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
  1870. continue
  1871. legal = char if char.upper() in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_' else '_'
  1872. out += legal
  1873. if len(prefix) > 0:
  1874. out += '_' + prefix
  1875. return out
  1876. def format_f(num):
  1877. s = MAX_FLOAT_PRECISION % num # rounds to N decimal places while changing to string
  1878. s = s.rstrip('0') # ignore trailing zeroes
  1879. s = s.rstrip('.') # ignore trailing .
  1880. return '0' if s == '-0' else s
  1881. def format_matrix4(matrix):
  1882. tempMatrix = matrix.copy()
  1883. tempMatrix.transpose()
  1884. ret = ''
  1885. first = True
  1886. for vect in tempMatrix:
  1887. if (first != True):
  1888. ret +=','
  1889. first = False;
  1890. ret += format_f(vect[0]) + ',' + format_f(vect[1]) + ',' + format_f(vect[2]) + ',' + format_f(vect[3])
  1891. return ret
  1892. def format_array3(array):
  1893. return format_f(array[0]) + ',' + format_f(array[1]) + ',' + format_f(array[2])
  1894. def format_array(array, max_per_line = MAX_VERTEX_ELEMENTS, indent = ''):
  1895. ret = ''
  1896. first = True
  1897. nOnLine = 0
  1898. for element in array:
  1899. if (first != True):
  1900. ret +=','
  1901. first = False;
  1902. ret += format_f(element)
  1903. nOnLine += 1
  1904. if nOnLine >= max_per_line:
  1905. ret += '\n' + indent
  1906. nOnLine = 0
  1907. return ret
  1908. def format_color(color):
  1909. return format_f(color.r) + ',' + format_f(color.g) + ',' + format_f(color.b)
  1910. def format_vector(vector):
  1911. return format_f(vector.x) + ',' + format_f(vector.z) + ',' + format_f(vector.y)
  1912. def format_vector_array(vectorArray, max_per_line = MAX_VERTEX_ELEMENTS, indent = ''):
  1913. ret = ''
  1914. first = True
  1915. nOnLine = 0
  1916. for vector in vectorArray:
  1917. if (first != True):
  1918. ret +=','
  1919. first = False;
  1920. ret += format_vector(vector)
  1921. nOnLine += 3
  1922. if nOnLine >= max_per_line:
  1923. ret += '\n' + indent
  1924. nOnLine = 0
  1925. return ret
  1926. def format_quaternion(quaternion):
  1927. return format_f(quaternion.x) + ',' + format_f(quaternion.z) + ',' + format_f(quaternion.y) + ',' + format_f(-quaternion.w)
  1928. def format_int(int):
  1929. candidate = str(int) # when int string of an int
  1930. if '.' in candidate:
  1931. return format_f(math.floor(int)) # format_f removes un-neccessary precision
  1932. else:
  1933. return candidate
  1934. def format_bool(bool):
  1935. if bool:
  1936. return 'true'
  1937. else:
  1938. return 'false'
  1939. def scale_vector(vector, mult, xOffset = 0):
  1940. ret = vector.copy()
  1941. ret.x *= mult
  1942. ret.x += xOffset
  1943. ret.z *= mult
  1944. ret.y *= mult
  1945. return ret
  1946. def same_vertex(vertA, vertB):
  1947. return vertA.x == vertB.x and vertA.y == vertB.y and vertA.z == vertB.z
  1948. def same_array(arrayA, arrayB):
  1949. if len(arrayA) != len(arrayB): return False
  1950. for i in range(len(arrayA)):
  1951. if arrayA[i] != arrayB[i] : return False
  1952. return True
  1953. #===============================================================================
  1954. # module level methods for writing JSON (.babylon) files
  1955. #===============================================================================
  1956. def write_matrix4(file_handler, name, matrix):
  1957. file_handler.write(',"' + name + '":[' + format_matrix4(matrix) + ']')
  1958. def write_array(file_handler, name, array):
  1959. file_handler.write('\n,"' + name + '":[' + format_array(array) + ']')
  1960. def write_array3(file_handler, name, array):
  1961. file_handler.write(',"' + name + '":[' + format_array3(array) + ']')
  1962. def write_color(file_handler, name, color):
  1963. file_handler.write(',"' + name + '":[' + format_color(color) + ']')
  1964. def write_vector(file_handler, name, vector):
  1965. file_handler.write(',"' + name + '":[' + format_vector(vector) + ']')
  1966. def write_vector_array(file_handler, name, vectorArray):
  1967. file_handler.write('\n,"' + name + '":[' + format_vector_array(vectorArray) + ']')
  1968. def write_quaternion(file_handler, name, quaternion):
  1969. file_handler.write(',"' + name +'":[' + format_quaternion(quaternion) + ']')
  1970. def write_string(file_handler, name, string, noComma = False):
  1971. if noComma == False:
  1972. file_handler.write(',')
  1973. file_handler.write('"' + name + '":"' + string + '"')
  1974. def write_float(file_handler, name, float):
  1975. file_handler.write(',"' + name + '":' + format_f(float))
  1976. def write_int(file_handler, name, int, noComma = False):
  1977. if noComma == False:
  1978. file_handler.write(',')
  1979. file_handler.write('"' + name + '":' + format_int(int))
  1980. def write_bool(file_handler, name, bool, noComma = False):
  1981. if noComma == False:
  1982. file_handler.write(',')
  1983. file_handler.write('"' + name + '":' + format_bool(bool))
  1984. #===============================================================================
  1985. # custom properties definition and display
  1986. #===============================================================================
  1987. bpy.types.Mesh.autoAnimate = bpy.props.BoolProperty(
  1988. name='Auto launch animations',
  1989. description='',
  1990. default = False
  1991. )
  1992. bpy.types.Mesh.useFlatShading = bpy.props.BoolProperty(
  1993. name='Use Flat Shading',
  1994. description='Use face normals. Increases vertices.',
  1995. default = False
  1996. )
  1997. bpy.types.Mesh.checkCollisions = bpy.props.BoolProperty(
  1998. name='Check Collisions',
  1999. description='Indicates mesh should be checked that it does not run into anything.',
  2000. default = False
  2001. )
  2002. bpy.types.Mesh.castShadows = bpy.props.BoolProperty(
  2003. name='Cast Shadows',
  2004. description='',
  2005. default = False
  2006. )
  2007. bpy.types.Mesh.receiveShadows = bpy.props.BoolProperty(
  2008. name='Receive Shadows',
  2009. description='',
  2010. default = False
  2011. )
  2012. bpy.types.Mesh.bakeSize = bpy.props.IntProperty(
  2013. name='Texture Size',
  2014. description='',
  2015. default = 1024
  2016. )
  2017. bpy.types.Mesh.bakeQuality = bpy.props.IntProperty(
  2018. name='Quality 1-100',
  2019. description='The trade-off between Quality - File size(100 highest quality)',
  2020. default = 50, min = 1, max = 100
  2021. )
  2022. bpy.types.Mesh.materialNameSpace = bpy.props.StringProperty(
  2023. name='Name Space',
  2024. description='Prefix to use for materials for sharing across .blends.',
  2025. default = DEFAULT_MATERIAL_NAMESPACE
  2026. )
  2027. bpy.types.Mesh.checkReadyOnlyOnce = bpy.props.BoolProperty(
  2028. name='Check Ready Only Once',
  2029. description='When checked better CPU utilization. Advanced user option.',
  2030. default = False
  2031. )
  2032. bpy.types.Mesh.freezeWorldMatrix = bpy.props.BoolProperty(
  2033. name='Freeze World Matrix',
  2034. description='Indicate the position, rotation, & scale do not change for performance reasons',
  2035. default = False
  2036. )
  2037. bpy.types.Mesh.loadDisabled = bpy.props.BoolProperty(
  2038. name='Load Disabled',
  2039. description='Indicate this mesh & children should not be active until enabled by code.',
  2040. default = False
  2041. )
  2042. bpy.types.Mesh.attachedSound = bpy.props.StringProperty(
  2043. name='Sound',
  2044. description='',
  2045. default = ''
  2046. )
  2047. bpy.types.Mesh.loopSound = bpy.props.BoolProperty(
  2048. name='Loop sound',
  2049. description='',
  2050. default = True
  2051. )
  2052. bpy.types.Mesh.autoPlaySound = bpy.props.BoolProperty(
  2053. name='Auto play sound',
  2054. description='',
  2055. default = True
  2056. )
  2057. bpy.types.Mesh.maxSoundDistance = bpy.props.FloatProperty(
  2058. name='Max sound distance',
  2059. description='',
  2060. default = 100
  2061. )
  2062. bpy.types.Mesh.maxInfluencers = bpy.props.IntProperty(
  2063. name='Max bone Influencers / Vertex',
  2064. description='When fewer than this are observed, the lower value is used.',
  2065. default = 8, min = 1, max = 8
  2066. )
  2067. #===============================================================================
  2068. bpy.types.Camera.autoAnimate = bpy.props.BoolProperty(
  2069. name='Auto launch animations',
  2070. description='',
  2071. default = False
  2072. )
  2073. bpy.types.Camera.CameraType = bpy.props.EnumProperty(
  2074. name='Camera Type',
  2075. description='',
  2076. # ONLY Append, or existing .blends will have their camera changed
  2077. items = (
  2078. (V_JOYSTICKS_CAM , 'Virtual Joysticks' , 'Use Virtual Joysticks Camera'),
  2079. (TOUCH_CAM , 'Touch' , 'Use Touch Camera'),
  2080. (GAMEPAD_CAM , 'Gamepad' , 'Use Gamepad Camera'),
  2081. (FREE_CAM , 'Free' , 'Use Free Camera'),
  2082. (FOLLOW_CAM , 'Follow' , 'Use Follow Camera'),
  2083. (DEV_ORIENT_CAM , 'Device Orientation' , 'Use Device Orientation Camera'),
  2084. (ARC_ROTATE_CAM , 'Arc Rotate' , 'Use Arc Rotate Camera'),
  2085. (VR_DEV_ORIENT_FREE_CAM , 'VR Dev Orientation Free' , 'Use VR Dev Orientation Free Camera'),
  2086. (WEB_VR_FREE_CAM , 'Web VR Free' , 'Use Web VR Free Camera')
  2087. ),
  2088. default = FREE_CAM
  2089. )
  2090. bpy.types.Camera.checkCollisions = bpy.props.BoolProperty(
  2091. name='Check Collisions',
  2092. description='',
  2093. default = False
  2094. )
  2095. bpy.types.Camera.applyGravity = bpy.props.BoolProperty(
  2096. name='Apply Gravity',
  2097. description='',
  2098. default = False
  2099. )
  2100. bpy.types.Camera.ellipsoid = bpy.props.FloatVectorProperty(
  2101. name='Ellipsoid',
  2102. description='',
  2103. default = mathutils.Vector((0.2, 0.9, 0.2))
  2104. )
  2105. bpy.types.Camera.Camera3DRig = bpy.props.EnumProperty(
  2106. name='Rig',
  2107. description='',
  2108. items = (
  2109. (RIG_MODE_NONE , 'None' , 'No 3D effects'),
  2110. (RIG_MODE_STEREOSCOPIC_ANAGLYPH , 'Anaaglph' , 'Stereoscopic Anagylph'),
  2111. (RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL , 'side-by-side Parallel' , 'Stereoscopic side-by-side parallel'),
  2112. (RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED, 'side-by-side crosseyed', 'Stereoscopic side-by-side crosseyed'),
  2113. (RIG_MODE_STEREOSCOPIC_OVERUNDER , 'over-under' , 'Stereoscopic over-under'),
  2114. (RIG_MODE_VR , 'VR distortion' , 'Use Web VR Free Camera')
  2115. ),
  2116. default = RIG_MODE_NONE
  2117. )
  2118. bpy.types.Camera.interaxialDistance = bpy.props.FloatProperty(
  2119. name='Interaxial Distance',
  2120. description='Distance between cameras. Used by all but VR 3D rigs.',
  2121. default = 0.0637
  2122. )
  2123. #===============================================================================
  2124. bpy.types.Lamp.autoAnimate = bpy.props.BoolProperty(
  2125. name='Auto launch animations',
  2126. description='',
  2127. default = False
  2128. )
  2129. bpy.types.Lamp.shadowMap = bpy.props.EnumProperty(
  2130. name='Shadow Map',
  2131. description='',
  2132. items = ((NO_SHADOWS , 'None' , 'No Shadow Maps'),
  2133. (STD_SHADOWS , 'Standard' , 'Use Standard Shadow Maps'),
  2134. (POISSON_SHADOWS , 'Poisson' , 'Use Poisson Sampling'),
  2135. (VARIANCE_SHADOWS , 'Variance' , 'Use Variance Shadow Maps'),
  2136. (BLUR_VARIANCE_SHADOWS, 'Blur Variance', 'Use Blur Variance Shadow Maps')
  2137. ),
  2138. default = NO_SHADOWS
  2139. )
  2140. bpy.types.Lamp.shadowMapSize = bpy.props.IntProperty(
  2141. name='Shadow Map Size',
  2142. description='',
  2143. default = 512
  2144. )
  2145. bpy.types.Lamp.shadowBias = bpy.props.FloatProperty(
  2146. name='Shadow Bias',
  2147. description='',
  2148. default = 0.00005
  2149. )
  2150. bpy.types.Lamp.shadowBlurScale = bpy.props.IntProperty(
  2151. name='Blur Scale',
  2152. description='',
  2153. default = 2
  2154. )
  2155. bpy.types.Lamp.shadowBlurBoxOffset = bpy.props.IntProperty(
  2156. name='Blur Box Offset',
  2157. description='',
  2158. default = 0
  2159. )
  2160. class ObjectPanel(bpy.types.Panel):
  2161. bl_label = 'Babylon.js'
  2162. bl_space_type = 'PROPERTIES'
  2163. bl_region_type = 'WINDOW'
  2164. bl_context = 'data'
  2165. def draw(self, context):
  2166. ob = context.object
  2167. if not ob or not ob.data:
  2168. return
  2169. layout = self.layout
  2170. isMesh = isinstance(ob.data, bpy.types.Mesh)
  2171. isCamera = isinstance(ob.data, bpy.types.Camera)
  2172. isLight = isinstance(ob.data, bpy.types.Lamp)
  2173. if isMesh:
  2174. row = layout.row()
  2175. row.prop(ob.data, 'useFlatShading')
  2176. row.prop(ob.data, 'checkCollisions')
  2177. row = layout.row()
  2178. row.prop(ob.data, 'castShadows')
  2179. row.prop(ob.data, 'receiveShadows')
  2180. row = layout.row()
  2181. row.prop(ob.data, 'freezeWorldMatrix')
  2182. row.prop(ob.data, 'loadDisabled')
  2183. layout.prop(ob.data, 'autoAnimate')
  2184. layout.prop(ob.data, 'maxInfluencers')
  2185. box = layout.box()
  2186. box.label('Materials')
  2187. box.prop(ob.data, 'materialNameSpace')
  2188. box.prop(ob.data, 'checkReadyOnlyOnce')
  2189. box = layout.box()
  2190. box.label(text='Procedural Texture / Cycles Baking')
  2191. box.prop(ob.data, 'bakeSize')
  2192. box.prop(ob.data, 'bakeQuality')
  2193. box = layout.box()
  2194. box.prop(ob.data, 'attachedSound')
  2195. box.prop(ob.data, 'autoPlaySound')
  2196. box.prop(ob.data, 'loopSound')
  2197. box.prop(ob.data, 'maxSoundDistance')
  2198. elif isCamera:
  2199. layout.prop(ob.data, 'CameraType')
  2200. layout.prop(ob.data, 'checkCollisions')
  2201. layout.prop(ob.data, 'applyGravity')
  2202. layout.prop(ob.data, 'ellipsoid')
  2203. box = layout.box()
  2204. box.label(text="3D Camera Rigs")
  2205. box.prop(ob.data, 'Camera3DRig')
  2206. box.prop(ob.data, 'interaxialDistance')
  2207. layout.prop(ob.data, 'autoAnimate')
  2208. elif isLight:
  2209. layout.prop(ob.data, 'shadowMap')
  2210. layout.prop(ob.data, 'shadowMapSize')
  2211. layout.prop(ob.data, 'shadowBias')
  2212. box = layout.box()
  2213. box.label(text="Blur Variance Shadows")
  2214. box.prop(ob.data, 'shadowBlurScale')
  2215. box.prop(ob.data, 'shadowBlurBoxOffset')
  2216. layout.prop(ob.data, 'autoAnimate')