convert_to_threejs.py 75 KB

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