convert_to_threejs.py 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183
  1. # @author zfedoran / http://github.com/zfedoran
  2. import os
  3. import sys
  4. import math
  5. import operator
  6. import re
  7. import json
  8. import types
  9. import shutil
  10. # #####################################################
  11. # Globals
  12. # #####################################################
  13. option_triangulate = True
  14. option_textures = True
  15. option_copy_textures = True
  16. option_prefix = True
  17. option_geometry = False
  18. option_default_camera = False
  19. option_default_light = False
  20. option_pretty_print = False
  21. converter = None
  22. inputFolder = ""
  23. outputFolder = ""
  24. # #####################################################
  25. # Pretty Printing Hacks
  26. # #####################################################
  27. # Force an array to be printed fully on a single line
  28. class NoIndent(object):
  29. def __init__(self, value, separator = ','):
  30. self.separator = separator
  31. self.value = value
  32. def encode(self):
  33. if not self.value:
  34. return None
  35. return '[ %s ]' % self.separator.join(str(f) for f in self.value)
  36. # Force an array into chunks rather than printing each element on a new line
  37. class ChunkedIndent(object):
  38. def __init__(self, value, chunk_size = 15, force_rounding = False):
  39. self.value = value
  40. self.size = chunk_size
  41. self.force_rounding = force_rounding
  42. def encode(self):
  43. # Turn the flat array into an array of arrays where each subarray is of
  44. # length chunk_size. Then string concat the values in the chunked
  45. # arrays, delimited with a ', ' and round the values finally append
  46. # '{CHUNK}' so that we can find the strings with regex later
  47. if not self.value:
  48. return None
  49. if self.force_rounding:
  50. return ['{CHUNK}%s' % ', '.join(str(round(f, 6)) for f in self.value[i:i+self.size]) for i in range(0, len(self.value), self.size)]
  51. else:
  52. return ['{CHUNK}%s' % ', '.join(str(f) for f in self.value[i:i+self.size]) for i in range(0, len(self.value), self.size)]
  53. # This custom encoder looks for instances of NoIndent or ChunkedIndent.
  54. # When it finds
  55. class CustomEncoder(json.JSONEncoder):
  56. def default(self, obj):
  57. if isinstance(obj, NoIndent) or isinstance(obj, ChunkedIndent):
  58. return obj.encode()
  59. else:
  60. return json.JSONEncoder.default(self, obj)
  61. def executeRegexHacks(output_string):
  62. # turn strings of arrays into arrays (remove the double quotes)
  63. output_string = re.sub(':\s*\"(\[.*\])\"', r': \1', output_string)
  64. output_string = re.sub('(\n\s*)\"(\[.*\])\"', r'\1\2', output_string)
  65. output_string = re.sub('(\n\s*)\"{CHUNK}(.*)\"', r'\1\2', output_string)
  66. # replace '0metadata' with metadata
  67. output_string = re.sub('0metadata', r'metadata', output_string)
  68. # replace 'zchildren' with children
  69. output_string = re.sub('zchildren', r'children', output_string)
  70. # add an extra newline after '"children": {'
  71. output_string = re.sub('(children.*{\s*\n)', r'\1\n', output_string)
  72. # add an extra newline after '},'
  73. output_string = re.sub('},\s*\n', r'},\n\n', output_string)
  74. # add an extra newline after '\n\s*],'
  75. output_string = re.sub('(\n\s*)],\s*\n', r'\1],\n\n', output_string)
  76. return output_string
  77. # #####################################################
  78. # Object Serializers
  79. # #####################################################
  80. # FbxVector2 is not JSON serializable
  81. def serializeVector2(v, round_vector = False):
  82. # JSON does not support NaN or Inf
  83. if math.isnan(v[0]) or math.isinf(v[0]):
  84. v[0] = 0
  85. if math.isnan(v[1]) or math.isinf(v[1]):
  86. v[1] = 0
  87. if round_vector or option_pretty_print:
  88. v = (round(v[0], 5), round(v[1], 5))
  89. if option_pretty_print:
  90. return NoIndent([v[0], v[1]], ', ')
  91. else:
  92. return [v[0], v[1]]
  93. # FbxVector3 is not JSON serializable
  94. def serializeVector3(v, round_vector = False):
  95. # JSON does not support NaN or Inf
  96. if math.isnan(v[0]) or math.isinf(v[0]):
  97. v[0] = 0
  98. if math.isnan(v[1]) or math.isinf(v[1]):
  99. v[1] = 0
  100. if math.isnan(v[2]) or math.isinf(v[2]):
  101. v[2] = 0
  102. if round_vector or option_pretty_print:
  103. v = (round(v[0], 5), round(v[1], 5), round(v[2], 5))
  104. if option_pretty_print:
  105. return NoIndent([v[0], v[1], v[2]], ', ')
  106. else:
  107. return [v[0], v[1], v[2]]
  108. # FbxVector4 is not JSON serializable
  109. def serializeVector4(v, round_vector = False):
  110. # JSON does not support NaN or Inf
  111. if math.isnan(v[0]) or math.isinf(v[0]):
  112. v[0] = 0
  113. if math.isnan(v[1]) or math.isinf(v[1]):
  114. v[1] = 0
  115. if math.isnan(v[2]) or math.isinf(v[2]):
  116. v[2] = 0
  117. if math.isnan(v[3]) or math.isinf(v[3]):
  118. v[3] = 0
  119. if round_vector or option_pretty_print:
  120. v = (round(v[0], 5), round(v[1], 5), round(v[2], 5), round(v[3], 5))
  121. if option_pretty_print:
  122. return NoIndent([v[0], v[1], v[2], v[3]], ', ')
  123. else:
  124. return [v[0], v[1], v[2], v[3]]
  125. # #####################################################
  126. # Helpers
  127. # #####################################################
  128. def getRadians(v):
  129. return ((v[0]*math.pi)/180, (v[1]*math.pi)/180, (v[2]*math.pi)/180)
  130. def getHex(c):
  131. color = (int(c[0]*255) << 16) + (int(c[1]*255) << 8) + int(c[2]*255)
  132. return int(color)
  133. def setBit(value, position, on):
  134. if on:
  135. mask = 1 << position
  136. return (value | mask)
  137. else:
  138. mask = ~(1 << position)
  139. return (value & mask)
  140. def generate_uvs(uv_layers):
  141. layers = []
  142. for uvs in uv_layers:
  143. tmp = []
  144. for uv in uvs:
  145. tmp.append(uv[0])
  146. tmp.append(uv[1])
  147. if option_pretty_print:
  148. layer = ChunkedIndent(tmp)
  149. else:
  150. layer = tmp
  151. layers.append(layer)
  152. return layers
  153. # #####################################################
  154. # Object Name Helpers
  155. # #####################################################
  156. def hasUniqueName(o, class_id):
  157. scene = o.GetScene()
  158. object_name = o.GetName()
  159. object_id = o.GetUniqueID()
  160. object_count = scene.GetSrcObjectCount(class_id)
  161. for i in range(object_count):
  162. other = scene.GetSrcObject(class_id, i)
  163. other_id = other.GetUniqueID()
  164. other_name = other.GetName()
  165. if other_id == object_id:
  166. continue
  167. if other_name == object_name:
  168. return False
  169. return True
  170. def getObjectName(o, force_prefix = False):
  171. if not o:
  172. return ""
  173. object_name = o.GetName()
  174. object_id = o.GetUniqueID()
  175. if not force_prefix:
  176. force_prefix = not hasUniqueName(o, FbxNode.ClassId)
  177. prefix = ""
  178. if option_prefix or force_prefix:
  179. prefix = "Object_%s_" % object_id
  180. return prefix + object_name
  181. def getMaterialName(o, force_prefix = False):
  182. object_name = o.GetName()
  183. object_id = o.GetUniqueID()
  184. if not force_prefix:
  185. force_prefix = not hasUniqueName(o, FbxSurfaceMaterial.ClassId)
  186. prefix = ""
  187. if option_prefix or force_prefix:
  188. prefix = "Material_%s_" % object_id
  189. return prefix + object_name
  190. def getTextureName(t, force_prefix = False):
  191. if type(t) is FbxFileTexture:
  192. texture_file = t.GetFileName()
  193. texture_id = os.path.splitext(os.path.basename(texture_file))[0]
  194. else:
  195. texture_id = t.GetName()
  196. if texture_id == "_empty_":
  197. texture_id = ""
  198. prefix = ""
  199. if option_prefix or force_prefix:
  200. prefix = "Texture_%s_" % t.GetUniqueID()
  201. if len(texture_id) == 0:
  202. prefix = prefix[0:len(prefix)-1]
  203. return prefix + texture_id
  204. def getMtlTextureName(texture_name, texture_id, force_prefix = False):
  205. texture_name = os.path.splitext(texture_name)[0]
  206. prefix = ""
  207. if option_prefix or force_prefix:
  208. prefix = "Texture_%s_" % texture_id
  209. return prefix + texture_name
  210. def getPrefixedName(o, prefix):
  211. return (prefix + '_%s_') % o.GetUniqueID() + o.GetName()
  212. # #####################################################
  213. # Triangulation
  214. # #####################################################
  215. def triangulate_node_hierarchy(node):
  216. node_attribute = node.GetNodeAttribute();
  217. if node_attribute:
  218. if node_attribute.GetAttributeType() == FbxNodeAttribute.eMesh or \
  219. node_attribute.GetAttributeType() == FbxNodeAttribute.eNurbs or \
  220. node_attribute.GetAttributeType() == FbxNodeAttribute.eNurbsSurface or \
  221. node_attribute.GetAttributeType() == FbxNodeAttribute.ePatch:
  222. converter.TriangulateInPlace(node);
  223. child_count = node.GetChildCount()
  224. for i in range(child_count):
  225. triangulate_node_hierarchy(node.GetChild(i))
  226. def triangulate_scene(scene):
  227. node = scene.GetRootNode()
  228. if node:
  229. for i in range(node.GetChildCount()):
  230. triangulate_node_hierarchy(node.GetChild(i))
  231. # #####################################################
  232. # Generate Material Object
  233. # #####################################################
  234. def generate_texture_bindings(material_property, material_params):
  235. # FBX to Three.js texture types
  236. binding_types = {
  237. "DiffuseColor": "map",
  238. "DiffuseFactor": "diffuseFactor",
  239. "EmissiveColor": "emissiveMap",
  240. "EmissiveFactor": "emissiveFactor",
  241. "AmbientColor": "lightMap", # "ambientMap",
  242. "AmbientFactor": "ambientFactor",
  243. "SpecularColor": "specularMap",
  244. "SpecularFactor": "specularFactor",
  245. "ShininessExponent": "shininessExponent",
  246. "NormalMap": "normalMap",
  247. "Bump": "bumpMap",
  248. "TransparentColor": "transparentMap",
  249. "TransparencyFactor": "transparentFactor",
  250. "ReflectionColor": "reflectionMap",
  251. "ReflectionFactor": "reflectionFactor",
  252. "DisplacementColor": "displacementMap",
  253. "VectorDisplacementColor": "vectorDisplacementMap"
  254. }
  255. if material_property.IsValid():
  256. #Here we have to check if it's layeredtextures, or just textures:
  257. layered_texture_count = material_property.GetSrcObjectCount(FbxLayeredTexture.ClassId)
  258. if layered_texture_count > 0:
  259. for j in range(layered_texture_count):
  260. layered_texture = material_property.GetSrcObject(FbxLayeredTexture.ClassId, j)
  261. texture_count = layered_texture.GetSrcObjectCount(FbxTexture.ClassId)
  262. for k in range(texture_count):
  263. texture = layered_texture.GetSrcObject(FbxTexture.ClassId,k)
  264. if texture:
  265. texture_id = getTextureName(texture, True)
  266. material_params[binding_types[str(material_property.GetName())]] = texture_id
  267. else:
  268. # no layered texture simply get on the property
  269. texture_count = material_property.GetSrcObjectCount(FbxTexture.ClassId)
  270. for j in range(texture_count):
  271. texture = material_property.GetSrcObject(FbxTexture.ClassId,j)
  272. if texture:
  273. texture_id = getTextureName(texture, True)
  274. material_params[binding_types[str(material_property.GetName())]] = texture_id
  275. def generate_material_object(material):
  276. #Get the implementation to see if it's a hardware shader.
  277. implementation = GetImplementation(material, "ImplementationHLSL")
  278. implementation_type = "HLSL"
  279. if not implementation:
  280. implementation = GetImplementation(material, "ImplementationCGFX")
  281. implementation_type = "CGFX"
  282. output = None
  283. material_params = None
  284. material_type = None
  285. if implementation:
  286. print("Shader materials are not supported")
  287. elif material.GetClassId().Is(FbxSurfaceLambert.ClassId):
  288. ambient = getHex(material.Ambient.Get())
  289. diffuse = getHex(material.Diffuse.Get())
  290. emissive = getHex(material.Emissive.Get())
  291. opacity = 1.0 - material.TransparencyFactor.Get()
  292. opacity = 1.0 if opacity == 0 else opacity
  293. opacity = opacity
  294. transparent = False
  295. reflectivity = 1
  296. material_type = 'MeshBasicMaterial'
  297. # material_type = 'MeshLambertMaterial'
  298. material_params = {
  299. 'color' : diffuse,
  300. 'ambient' : ambient,
  301. 'emissive' : emissive,
  302. 'reflectivity' : reflectivity,
  303. 'transparent' : transparent,
  304. 'opacity' : opacity
  305. }
  306. elif material.GetClassId().Is(FbxSurfacePhong.ClassId):
  307. ambient = getHex(material.Ambient.Get())
  308. diffuse = getHex(material.Diffuse.Get())
  309. emissive = getHex(material.Emissive.Get())
  310. specular = getHex(material.Specular.Get())
  311. opacity = 1.0 - material.TransparencyFactor.Get()
  312. opacity = 1.0 if opacity == 0 else opacity
  313. opacity = opacity
  314. shininess = material.Shininess.Get()
  315. transparent = False
  316. reflectivity = 1
  317. bumpScale = 1
  318. material_type = 'MeshPhongMaterial'
  319. material_params = {
  320. 'color' : diffuse,
  321. 'ambient' : ambient,
  322. 'emissive' : emissive,
  323. 'specular' : specular,
  324. 'shininess' : shininess,
  325. 'bumpScale' : bumpScale,
  326. 'reflectivity' : reflectivity,
  327. 'transparent' : transparent,
  328. 'opacity' : opacity
  329. }
  330. else:
  331. print "Unknown type of Material", getMaterialName(material)
  332. # default to Lambert Material if the current Material type cannot be handeled
  333. if not material_type:
  334. ambient = getHex((0,0,0))
  335. diffuse = getHex((0.5,0.5,0.5))
  336. emissive = getHex((0,0,0))
  337. opacity = 1
  338. transparent = False
  339. reflectivity = 1
  340. material_type = 'MeshLambertMaterial'
  341. material_params = {
  342. 'color' : diffuse,
  343. 'ambient' : ambient,
  344. 'emissive' : emissive,
  345. 'reflectivity' : reflectivity,
  346. 'transparent' : transparent,
  347. 'opacity' : opacity
  348. }
  349. if option_textures:
  350. texture_count = FbxLayerElement.sTypeTextureCount()
  351. for texture_index in range(texture_count):
  352. material_property = material.FindProperty(FbxLayerElement.sTextureChannelNames(texture_index))
  353. generate_texture_bindings(material_property, material_params)
  354. material_params['wireframe'] = False
  355. material_params['wireframeLinewidth'] = 1
  356. output = {
  357. 'type' : material_type,
  358. 'parameters' : material_params
  359. }
  360. return output
  361. def generate_proxy_material_object(node, material_names):
  362. material_type = 'MeshFaceMaterial'
  363. material_params = {
  364. 'materials' : material_names
  365. }
  366. output = {
  367. 'type' : material_type,
  368. 'parameters' : material_params
  369. }
  370. return output
  371. # #####################################################
  372. # Find Scene Materials
  373. # #####################################################
  374. def extract_materials_from_node(node, material_dict):
  375. name = node.GetName()
  376. mesh = node.GetNodeAttribute()
  377. node = None
  378. if mesh:
  379. node = mesh.GetNode()
  380. if node:
  381. material_count = node.GetMaterialCount()
  382. material_names = []
  383. for l in range(mesh.GetLayerCount()):
  384. materials = mesh.GetLayer(l).GetMaterials()
  385. if materials:
  386. if materials.GetReferenceMode() == FbxLayerElement.eIndex:
  387. #Materials are in an undefined external table
  388. continue
  389. for i in range(material_count):
  390. material = node.GetMaterial(i)
  391. material_names.append(getMaterialName(material))
  392. if material_count > 1:
  393. proxy_material = generate_proxy_material_object(node, material_names)
  394. proxy_name = getMaterialName(node, True)
  395. material_dict[proxy_name] = proxy_material
  396. def generate_materials_from_hierarchy(node, material_dict):
  397. if node.GetNodeAttribute() == None:
  398. pass
  399. else:
  400. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  401. if attribute_type == FbxNodeAttribute.eMesh:
  402. extract_materials_from_node(node, material_dict)
  403. for i in range(node.GetChildCount()):
  404. generate_materials_from_hierarchy(node.GetChild(i), material_dict)
  405. def generate_material_dict(scene):
  406. material_dict = {}
  407. # generate all materials for this scene
  408. material_count = scene.GetSrcObjectCount(FbxSurfaceMaterial.ClassId)
  409. for i in range(material_count):
  410. material = scene.GetSrcObject(FbxSurfaceMaterial.ClassId, i)
  411. material_object = generate_material_object(material)
  412. material_name = getMaterialName(material)
  413. material_dict[material_name] = material_object
  414. # generate material porxies
  415. # Three.js does not support meshs with multiple materials, however it does
  416. # support materials with multiple submaterials
  417. node = scene.GetRootNode()
  418. if node:
  419. for i in range(node.GetChildCount()):
  420. generate_materials_from_hierarchy(node.GetChild(i), material_dict)
  421. return material_dict
  422. # #####################################################
  423. # Generate Texture Object
  424. # #####################################################
  425. def generate_texture_object(texture):
  426. #TODO: extract more texture properties
  427. wrap_u = texture.GetWrapModeU()
  428. wrap_v = texture.GetWrapModeV()
  429. offset = texture.GetUVTranslation()
  430. if type(texture) is FbxFileTexture:
  431. url = texture.GetFileName()
  432. else:
  433. url = getTextureName( texture )
  434. #url = replace_inFolder2OutFolder( url )
  435. #print( url )
  436. index = url.rfind( '/' )
  437. if index == -1:
  438. index = url.rfind( '\\' )
  439. filename = url[ index+1 : len(url) ]
  440. output = {
  441. 'url': filename,
  442. 'fullpath': url,
  443. 'repeat': serializeVector2( (1,1) ),
  444. 'offset': serializeVector2( texture.GetUVTranslation() ),
  445. 'magFilter': 'LinearFilter',
  446. 'minFilter': 'LinearMipMapLinearFilter',
  447. 'anisotropy': True
  448. }
  449. return output
  450. # #####################################################
  451. # Replace Texture input path to output
  452. # #####################################################
  453. def replace_inFolder2OutFolder(url):
  454. folderIndex = url.find(inputFolder)
  455. if folderIndex != -1:
  456. url = url[ folderIndex+len(inputFolder): ]
  457. url = outputFolder + url
  458. return url
  459. # #####################################################
  460. # Replace Texture output path to input
  461. # #####################################################
  462. def replace_OutFolder2inFolder(url):
  463. folderIndex = url.find(outputFolder)
  464. if folderIndex != -1:
  465. url = url[ folderIndex+len(outputFolder): ]
  466. url = inputFolder + url
  467. return url
  468. # #####################################################
  469. # Find Scene Textures
  470. # #####################################################
  471. def extract_material_textures(material_property, texture_dict):
  472. if material_property.IsValid():
  473. #Here we have to check if it's layeredtextures, or just textures:
  474. layered_texture_count = material_property.GetSrcObjectCount(FbxLayeredTexture.ClassId)
  475. if layered_texture_count > 0:
  476. for j in range(layered_texture_count):
  477. layered_texture = material_property.GetSrcObject(FbxLayeredTexture.ClassId, j)
  478. texture_count = layered_texture.GetSrcObjectCount(FbxTexture.ClassId)
  479. for k in range(texture_count):
  480. texture = layered_texture.GetSrcObject(FbxTexture.ClassId,k)
  481. if texture:
  482. texture_object = generate_texture_object(texture)
  483. texture_name = getTextureName( texture, True )
  484. texture_dict[texture_name] = texture_object
  485. else:
  486. # no layered texture simply get on the property
  487. texture_count = material_property.GetSrcObjectCount(FbxTexture.ClassId)
  488. for j in range(texture_count):
  489. texture = material_property.GetSrcObject(FbxTexture.ClassId,j)
  490. if texture:
  491. texture_object = generate_texture_object(texture)
  492. texture_name = getTextureName( texture, True )
  493. texture_dict[texture_name] = texture_object
  494. def extract_textures_from_node(node, texture_dict):
  495. name = node.GetName()
  496. mesh = node.GetNodeAttribute()
  497. #for all materials attached to this mesh
  498. material_count = mesh.GetNode().GetSrcObjectCount(FbxSurfaceMaterial.ClassId)
  499. for material_index in range(material_count):
  500. material = mesh.GetNode().GetSrcObject(FbxSurfaceMaterial.ClassId, material_index)
  501. #go through all the possible textures types
  502. if material:
  503. texture_count = FbxLayerElement.sTypeTextureCount()
  504. for texture_index in range(texture_count):
  505. material_property = material.FindProperty(FbxLayerElement.sTextureChannelNames(texture_index))
  506. extract_material_textures(material_property, texture_dict)
  507. def generate_textures_from_hierarchy(node, texture_dict):
  508. if node.GetNodeAttribute() == None:
  509. pass
  510. else:
  511. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  512. if attribute_type == FbxNodeAttribute.eMesh:
  513. extract_textures_from_node(node, texture_dict)
  514. for i in range(node.GetChildCount()):
  515. generate_textures_from_hierarchy(node.GetChild(i), texture_dict)
  516. def generate_texture_dict(scene):
  517. if not option_textures:
  518. return {}
  519. texture_dict = {}
  520. node = scene.GetRootNode()
  521. if node:
  522. for i in range(node.GetChildCount()):
  523. generate_textures_from_hierarchy(node.GetChild(i), texture_dict)
  524. return texture_dict
  525. # #####################################################
  526. # Extract Fbx SDK Mesh Data
  527. # #####################################################
  528. def extract_fbx_vertex_positions(mesh):
  529. control_points_count = mesh.GetControlPointsCount()
  530. control_points = mesh.GetControlPoints()
  531. positions = []
  532. for i in range(control_points_count):
  533. tmp = control_points[i]
  534. tmp = [tmp[0], tmp[1], tmp[2]]
  535. positions.append(tmp)
  536. node = mesh.GetNode()
  537. if node:
  538. t = node.GeometricTranslation.Get()
  539. t = FbxVector4(t[0], t[1], t[2], 1)
  540. r = node.GeometricRotation.Get()
  541. r = FbxVector4(r[0], r[1], r[2], 1)
  542. s = node.GeometricScaling.Get()
  543. s = FbxVector4(s[0], s[1], s[2], 1)
  544. hasGeometricTransform = False
  545. if t[0] != 0 or t[1] != 0 or t[2] != 0 or \
  546. r[0] != 0 or r[1] != 0 or r[2] != 0 or \
  547. s[0] != 1 or s[1] != 1 or s[2] != 1:
  548. hasGeometricTransform = True
  549. if hasGeometricTransform:
  550. geo_transform = FbxMatrix(t,r,s)
  551. else:
  552. geo_transform = FbxMatrix()
  553. transform = None
  554. if option_geometry:
  555. # FbxMeshes are local to their node, we need the vertices in global space
  556. # when scene nodes are not exported
  557. transform = node.EvaluateGlobalTransform()
  558. transform = FbxMatrix(transform) * geo_transform
  559. elif hasGeometricTransform:
  560. transform = geo_transform
  561. if transform:
  562. for i in range(len(positions)):
  563. v = positions[i]
  564. position = FbxVector4(v[0], v[1], v[2])
  565. position = transform.MultNormalize(position)
  566. positions[i] = [position[0], position[1], position[2]]
  567. return positions
  568. def extract_fbx_vertex_normals(mesh):
  569. # eNone The mapping is undetermined.
  570. # eByControlPoint There will be one mapping coordinate for each surface control point/vertex.
  571. # eByPolygonVertex There will be one mapping coordinate for each vertex, for every polygon of which it is a part. This means that a vertex will have as many mapping coordinates as polygons of which it is a part.
  572. # eByPolygon There can be only one mapping coordinate for the whole polygon.
  573. # eByEdge There will be one mapping coordinate for each unique edge in the mesh. This is meant to be used with smoothing layer elements.
  574. # eAllSame There can be only one mapping coordinate for the whole surface.
  575. layered_normal_indices = []
  576. layered_normal_values = []
  577. poly_count = mesh.GetPolygonCount()
  578. control_points = mesh.GetControlPoints()
  579. for l in range(mesh.GetLayerCount()):
  580. mesh_normals = mesh.GetLayer(l).GetNormals()
  581. if not mesh_normals:
  582. continue
  583. normals_array = mesh_normals.GetDirectArray()
  584. normals_count = normals_array.GetCount()
  585. if normals_count == 0:
  586. continue
  587. normal_indices = []
  588. normal_values = []
  589. # values
  590. for i in range(normals_count):
  591. normal = normals_array.GetAt(i)
  592. normal = [normal[0], normal[1], normal[2]]
  593. normal_values.append(normal)
  594. node = mesh.GetNode()
  595. if node:
  596. t = node.GeometricTranslation.Get()
  597. t = FbxVector4(t[0], t[1], t[2], 1)
  598. r = node.GeometricRotation.Get()
  599. r = FbxVector4(r[0], r[1], r[2], 1)
  600. s = node.GeometricScaling.Get()
  601. s = FbxVector4(s[0], s[1], s[2], 1)
  602. hasGeometricTransform = False
  603. if t[0] != 0 or t[1] != 0 or t[2] != 0 or \
  604. r[0] != 0 or r[1] != 0 or r[2] != 0 or \
  605. s[0] != 1 or s[1] != 1 or s[2] != 1:
  606. hasGeometricTransform = True
  607. if hasGeometricTransform:
  608. geo_transform = FbxMatrix(t,r,s)
  609. else:
  610. geo_transform = FbxMatrix()
  611. transform = None
  612. if option_geometry:
  613. # FbxMeshes are local to their node, we need the vertices in global space
  614. # when scene nodes are not exported
  615. transform = node.EvaluateGlobalTransform()
  616. transform = FbxMatrix(transform) * geo_transform
  617. elif hasGeometricTransform:
  618. transform = geo_transform
  619. if transform:
  620. t = FbxVector4(0,0,0,1)
  621. transform.SetRow(3, t)
  622. for i in range(len(normal_values)):
  623. n = normal_values[i]
  624. normal = FbxVector4(n[0], n[1], n[2])
  625. normal = transform.MultNormalize(normal)
  626. normal.Normalize()
  627. normal = [normal[0], normal[1], normal[2]]
  628. normal_values[i] = normal
  629. # indices
  630. vertexId = 0
  631. for p in range(poly_count):
  632. poly_size = mesh.GetPolygonSize(p)
  633. poly_normals = []
  634. for v in range(poly_size):
  635. control_point_index = mesh.GetPolygonVertex(p, v)
  636. # mapping mode is by control points. The mesh should be smooth and soft.
  637. # we can get normals by retrieving each control point
  638. if mesh_normals.GetMappingMode() == FbxLayerElement.eByControlPoint:
  639. # reference mode is direct, the normal index is same as vertex index.
  640. # get normals by the index of control vertex
  641. if mesh_normals.GetReferenceMode() == FbxLayerElement.eDirect:
  642. poly_normals.append(control_point_index)
  643. elif mesh_normals.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  644. index = mesh_normals.GetIndexArray().GetAt(control_point_index)
  645. poly_normals.append(index)
  646. # mapping mode is by polygon-vertex.
  647. # we can get normals by retrieving polygon-vertex.
  648. elif mesh_normals.GetMappingMode() == FbxLayerElement.eByPolygonVertex:
  649. if mesh_normals.GetReferenceMode() == FbxLayerElement.eDirect:
  650. poly_normals.append(vertexId)
  651. elif mesh_normals.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  652. index = mesh_normals.GetIndexArray().GetAt(vertexId)
  653. poly_normals.append(index)
  654. elif mesh_normals.GetMappingMode() == FbxLayerElement.eByPolygon or \
  655. mesh_normals.GetMappingMode() == FbxLayerElement.eAllSame or \
  656. mesh_normals.GetMappingMode() == FbxLayerElement.eNone:
  657. print("unsupported normal mapping mode for polygon vertex")
  658. vertexId += 1
  659. normal_indices.append(poly_normals)
  660. layered_normal_values.append(normal_values)
  661. layered_normal_indices.append(normal_indices)
  662. normal_values = []
  663. normal_indices = []
  664. # Three.js only supports one layer of normals
  665. if len(layered_normal_values) > 0:
  666. normal_values = layered_normal_values[0]
  667. normal_indices = layered_normal_indices[0]
  668. return normal_values, normal_indices
  669. def extract_fbx_vertex_colors(mesh):
  670. # eNone The mapping is undetermined.
  671. # eByControlPoint There will be one mapping coordinate for each surface control point/vertex.
  672. # eByPolygonVertex There will be one mapping coordinate for each vertex, for every polygon of which it is a part. This means that a vertex will have as many mapping coordinates as polygons of which it is a part.
  673. # eByPolygon There can be only one mapping coordinate for the whole polygon.
  674. # eByEdge There will be one mapping coordinate for each unique edge in the mesh. This is meant to be used with smoothing layer elements.
  675. # eAllSame There can be only one mapping coordinate for the whole surface.
  676. layered_color_indices = []
  677. layered_color_values = []
  678. poly_count = mesh.GetPolygonCount()
  679. control_points = mesh.GetControlPoints()
  680. for l in range(mesh.GetLayerCount()):
  681. mesh_colors = mesh.GetLayer(l).GetVertexColors()
  682. if not mesh_colors:
  683. continue
  684. colors_array = mesh_colors.GetDirectArray()
  685. colors_count = colors_array.GetCount()
  686. if colors_count == 0:
  687. continue
  688. color_indices = []
  689. color_values = []
  690. # values
  691. for i in range(colors_count):
  692. color = colors_array.GetAt(i)
  693. color = [color.mRed, color.mGreen, color.mBlue, color.mAlpha]
  694. color_values.append(color)
  695. # indices
  696. vertexId = 0
  697. for p in range(poly_count):
  698. poly_size = mesh.GetPolygonSize(p)
  699. poly_colors = []
  700. for v in range(poly_size):
  701. control_point_index = mesh.GetPolygonVertex(p, v)
  702. if mesh_colors.GetMappingMode() == FbxLayerElement.eByControlPoint:
  703. if mesh_colors.GetReferenceMode() == FbxLayerElement.eDirect:
  704. poly_colors.append(control_point_index)
  705. elif mesh_colors.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  706. index = mesh_colors.GetIndexArray().GetAt(control_point_index)
  707. poly_colors.append(index)
  708. elif mesh_colors.GetMappingMode() == FbxLayerElement.eByPolygonVertex:
  709. if mesh_colors.GetReferenceMode() == FbxLayerElement.eDirect:
  710. poly_colors.append(vertexId)
  711. elif mesh_colors.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  712. index = mesh_colors.GetIndexArray().GetAt(vertexId)
  713. poly_colors.append(index)
  714. elif mesh_colors.GetMappingMode() == FbxLayerElement.eByPolygon or \
  715. mesh_colors.GetMappingMode() == FbxLayerElement.eAllSame or \
  716. mesh_colors.GetMappingMode() == FbxLayerElement.eNone:
  717. print("unsupported color mapping mode for polygon vertex")
  718. vertexId += 1
  719. color_indices.append(poly_colors)
  720. layered_color_indices.append( color_indices )
  721. layered_color_values.append( color_values )
  722. color_values = []
  723. color_indices = []
  724. # Three.js only supports one layer of colors
  725. if len(layered_color_values) > 0:
  726. color_values = layered_color_values[0]
  727. color_indices = layered_color_indices[0]
  728. '''
  729. # The Fbx SDK defaults mesh.Color to (0.8, 0.8, 0.8)
  730. # This causes most models to receive incorrect vertex colors
  731. if len(color_values) == 0:
  732. color = mesh.Color.Get()
  733. color_values = [[color[0], color[1], color[2]]]
  734. color_indices = []
  735. for p in range(poly_count):
  736. poly_size = mesh.GetPolygonSize(p)
  737. color_indices.append([0] * poly_size)
  738. '''
  739. return color_values, color_indices
  740. def extract_fbx_vertex_uvs(mesh):
  741. # eNone The mapping is undetermined.
  742. # eByControlPoint There will be one mapping coordinate for each surface control point/vertex.
  743. # eByPolygonVertex There will be one mapping coordinate for each vertex, for every polygon of which it is a part. This means that a vertex will have as many mapping coordinates as polygons of which it is a part.
  744. # eByPolygon There can be only one mapping coordinate for the whole polygon.
  745. # eByEdge There will be one mapping coordinate for each unique edge in the mesh. This is meant to be used with smoothing layer elements.
  746. # eAllSame There can be only one mapping coordinate for the whole surface.
  747. layered_uv_indices = []
  748. layered_uv_values = []
  749. poly_count = mesh.GetPolygonCount()
  750. control_points = mesh.GetControlPoints()
  751. for l in range(mesh.GetLayerCount()):
  752. mesh_uvs = mesh.GetLayer(l).GetUVs()
  753. if not mesh_uvs:
  754. continue
  755. uvs_array = mesh_uvs.GetDirectArray()
  756. uvs_count = uvs_array.GetCount()
  757. if uvs_count == 0:
  758. continue
  759. uv_indices = []
  760. uv_values = []
  761. # values
  762. for i in range(uvs_count):
  763. uv = uvs_array.GetAt(i)
  764. uv = [uv[0], uv[1]]
  765. uv_values.append(uv)
  766. # indices
  767. vertexId = 0
  768. for p in range(poly_count):
  769. poly_size = mesh.GetPolygonSize(p)
  770. poly_uvs = []
  771. for v in range(poly_size):
  772. control_point_index = mesh.GetPolygonVertex(p, v)
  773. if mesh_uvs.GetMappingMode() == FbxLayerElement.eByControlPoint:
  774. if mesh_uvs.GetReferenceMode() == FbxLayerElement.eDirect:
  775. poly_uvs.append(control_point_index)
  776. elif mesh_uvs.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  777. index = mesh_uvs.GetIndexArray().GetAt(control_point_index)
  778. poly_uvs.append(index)
  779. elif mesh_uvs.GetMappingMode() == FbxLayerElement.eByPolygonVertex:
  780. uv_texture_index = mesh_uvs.GetIndexArray().GetAt(vertexId)
  781. if mesh_uvs.GetReferenceMode() == FbxLayerElement.eDirect or \
  782. mesh_uvs.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  783. poly_uvs.append(uv_texture_index)
  784. elif mesh_uvs.GetMappingMode() == FbxLayerElement.eByPolygon or \
  785. mesh_uvs.GetMappingMode() == FbxLayerElement.eAllSame or \
  786. mesh_uvs.GetMappingMode() == FbxLayerElement.eNone:
  787. print("unsupported uv mapping mode for polygon vertex")
  788. vertexId += 1
  789. uv_indices.append(poly_uvs)
  790. layered_uv_values.append(uv_values)
  791. layered_uv_indices.append(uv_indices)
  792. return layered_uv_values, layered_uv_indices
  793. # #####################################################
  794. # Process Mesh Geometry
  795. # #####################################################
  796. def generate_normal_key(normal):
  797. return (round(normal[0], 6), round(normal[1], 6), round(normal[2], 6))
  798. def generate_color_key(color):
  799. return getHex(color)
  800. def generate_uv_key(uv):
  801. return (round(uv[0], 6), round(uv[1], 6))
  802. def append_non_duplicate_uvs(source_uvs, dest_uvs, counts):
  803. source_layer_count = len(source_uvs)
  804. for layer_index in range(source_layer_count):
  805. dest_layer_count = len(dest_uvs)
  806. if dest_layer_count <= layer_index:
  807. dest_uv_layer = {}
  808. count = 0
  809. dest_uvs.append(dest_uv_layer)
  810. counts.append(count)
  811. else:
  812. dest_uv_layer = dest_uvs[layer_index]
  813. count = counts[layer_index]
  814. source_uv_layer = source_uvs[layer_index]
  815. for uv in source_uv_layer:
  816. key = generate_uv_key(uv)
  817. if key not in dest_uv_layer:
  818. dest_uv_layer[key] = count
  819. count += 1
  820. counts[layer_index] = count
  821. return counts
  822. def generate_unique_normals_dictionary(mesh_list):
  823. normals_dictionary = {}
  824. nnormals = 0
  825. # Merge meshes, remove duplicate data
  826. for mesh in mesh_list:
  827. node = mesh.GetNode()
  828. normal_values, normal_indices = extract_fbx_vertex_normals(mesh)
  829. if len(normal_values) > 0:
  830. for normal in normal_values:
  831. key = generate_normal_key(normal)
  832. if key not in normals_dictionary:
  833. normals_dictionary[key] = nnormals
  834. nnormals += 1
  835. return normals_dictionary
  836. def generate_unique_colors_dictionary(mesh_list):
  837. colors_dictionary = {}
  838. ncolors = 0
  839. # Merge meshes, remove duplicate data
  840. for mesh in mesh_list:
  841. color_values, color_indices = extract_fbx_vertex_colors(mesh)
  842. if len(color_values) > 0:
  843. for color in color_values:
  844. key = generate_color_key(color)
  845. if key not in colors_dictionary:
  846. colors_dictionary[key] = ncolors
  847. ncolors += 1
  848. return colors_dictionary
  849. def generate_unique_uvs_dictionary_layers(mesh_list):
  850. uvs_dictionary_layers = []
  851. nuvs_list = []
  852. # Merge meshes, remove duplicate data
  853. for mesh in mesh_list:
  854. uv_values, uv_indices = extract_fbx_vertex_uvs(mesh)
  855. if len(uv_values) > 0:
  856. nuvs_list = append_non_duplicate_uvs(uv_values, uvs_dictionary_layers, nuvs_list)
  857. return uvs_dictionary_layers
  858. def generate_normals_from_dictionary(normals_dictionary):
  859. normal_values = []
  860. for key, index in sorted(normals_dictionary.items(), key = operator.itemgetter(1)):
  861. normal_values.append(key)
  862. return normal_values
  863. def generate_colors_from_dictionary(colors_dictionary):
  864. color_values = []
  865. for key, index in sorted(colors_dictionary.items(), key = operator.itemgetter(1)):
  866. color_values.append(key)
  867. return color_values
  868. def generate_uvs_from_dictionary_layers(uvs_dictionary_layers):
  869. uv_values = []
  870. for uvs_dictionary in uvs_dictionary_layers:
  871. uv_values_layer = []
  872. for key, index in sorted(uvs_dictionary.items(), key = operator.itemgetter(1)):
  873. uv_values_layer.append(key)
  874. uv_values.append(uv_values_layer)
  875. return uv_values
  876. def generate_normal_indices_for_poly(poly_index, mesh_normal_values, mesh_normal_indices, normals_to_indices):
  877. if len(mesh_normal_indices) <= 0:
  878. return []
  879. poly_normal_indices = mesh_normal_indices[poly_index]
  880. poly_size = len(poly_normal_indices)
  881. output_poly_normal_indices = []
  882. for v in range(poly_size):
  883. normal_index = poly_normal_indices[v]
  884. normal_value = mesh_normal_values[normal_index]
  885. key = generate_normal_key(normal_value)
  886. output_index = normals_to_indices[key]
  887. output_poly_normal_indices.append(output_index)
  888. return output_poly_normal_indices
  889. def generate_color_indices_for_poly(poly_index, mesh_color_values, mesh_color_indices, colors_to_indices):
  890. if len(mesh_color_indices) <= 0:
  891. return []
  892. poly_color_indices = mesh_color_indices[poly_index]
  893. poly_size = len(poly_color_indices)
  894. output_poly_color_indices = []
  895. for v in range(poly_size):
  896. color_index = poly_color_indices[v]
  897. color_value = mesh_color_values[color_index]
  898. key = generate_color_key(color_value)
  899. output_index = colors_to_indices[key]
  900. output_poly_color_indices.append(output_index)
  901. return output_poly_color_indices
  902. def generate_uv_indices_for_poly(poly_index, mesh_uv_values, mesh_uv_indices, uvs_to_indices):
  903. if len(mesh_uv_indices) <= 0:
  904. return []
  905. poly_uv_indices = mesh_uv_indices[poly_index]
  906. poly_size = len(poly_uv_indices)
  907. output_poly_uv_indices = []
  908. for v in range(poly_size):
  909. uv_index = poly_uv_indices[v]
  910. uv_value = mesh_uv_values[uv_index]
  911. key = generate_uv_key(uv_value)
  912. output_index = uvs_to_indices[key]
  913. output_poly_uv_indices.append(output_index)
  914. return output_poly_uv_indices
  915. def process_mesh_vertices(mesh_list):
  916. vertex_offset = 0
  917. vertex_offset_list = [0]
  918. vertices = []
  919. for mesh in mesh_list:
  920. node = mesh.GetNode()
  921. mesh_vertices = extract_fbx_vertex_positions(mesh)
  922. vertices.extend(mesh_vertices[:])
  923. vertex_offset += len(mesh_vertices)
  924. vertex_offset_list.append(vertex_offset)
  925. return vertices, vertex_offset_list
  926. def process_mesh_materials(mesh_list):
  927. material_offset = 0
  928. material_offset_list = [0]
  929. materials_list = []
  930. #TODO: remove duplicate mesh references
  931. for mesh in mesh_list:
  932. node = mesh.GetNode()
  933. material_count = node.GetMaterialCount()
  934. if material_count > 0:
  935. for l in range(mesh.GetLayerCount()):
  936. materials = mesh.GetLayer(l).GetMaterials()
  937. if materials:
  938. if materials.GetReferenceMode() == FbxLayerElement.eIndex:
  939. #Materials are in an undefined external table
  940. continue
  941. for i in range(material_count):
  942. material = node.GetMaterial(i)
  943. materials_list.append( material )
  944. material_offset += material_count
  945. material_offset_list.append(material_offset)
  946. return materials_list, material_offset_list
  947. def process_mesh_polygons(mesh_list, normals_to_indices, colors_to_indices, uvs_to_indices_list, vertex_offset_list, material_offset_list):
  948. faces = []
  949. for mesh_index in range(len(mesh_list)):
  950. mesh = mesh_list[mesh_index]
  951. flipWindingOrder = False
  952. node = mesh.GetNode()
  953. if node:
  954. local_scale = node.EvaluateLocalScaling()
  955. if local_scale[0] < 0 or local_scale[1] < 0 or local_scale[2] < 0:
  956. flipWindingOrder = True
  957. poly_count = mesh.GetPolygonCount()
  958. control_points = mesh.GetControlPoints()
  959. normal_values, normal_indices = extract_fbx_vertex_normals(mesh)
  960. color_values, color_indices = extract_fbx_vertex_colors(mesh)
  961. uv_values_layers, uv_indices_layers = extract_fbx_vertex_uvs(mesh)
  962. for poly_index in range(poly_count):
  963. poly_size = mesh.GetPolygonSize(poly_index)
  964. face_normals = generate_normal_indices_for_poly(poly_index, normal_values, normal_indices, normals_to_indices)
  965. face_colors = generate_color_indices_for_poly(poly_index, color_values, color_indices, colors_to_indices)
  966. face_uv_layers = []
  967. for l in range(len(uv_indices_layers)):
  968. uv_values = uv_values_layers[l]
  969. uv_indices = uv_indices_layers[l]
  970. face_uv_indices = generate_uv_indices_for_poly(poly_index, uv_values, uv_indices, uvs_to_indices_list[l])
  971. face_uv_layers.append(face_uv_indices)
  972. face_vertices = []
  973. for vertex_index in range(poly_size):
  974. control_point_index = mesh.GetPolygonVertex(poly_index, vertex_index)
  975. face_vertices.append(control_point_index)
  976. #TODO: assign a default material to any mesh without one
  977. if len(material_offset_list) <= mesh_index:
  978. material_offset = 0
  979. else:
  980. material_offset = material_offset_list[mesh_index]
  981. vertex_offset = vertex_offset_list[mesh_index]
  982. if poly_size > 4:
  983. new_face_normals = []
  984. new_face_colors = []
  985. new_face_uv_layers = []
  986. for i in range(poly_size - 2):
  987. new_face_vertices = [face_vertices[0], face_vertices[i+1], face_vertices[i+2]]
  988. if len(face_normals):
  989. new_face_normals = [face_normals[0], face_normals[i+1], face_normals[i+2]]
  990. if len(face_colors):
  991. new_face_colors = [face_colors[0], face_colors[i+1], face_colors[i+2]]
  992. if len(face_uv_layers):
  993. new_face_uv_layers = []
  994. for layer in face_uv_layers:
  995. new_face_uv_layers.append([layer[0], layer[i+1], layer[i+2]])
  996. face = generate_mesh_face(mesh,
  997. poly_index,
  998. new_face_vertices,
  999. new_face_normals,
  1000. new_face_colors,
  1001. new_face_uv_layers,
  1002. vertex_offset,
  1003. material_offset,
  1004. flipWindingOrder)
  1005. faces.append(face)
  1006. else:
  1007. face = generate_mesh_face(mesh,
  1008. poly_index,
  1009. face_vertices,
  1010. face_normals,
  1011. face_colors,
  1012. face_uv_layers,
  1013. vertex_offset,
  1014. material_offset,
  1015. flipWindingOrder)
  1016. faces.append(face)
  1017. return faces
  1018. def generate_mesh_face(mesh, polygon_index, vertex_indices, normals, colors, uv_layers, vertex_offset, material_offset, flipOrder):
  1019. isTriangle = ( len(vertex_indices) == 3 )
  1020. nVertices = 3 if isTriangle else 4
  1021. hasMaterial = False
  1022. for l in range(mesh.GetLayerCount()):
  1023. materials = mesh.GetLayer(l).GetMaterials()
  1024. if materials:
  1025. hasMaterial = True
  1026. break
  1027. hasFaceUvs = False
  1028. hasFaceVertexUvs = len(uv_layers) > 0
  1029. hasFaceNormals = False
  1030. hasFaceVertexNormals = len(normals) > 0
  1031. hasFaceColors = False
  1032. hasFaceVertexColors = len(colors) > 0
  1033. faceType = 0
  1034. faceType = setBit(faceType, 0, not isTriangle)
  1035. faceType = setBit(faceType, 1, hasMaterial)
  1036. faceType = setBit(faceType, 2, hasFaceUvs)
  1037. faceType = setBit(faceType, 3, hasFaceVertexUvs)
  1038. faceType = setBit(faceType, 4, hasFaceNormals)
  1039. faceType = setBit(faceType, 5, hasFaceVertexNormals)
  1040. faceType = setBit(faceType, 6, hasFaceColors)
  1041. faceType = setBit(faceType, 7, hasFaceVertexColors)
  1042. faceData = []
  1043. # order is important, must match order in JSONLoader
  1044. # face type
  1045. # vertex indices
  1046. # material index
  1047. # face uvs index
  1048. # face vertex uvs indices
  1049. # face color index
  1050. # face vertex colors indices
  1051. faceData.append(faceType)
  1052. if flipOrder:
  1053. if nVertices == 3:
  1054. vertex_indices = [vertex_indices[0], vertex_indices[2], vertex_indices[1]]
  1055. if hasFaceVertexNormals:
  1056. normals = [normals[0], normals[2], normals[1]]
  1057. if hasFaceVertexColors:
  1058. colors = [colors[0], colors[2], colors[1]]
  1059. if hasFaceVertexUvs:
  1060. tmp = []
  1061. for polygon_uvs in uv_layers:
  1062. tmp.append([polygon_uvs[0], polygon_uvs[2], polygon_uvs[1]])
  1063. uv_layers = tmp
  1064. else:
  1065. vertex_indices = [vertex_indices[0], vertex_indices[3], vertex_indices[2], vertex_indices[1]]
  1066. if hasFaceVertexNormals:
  1067. normals = [normals[0], normals[3], normals[2], normals[1]]
  1068. if hasFaceVertexColors:
  1069. colors = [colors[0], colors[3], colors[2], colors[1]]
  1070. if hasFaceVertexUvs:
  1071. tmp = []
  1072. for polygon_uvs in uv_layers:
  1073. tmp.append([polygon_uvs[0], polygon_uvs[3], polygon_uvs[2], polygon_uvs[3]])
  1074. uv_layers = tmp
  1075. for i in range(nVertices):
  1076. index = vertex_indices[i] + vertex_offset
  1077. faceData.append(index)
  1078. if hasMaterial:
  1079. material_id = 0
  1080. for l in range(mesh.GetLayerCount()):
  1081. materials = mesh.GetLayer(l).GetMaterials()
  1082. if materials:
  1083. material_id = materials.GetIndexArray().GetAt(polygon_index)
  1084. break
  1085. material_id += material_offset
  1086. faceData.append( material_id )
  1087. if hasFaceVertexUvs:
  1088. for polygon_uvs in uv_layers:
  1089. for i in range(nVertices):
  1090. index = polygon_uvs[i]
  1091. faceData.append(index)
  1092. if hasFaceVertexNormals:
  1093. for i in range(nVertices):
  1094. index = normals[i]
  1095. faceData.append(index)
  1096. if hasFaceVertexColors:
  1097. for i in range(nVertices):
  1098. index = colors[i]
  1099. faceData.append(index)
  1100. return faceData
  1101. # #####################################################
  1102. # Generate Mesh Object (for scene output format)
  1103. # #####################################################
  1104. def generate_scene_output(node):
  1105. mesh = node.GetNodeAttribute()
  1106. # This is done in order to keep the scene output and non-scene output code DRY
  1107. mesh_list = [ mesh ]
  1108. # Extract the mesh data into arrays
  1109. vertices, vertex_offsets = process_mesh_vertices(mesh_list)
  1110. materials, material_offsets = process_mesh_materials(mesh_list)
  1111. normals_to_indices = generate_unique_normals_dictionary(mesh_list)
  1112. colors_to_indices = generate_unique_colors_dictionary(mesh_list)
  1113. uvs_to_indices_list = generate_unique_uvs_dictionary_layers(mesh_list)
  1114. normal_values = generate_normals_from_dictionary(normals_to_indices)
  1115. color_values = generate_colors_from_dictionary(colors_to_indices)
  1116. uv_values = generate_uvs_from_dictionary_layers(uvs_to_indices_list)
  1117. # Generate mesh faces for the Three.js file format
  1118. faces = process_mesh_polygons(mesh_list,
  1119. normals_to_indices,
  1120. colors_to_indices,
  1121. uvs_to_indices_list,
  1122. vertex_offsets,
  1123. material_offsets)
  1124. # Generate counts for uvs, vertices, normals, colors, and faces
  1125. nuvs = []
  1126. for layer_index, uvs in enumerate(uv_values):
  1127. nuvs.append(str(len(uvs)))
  1128. nvertices = len(vertices)
  1129. nnormals = len(normal_values)
  1130. ncolors = len(color_values)
  1131. nfaces = len(faces)
  1132. # Flatten the arrays, currently they are in the form of [[0, 1, 2], [3, 4, 5], ...]
  1133. vertices = [val for v in vertices for val in v]
  1134. normal_values = [val for n in normal_values for val in n]
  1135. color_values = [c for c in color_values]
  1136. faces = [val for f in faces for val in f]
  1137. uv_values = generate_uvs(uv_values)
  1138. # Disable automatic json indenting when pretty printing for the arrays
  1139. if option_pretty_print:
  1140. nuvs = NoIndent(nuvs)
  1141. vertices = ChunkedIndent(vertices, 15, True)
  1142. normal_values = ChunkedIndent(normal_values, 15, True)
  1143. color_values = ChunkedIndent(color_values, 15)
  1144. faces = ChunkedIndent(faces, 30)
  1145. metadata = {
  1146. 'vertices' : nvertices,
  1147. 'normals' : nnormals,
  1148. 'colors' : ncolors,
  1149. 'faces' : nfaces,
  1150. 'uvs' : nuvs
  1151. }
  1152. output = {
  1153. 'scale' : 1,
  1154. 'materials' : [],
  1155. 'vertices' : vertices,
  1156. 'normals' : [] if nnormals <= 0 else normal_values,
  1157. 'colors' : [] if ncolors <= 0 else color_values,
  1158. 'uvs' : uv_values,
  1159. 'faces' : faces
  1160. }
  1161. if option_pretty_print:
  1162. output['0metadata'] = metadata
  1163. else:
  1164. output['metadata'] = metadata
  1165. return output
  1166. # #####################################################
  1167. # Generate Mesh Object (for non-scene output)
  1168. # #####################################################
  1169. def generate_non_scene_output(scene):
  1170. mesh_list = generate_mesh_list(scene)
  1171. # Extract the mesh data into arrays
  1172. vertices, vertex_offsets = process_mesh_vertices(mesh_list)
  1173. materials, material_offsets = process_mesh_materials(mesh_list)
  1174. normals_to_indices = generate_unique_normals_dictionary(mesh_list)
  1175. colors_to_indices = generate_unique_colors_dictionary(mesh_list)
  1176. uvs_to_indices_list = generate_unique_uvs_dictionary_layers(mesh_list)
  1177. normal_values = generate_normals_from_dictionary(normals_to_indices)
  1178. color_values = generate_colors_from_dictionary(colors_to_indices)
  1179. uv_values = generate_uvs_from_dictionary_layers(uvs_to_indices_list)
  1180. # Generate mesh faces for the Three.js file format
  1181. faces = process_mesh_polygons(mesh_list,
  1182. normals_to_indices,
  1183. colors_to_indices,
  1184. uvs_to_indices_list,
  1185. vertex_offsets,
  1186. material_offsets)
  1187. # Generate counts for uvs, vertices, normals, colors, and faces
  1188. nuvs = []
  1189. for layer_index, uvs in enumerate(uv_values):
  1190. nuvs.append(str(len(uvs)))
  1191. nvertices = len(vertices)
  1192. nnormals = len(normal_values)
  1193. ncolors = len(color_values)
  1194. nfaces = len(faces)
  1195. # Flatten the arrays, currently they are in the form of [[0, 1, 2], [3, 4, 5], ...]
  1196. vertices = [val for v in vertices for val in v]
  1197. normal_values = [val for n in normal_values for val in n]
  1198. color_values = [c for c in color_values]
  1199. faces = [val for f in faces for val in f]
  1200. uv_values = generate_uvs(uv_values)
  1201. # Disable json indenting when pretty printing for the arrays
  1202. if option_pretty_print:
  1203. nuvs = NoIndent(nuvs)
  1204. vertices = NoIndent(vertices)
  1205. normal_values = NoIndent(normal_values)
  1206. color_values = NoIndent(color_values)
  1207. faces = NoIndent(faces)
  1208. metadata = {
  1209. 'formatVersion' : 3,
  1210. 'type' : 'geometry',
  1211. 'generatedBy' : 'convert-to-threejs.py',
  1212. 'vertices' : nvertices,
  1213. 'normals' : nnormals,
  1214. 'colors' : ncolors,
  1215. 'faces' : nfaces,
  1216. 'uvs' : nuvs
  1217. }
  1218. output = {
  1219. 'scale' : 1,
  1220. 'materials' : [],
  1221. 'vertices' : vertices,
  1222. 'normals' : [] if nnormals <= 0 else normal_values,
  1223. 'colors' : [] if ncolors <= 0 else color_values,
  1224. 'uvs' : uv_values,
  1225. 'faces' : faces
  1226. }
  1227. if option_pretty_print:
  1228. output['0metadata'] = metadata
  1229. else:
  1230. output['metadata'] = metadata
  1231. return output
  1232. def generate_mesh_list_from_hierarchy(node, mesh_list):
  1233. if node.GetNodeAttribute() == None:
  1234. pass
  1235. else:
  1236. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  1237. if attribute_type == FbxNodeAttribute.eMesh or \
  1238. attribute_type == FbxNodeAttribute.eNurbs or \
  1239. attribute_type == FbxNodeAttribute.eNurbsSurface or \
  1240. attribute_type == FbxNodeAttribute.ePatch:
  1241. if attribute_type != FbxNodeAttribute.eMesh:
  1242. converter.TriangulateInPlace(node);
  1243. mesh_list.append(node.GetNodeAttribute())
  1244. for i in range(node.GetChildCount()):
  1245. generate_mesh_list_from_hierarchy(node.GetChild(i), mesh_list)
  1246. def generate_mesh_list(scene):
  1247. mesh_list = []
  1248. node = scene.GetRootNode()
  1249. if node:
  1250. for i in range(node.GetChildCount()):
  1251. generate_mesh_list_from_hierarchy(node.GetChild(i), mesh_list)
  1252. return mesh_list
  1253. # #####################################################
  1254. # Generate Embed Objects
  1255. # #####################################################
  1256. def generate_embed_dict_from_hierarchy(node, embed_dict):
  1257. if node.GetNodeAttribute() == None:
  1258. pass
  1259. else:
  1260. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  1261. if attribute_type == FbxNodeAttribute.eMesh or \
  1262. attribute_type == FbxNodeAttribute.eNurbs or \
  1263. attribute_type == FbxNodeAttribute.eNurbsSurface or \
  1264. attribute_type == FbxNodeAttribute.ePatch:
  1265. if attribute_type != FbxNodeAttribute.eMesh:
  1266. converter.TriangulateInPlace(node);
  1267. embed_object = generate_scene_output(node)
  1268. embed_name = getPrefixedName(node, 'Embed')
  1269. embed_dict[embed_name] = embed_object
  1270. for i in range(node.GetChildCount()):
  1271. generate_embed_dict_from_hierarchy(node.GetChild(i), embed_dict)
  1272. def generate_embed_dict(scene):
  1273. embed_dict = {}
  1274. node = scene.GetRootNode()
  1275. if node:
  1276. for i in range(node.GetChildCount()):
  1277. generate_embed_dict_from_hierarchy(node.GetChild(i), embed_dict)
  1278. return embed_dict
  1279. # #####################################################
  1280. # Generate Geometry Objects
  1281. # #####################################################
  1282. def generate_geometry_object(node):
  1283. output = {
  1284. 'type' : 'embedded',
  1285. 'id' : getPrefixedName( node, 'Embed' )
  1286. }
  1287. return output
  1288. def generate_geometry_dict_from_hierarchy(node, geometry_dict):
  1289. if node.GetNodeAttribute() == None:
  1290. pass
  1291. else:
  1292. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  1293. if attribute_type == FbxNodeAttribute.eMesh:
  1294. geometry_object = generate_geometry_object(node)
  1295. geometry_name = getPrefixedName( node, 'Geometry' )
  1296. geometry_dict[geometry_name] = geometry_object
  1297. for i in range(node.GetChildCount()):
  1298. generate_geometry_dict_from_hierarchy(node.GetChild(i), geometry_dict)
  1299. def generate_geometry_dict(scene):
  1300. geometry_dict = {}
  1301. node = scene.GetRootNode()
  1302. if node:
  1303. for i in range(node.GetChildCount()):
  1304. generate_geometry_dict_from_hierarchy(node.GetChild(i), geometry_dict)
  1305. return geometry_dict
  1306. # #####################################################
  1307. # Generate Light Node Objects
  1308. # #####################################################
  1309. def generate_default_light():
  1310. direction = (1,1,1)
  1311. color = (1,1,1)
  1312. intensity = 80.0
  1313. output = {
  1314. 'type': 'DirectionalLight',
  1315. 'color': getHex(color),
  1316. 'intensity': intensity/100.00,
  1317. 'direction': serializeVector3( direction ),
  1318. 'target': getObjectName( None )
  1319. }
  1320. return output
  1321. def generate_light_object(node):
  1322. light = node.GetNodeAttribute()
  1323. light_types = ["point", "directional", "spot", "area", "volume"]
  1324. light_type = light_types[light.LightType.Get()]
  1325. transform = node.EvaluateLocalTransform()
  1326. position = transform.GetT()
  1327. output = None
  1328. if light_type == "directional":
  1329. # Three.js directional lights emit light from a point in 3d space to a target node or the origin.
  1330. # When there is no target, we need to take a point, one unit away from the origin, and move it
  1331. # into the right location so that the origin acts like the target
  1332. if node.GetTarget():
  1333. direction = position
  1334. else:
  1335. translation = FbxVector4(0,0,0,0)
  1336. scale = FbxVector4(1,1,1,1)
  1337. rotation = transform.GetR()
  1338. matrix = FbxMatrix(translation, rotation, scale)
  1339. direction = matrix.MultNormalize(FbxVector4(0,1,0,1))
  1340. output = {
  1341. 'type': 'DirectionalLight',
  1342. 'color': getHex(light.Color.Get()),
  1343. 'intensity': light.Intensity.Get()/100.0,
  1344. 'direction': serializeVector3( direction ),
  1345. 'target': getObjectName( node.GetTarget() )
  1346. }
  1347. elif light_type == "point":
  1348. output = {
  1349. 'type': 'PointLight',
  1350. 'color': getHex(light.Color.Get()),
  1351. 'intensity': light.Intensity.Get()/100.0,
  1352. 'position': serializeVector3( position ),
  1353. 'distance': light.FarAttenuationEnd.Get()
  1354. }
  1355. elif light_type == "spot":
  1356. output = {
  1357. 'type': 'SpotLight',
  1358. 'color': getHex(light.Color.Get()),
  1359. 'intensity': light.Intensity.Get()/100.0,
  1360. 'position': serializeVector3( position ),
  1361. 'distance': light.FarAttenuationEnd.Get(),
  1362. 'angle': light.OuterAngle.Get()*math.pi/180,
  1363. 'exponent': light.DecayType.Get(),
  1364. 'target': getObjectName( node.GetTarget() )
  1365. }
  1366. return output
  1367. def generate_ambient_light(scene):
  1368. scene_settings = scene.GetGlobalSettings()
  1369. ambient_color = scene_settings.GetAmbientColor()
  1370. ambient_color = (ambient_color.mRed, ambient_color.mGreen, ambient_color.mBlue)
  1371. if ambient_color[0] == 0 and ambient_color[1] == 0 and ambient_color[2] == 0:
  1372. return None
  1373. output = {
  1374. 'type': 'AmbientLight',
  1375. 'color': getHex(ambient_color)
  1376. }
  1377. return output
  1378. # #####################################################
  1379. # Generate Camera Node Objects
  1380. # #####################################################
  1381. def generate_default_camera():
  1382. position = (100, 100, 100)
  1383. near = 0.1
  1384. far = 1000
  1385. fov = 75
  1386. output = {
  1387. 'type': 'PerspectiveCamera',
  1388. 'fov': fov,
  1389. 'near': near,
  1390. 'far': far,
  1391. 'position': serializeVector3( position )
  1392. }
  1393. return output
  1394. def generate_camera_object(node):
  1395. camera = node.GetNodeAttribute()
  1396. position = camera.Position.Get()
  1397. projection_types = [ "perspective", "orthogonal" ]
  1398. projection = projection_types[camera.ProjectionType.Get()]
  1399. near = camera.NearPlane.Get()
  1400. far = camera.FarPlane.Get()
  1401. name = getObjectName( node )
  1402. output = {}
  1403. if projection == "perspective":
  1404. aspect = camera.PixelAspectRatio.Get()
  1405. fov = camera.FieldOfView.Get()
  1406. output = {
  1407. 'type': 'PerspectiveCamera',
  1408. 'fov': fov,
  1409. 'aspect': aspect,
  1410. 'near': near,
  1411. 'far': far,
  1412. 'position': serializeVector3( position )
  1413. }
  1414. elif projection == "orthogonal":
  1415. left = ""
  1416. right = ""
  1417. top = ""
  1418. bottom = ""
  1419. output = {
  1420. 'type': 'PerspectiveCamera',
  1421. 'left': left,
  1422. 'right': right,
  1423. 'top': top,
  1424. 'bottom': bottom,
  1425. 'near': near,
  1426. 'far': far,
  1427. 'position': serializeVector3( position )
  1428. }
  1429. return output
  1430. # #####################################################
  1431. # Generate Camera Names
  1432. # #####################################################
  1433. def generate_camera_name_list_from_hierarchy(node, camera_list):
  1434. if node.GetNodeAttribute() == None:
  1435. pass
  1436. else:
  1437. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  1438. if attribute_type == FbxNodeAttribute.eCamera:
  1439. camera_string = getObjectName(node)
  1440. camera_list.append(camera_string)
  1441. for i in range(node.GetChildCount()):
  1442. generate_camera_name_list_from_hierarchy(node.GetChild(i), camera_list)
  1443. def generate_camera_name_list(scene):
  1444. camera_list = []
  1445. node = scene.GetRootNode()
  1446. if node:
  1447. for i in range(node.GetChildCount()):
  1448. generate_camera_name_list_from_hierarchy(node.GetChild(i), camera_list)
  1449. return camera_list
  1450. # #####################################################
  1451. # Generate Mesh Node Object
  1452. # #####################################################
  1453. def generate_mesh_object(node):
  1454. mesh = node.GetNodeAttribute()
  1455. transform = node.EvaluateLocalTransform()
  1456. position = transform.GetT()
  1457. scale = transform.GetS()
  1458. rotation = getRadians(transform.GetR())
  1459. quaternion = transform.GetQ()
  1460. material_count = node.GetMaterialCount()
  1461. material_name = ""
  1462. if material_count > 0:
  1463. material_names = []
  1464. for l in range(mesh.GetLayerCount()):
  1465. materials = mesh.GetLayer(l).GetMaterials()
  1466. if materials:
  1467. if materials.GetReferenceMode() == FbxLayerElement.eIndex:
  1468. #Materials are in an undefined external table
  1469. continue
  1470. for i in range(material_count):
  1471. material = node.GetMaterial(i)
  1472. material_names.append( getMaterialName(material) )
  1473. if not material_count > 1 and not len(material_names) > 0:
  1474. material_names.append('')
  1475. #If this mesh has more than one material, use a proxy material
  1476. material_name = getMaterialName( node, True) if material_count > 1 else material_names[0]
  1477. output = {
  1478. 'geometry': getPrefixedName( node, 'Geometry' ),
  1479. 'material': material_name,
  1480. 'position': serializeVector3( position ),
  1481. 'quaternion': serializeVector4( quaternion ),
  1482. 'scale': serializeVector3( scale ),
  1483. 'visible': True,
  1484. }
  1485. return output
  1486. # #####################################################
  1487. # Generate Node Object
  1488. # #####################################################
  1489. def generate_object(node):
  1490. node_types = ["Unknown", "Null", "Marker", "Skeleton", "Mesh", "Nurbs", "Patch", "Camera",
  1491. "CameraStereo", "CameraSwitcher", "Light", "OpticalReference", "OpticalMarker", "NurbsCurve",
  1492. "TrimNurbsSurface", "Boundary", "NurbsSurface", "Shape", "LODGroup", "SubDiv", "CachedEffect", "Line"]
  1493. transform = node.EvaluateLocalTransform()
  1494. position = transform.GetT()
  1495. scale = transform.GetS()
  1496. rotation = getRadians(transform.GetR())
  1497. quaternion = transform.GetQ()
  1498. node_type = ""
  1499. if node.GetNodeAttribute() == None:
  1500. node_type = "Null"
  1501. else:
  1502. node_type = node_types[node.GetNodeAttribute().GetAttributeType()]
  1503. name = getObjectName( node )
  1504. output = {
  1505. 'fbx_type': node_type,
  1506. 'position': serializeVector3( position ),
  1507. 'quaternion': serializeVector4( quaternion ),
  1508. 'scale': serializeVector3( scale ),
  1509. 'visible': True
  1510. }
  1511. return output
  1512. # #####################################################
  1513. # Parse Scene Node Objects
  1514. # #####################################################
  1515. def generate_object_hierarchy(node, object_dict):
  1516. object_count = 0
  1517. if node.GetNodeAttribute() == None:
  1518. object_data = generate_object(node)
  1519. else:
  1520. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  1521. if attribute_type == FbxNodeAttribute.eMesh:
  1522. object_data = generate_mesh_object(node)
  1523. elif attribute_type == FbxNodeAttribute.eLight:
  1524. object_data = generate_light_object(node)
  1525. elif attribute_type == FbxNodeAttribute.eCamera:
  1526. object_data = generate_camera_object(node)
  1527. else:
  1528. object_data = generate_object(node)
  1529. object_count += 1
  1530. object_name = getObjectName(node)
  1531. object_children = {}
  1532. for i in range(node.GetChildCount()):
  1533. object_count += generate_object_hierarchy(node.GetChild(i), object_children)
  1534. if node.GetChildCount() > 0:
  1535. # Having 'children' above other attributes is hard to read.
  1536. # We can send it to the bottom using the last letter of the alphabet 'z'.
  1537. # This letter is removed from the final output.
  1538. if option_pretty_print:
  1539. object_data['zchildren'] = object_children
  1540. else:
  1541. object_data['children'] = object_children
  1542. object_dict[object_name] = object_data
  1543. return object_count
  1544. def generate_scene_objects(scene):
  1545. object_count = 0
  1546. object_dict = {}
  1547. ambient_light = generate_ambient_light(scene)
  1548. if ambient_light:
  1549. object_dict['AmbientLight'] = ambient_light
  1550. object_count += 1
  1551. if option_default_light:
  1552. default_light = generate_default_light()
  1553. object_dict['DefaultLight'] = default_light
  1554. object_count += 1
  1555. if option_default_camera:
  1556. default_camera = generate_default_camera()
  1557. object_dict['DefaultCamera'] = default_camera
  1558. object_count += 1
  1559. node = scene.GetRootNode()
  1560. if node:
  1561. for i in range(node.GetChildCount()):
  1562. object_count += generate_object_hierarchy(node.GetChild(i), object_dict)
  1563. return object_dict, object_count
  1564. # #####################################################
  1565. # Generate Scene Output
  1566. # #####################################################
  1567. def extract_scene(scene, filename):
  1568. global_settings = scene.GetGlobalSettings()
  1569. objects, nobjects = generate_scene_objects(scene)
  1570. textures = generate_texture_dict(scene)
  1571. materials = generate_material_dict(scene)
  1572. geometries = generate_geometry_dict(scene)
  1573. embeds = generate_embed_dict(scene)
  1574. ntextures = len(textures)
  1575. nmaterials = len(materials)
  1576. ngeometries = len(geometries)
  1577. position = serializeVector3( (0,0,0) )
  1578. rotation = serializeVector3( (0,0,0) )
  1579. scale = serializeVector3( (1,1,1) )
  1580. camera_names = generate_camera_name_list(scene)
  1581. scene_settings = scene.GetGlobalSettings()
  1582. # This does not seem to be any help here
  1583. # global_settings.GetDefaultCamera()
  1584. defcamera = camera_names[0] if len(camera_names) > 0 else ""
  1585. if option_default_camera:
  1586. defcamera = 'default_camera'
  1587. metadata = {
  1588. 'formatVersion': 3.2,
  1589. 'type': 'scene',
  1590. 'generatedBy': 'convert-to-threejs.py',
  1591. 'objects': nobjects,
  1592. 'geometries': ngeometries,
  1593. 'materials': nmaterials,
  1594. 'textures': ntextures
  1595. }
  1596. transform = {
  1597. 'position' : position,
  1598. 'rotation' : rotation,
  1599. 'scale' : scale
  1600. }
  1601. defaults = {
  1602. 'bgcolor' : 0,
  1603. 'camera' : defcamera,
  1604. 'fog' : ''
  1605. }
  1606. output = {
  1607. 'objects': objects,
  1608. 'geometries': geometries,
  1609. 'materials': materials,
  1610. 'textures': textures,
  1611. 'embeds': embeds,
  1612. 'transform': transform,
  1613. 'defaults': defaults,
  1614. }
  1615. if option_pretty_print:
  1616. output['0metadata'] = metadata
  1617. else:
  1618. output['metadata'] = metadata
  1619. return output
  1620. # #####################################################
  1621. # Generate Non-Scene Output
  1622. # #####################################################
  1623. def extract_geometry(scene, filename):
  1624. output = generate_non_scene_output(scene)
  1625. return output
  1626. # #####################################################
  1627. # File Helpers
  1628. # #####################################################
  1629. def write_file(filepath, content):
  1630. index = filepath.rfind('/')
  1631. dir = filepath[0:index]
  1632. #if not os.path.exists(dir):
  1633. #os.makedirs(dir)
  1634. out = open(filepath, "w")
  1635. out.write(content.encode('utf8', 'replace'))
  1636. out.close()
  1637. def read_file(filepath):
  1638. f = open(filepath)
  1639. content = f.readlines()
  1640. f.close()
  1641. return content
  1642. def copy_textures(textures):
  1643. texture_dict = {}
  1644. for key in textures:
  1645. url = textures[key]['fullpath']
  1646. #src = replace_OutFolder2inFolder(url)
  1647. #print( src )
  1648. #print( url )
  1649. if url in texture_dict: # texture has been copied
  1650. continue
  1651. if not os.path.exists(url):
  1652. print("copy_texture error: we can't find this texture at " + url)
  1653. continue
  1654. try:
  1655. index = url.rfind('/')
  1656. if index == -1:
  1657. index = url.rfind( '\\' )
  1658. filename = url[index+1:len(url)]
  1659. saveFolder = "maps"
  1660. saveFilename = saveFolder + "/" + filename
  1661. #print( src )
  1662. #print( url )
  1663. #print( saveFilename )
  1664. if not os.path.exists(saveFolder):
  1665. os.makedirs(saveFolder)
  1666. shutil.copyfile(url, saveFilename)
  1667. texture_dict[url] = True
  1668. except IOError as e:
  1669. print "I/O error({0}): {1} {2}".format(e.errno, e.strerror, url)
  1670. def findFilesWithExt(directory, ext, include_path = True):
  1671. ext = ext.lower()
  1672. found = []
  1673. for root, dirs, files in os.walk(directory):
  1674. for filename in files:
  1675. current_ext = os.path.splitext(filename)[1].lower()
  1676. if current_ext == ext:
  1677. if include_path:
  1678. found.append(os.path.join(root, filename))
  1679. else:
  1680. found.append(filename)
  1681. return found
  1682. # #####################################################
  1683. # main
  1684. # #####################################################
  1685. if __name__ == "__main__":
  1686. from optparse import OptionParser
  1687. try:
  1688. from FbxCommon import *
  1689. except ImportError:
  1690. import platform
  1691. msg = 'Could not locate the python FBX SDK!\n'
  1692. msg += 'You need to copy the FBX SDK into your python install folder such as '
  1693. if platform.system() == 'Windows' or platform.system() == 'Microsoft':
  1694. msg += '"Python26/Lib/site-packages"'
  1695. elif platform.system() == 'Linux':
  1696. msg += '"/usr/local/lib/python2.6/site-packages"'
  1697. elif platform.system() == 'Darwin':
  1698. msg += '"/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages"'
  1699. msg += ' folder.'
  1700. print(msg)
  1701. sys.exit(1)
  1702. usage = "Usage: %prog [source_file.fbx] [output_file.js] [options]"
  1703. parser = OptionParser(usage=usage)
  1704. parser.add_option('-t', '--triangulate', action='store_true', dest='triangulate', help="force quad geometry into triangles", default=False)
  1705. parser.add_option('-x', '--ignore-textures', action='store_true', dest='notextures', help="don't include texture references in output file", default=False)
  1706. parser.add_option('-n', '--no-texture-copy', action='store_true', dest='notexturecopy', help="don't copy texture files", default=False)
  1707. parser.add_option('-u', '--force-prefix', action='store_true', dest='prefix', help="prefix all object names in output file to ensure uniqueness", default=False)
  1708. parser.add_option('-f', '--flatten-scene', action='store_true', dest='geometry', help="merge all geometries and apply node transforms", default=False)
  1709. parser.add_option('-c', '--add-camera', action='store_true', dest='defcamera', help="include default camera in output scene", default=False)
  1710. parser.add_option('-l', '--add-light', action='store_true', dest='deflight', help="include default light in output scene", default=False)
  1711. parser.add_option('-p', '--pretty-print', action='store_true', dest='pretty', help="prefix all object names in output file", default=False)
  1712. (options, args) = parser.parse_args()
  1713. option_triangulate = options.triangulate
  1714. option_textures = True if not options.notextures else False
  1715. option_copy_textures = True if not options.notexturecopy else False
  1716. option_prefix = options.prefix
  1717. option_geometry = options.geometry
  1718. option_default_camera = options.defcamera
  1719. option_default_light = options.deflight
  1720. option_pretty_print = options.pretty
  1721. # Prepare the FBX SDK.
  1722. sdk_manager, scene = InitializeSdkObjects()
  1723. converter = FbxGeometryConverter(sdk_manager)
  1724. # The converter takes an FBX file as an argument.
  1725. if len(args) > 1:
  1726. print("\nLoading file: %s" % args[0])
  1727. result = LoadScene(sdk_manager, scene, args[0])
  1728. else:
  1729. result = False
  1730. print("\nUsage: convert_fbx_to_threejs [source_file.fbx] [output_file.js]\n")
  1731. if not result:
  1732. print("\nAn error occurred while loading the file...")
  1733. else:
  1734. if option_triangulate:
  1735. print("\nForcing geometry to triangles")
  1736. triangulate_scene(scene)
  1737. # According to asset's coordinate to convert scene
  1738. upVector = scene.GetGlobalSettings().GetAxisSystem().GetUpVector();
  1739. axis_system = FbxAxisSystem.MayaYUp
  1740. if upVector[0] == 3:
  1741. axis_system = FbxAxisSystem.MayaZUp
  1742. axis_system.ConvertScene(scene)
  1743. inputFolder = args[0].replace( "\\", "/" );
  1744. index = args[0].rfind( "/" );
  1745. inputFolder = inputFolder[:index]
  1746. outputFolder = args[1].replace( "\\", "/" );
  1747. index = args[1].rfind( "/" );
  1748. outputFolder = outputFolder[:index]
  1749. if option_geometry:
  1750. output_content = extract_geometry(scene, os.path.basename(args[0]))
  1751. else:
  1752. output_content = extract_scene(scene, os.path.basename(args[0]))
  1753. if option_pretty_print:
  1754. output_string = json.dumps(output_content, indent=4, cls=CustomEncoder, separators=(',', ': '), sort_keys=True)
  1755. output_string = executeRegexHacks(output_string)
  1756. else:
  1757. output_string = json.dumps(output_content, separators=(',', ': '), sort_keys=True)
  1758. output_path = os.path.join(os.getcwd(), args[1])
  1759. write_file(output_path, output_string)
  1760. if option_copy_textures:
  1761. copy_textures( output_content['textures'] )
  1762. print("\nExported Three.js file to:\n%s\n" % output_path)
  1763. # Destroy all objects created by the FBX SDK.
  1764. sdk_manager.Destroy()
  1765. sys.exit(0)