io_export_babylon.py 122 KB

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