io_export_babylon.py 121 KB

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