convert_to_threejs.py 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160
  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. layered_color_indices.append( color_indices )
  713. layered_color_values.append( color_values )
  714. color_values = []
  715. color_indices = []
  716. # Three.js only supports one layer of colors
  717. if len(layered_color_values) > 0:
  718. color_values = layered_color_values[0]
  719. color_indices = layered_color_indices[0]
  720. '''
  721. # The Fbx SDK defaults mesh.Color to (0.8, 0.8, 0.8)
  722. # This causes most models to receive incorrect vertex colors
  723. if len(color_values) == 0:
  724. color = mesh.Color.Get()
  725. color_values = [[color[0], color[1], color[2]]]
  726. color_indices = []
  727. for p in range(poly_count):
  728. poly_size = mesh.GetPolygonSize(p)
  729. color_indices.append([0] * poly_size)
  730. '''
  731. return color_values, color_indices
  732. def extract_fbx_vertex_uvs(mesh):
  733. # eNone The mapping is undetermined.
  734. # eByControlPoint There will be one mapping coordinate for each surface control point/vertex.
  735. # 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.
  736. # eByPolygon There can be only one mapping coordinate for the whole polygon.
  737. # eByEdge There will be one mapping coordinate for each unique edge in the mesh. This is meant to be used with smoothing layer elements.
  738. # eAllSame There can be only one mapping coordinate for the whole surface.
  739. layered_uv_indices = []
  740. layered_uv_values = []
  741. poly_count = mesh.GetPolygonCount()
  742. control_points = mesh.GetControlPoints()
  743. for l in range(mesh.GetLayerCount()):
  744. mesh_uvs = mesh.GetLayer(l).GetUVs()
  745. if not mesh_uvs:
  746. continue
  747. uvs_array = mesh_uvs.GetDirectArray()
  748. uvs_count = uvs_array.GetCount()
  749. if uvs_count == 0:
  750. continue
  751. uv_indices = []
  752. uv_values = []
  753. # values
  754. for i in range(uvs_count):
  755. uv = uvs_array.GetAt(i)
  756. uv = [uv[0], uv[1]]
  757. uv_values.append(uv)
  758. # indices
  759. vertexId = 0
  760. for p in range(poly_count):
  761. poly_size = mesh.GetPolygonSize(p)
  762. poly_uvs = []
  763. for v in range(poly_size):
  764. control_point_index = mesh.GetPolygonVertex(p, v)
  765. if mesh_uvs.GetMappingMode() == FbxLayerElement.eByControlPoint:
  766. if mesh_uvs.GetReferenceMode() == FbxLayerElement.eDirect:
  767. poly_uvs.append(control_point_index)
  768. elif mesh_uvs.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  769. index = mesh_uvs.GetIndexArray().GetAt(control_point_index)
  770. poly_uvs.append(index)
  771. elif mesh_uvs.GetMappingMode() == FbxLayerElement.eByPolygonVertex:
  772. uv_texture_index = mesh_uvs.GetIndexArray().GetAt(vertexId)
  773. if mesh_uvs.GetReferenceMode() == FbxLayerElement.eDirect or \
  774. mesh_uvs.GetReferenceMode() == FbxLayerElement.eIndexToDirect:
  775. poly_uvs.append(uv_texture_index)
  776. elif mesh_uvs.GetMappingMode() == FbxLayerElement.eByPolygon or \
  777. mesh_uvs.GetMappingMode() == FbxLayerElement.eAllSame or \
  778. mesh_uvs.GetMappingMode() == FbxLayerElement.eNone:
  779. print("unsupported uv mapping mode for polygon vertex")
  780. vertexId += 1
  781. uv_indices.append(poly_uvs)
  782. layered_uv_values.append(uv_values)
  783. layered_uv_indices.append(uv_indices)
  784. return layered_uv_values, layered_uv_indices
  785. # #####################################################
  786. # Process Mesh Geometry
  787. # #####################################################
  788. def generate_normal_key(normal):
  789. return (round(normal[0], 6), round(normal[1], 6), round(normal[2], 6))
  790. def generate_color_key(color):
  791. return getHex(color)
  792. def generate_uv_key(uv):
  793. return (round(uv[0], 6), round(uv[1], 6))
  794. def append_non_duplicate_uvs(source_uvs, dest_uvs, counts):
  795. source_layer_count = len(source_uvs)
  796. for layer_index in range(source_layer_count):
  797. dest_layer_count = len(dest_uvs)
  798. if dest_layer_count <= layer_index:
  799. dest_uv_layer = {}
  800. count = 0
  801. dest_uvs.append(dest_uv_layer)
  802. counts.append(count)
  803. else:
  804. dest_uv_layer = dest_uvs[layer_index]
  805. count = counts[layer_index]
  806. source_uv_layer = source_uvs[layer_index]
  807. for uv in source_uv_layer:
  808. key = generate_uv_key(uv)
  809. if key not in dest_uv_layer:
  810. dest_uv_layer[key] = count
  811. count += 1
  812. counts[layer_index] = count
  813. return counts
  814. def generate_unique_normals_dictionary(mesh_list):
  815. normals_dictionary = {}
  816. nnormals = 0
  817. # Merge meshes, remove duplicate data
  818. for mesh in mesh_list:
  819. node = mesh.GetNode()
  820. normal_values, normal_indices = extract_fbx_vertex_normals(mesh)
  821. if len(normal_values) > 0:
  822. for normal in normal_values:
  823. key = generate_normal_key(normal)
  824. if key not in normals_dictionary:
  825. normals_dictionary[key] = nnormals
  826. nnormals += 1
  827. return normals_dictionary
  828. def generate_unique_colors_dictionary(mesh_list):
  829. colors_dictionary = {}
  830. ncolors = 0
  831. # Merge meshes, remove duplicate data
  832. for mesh in mesh_list:
  833. color_values, color_indices = extract_fbx_vertex_colors(mesh)
  834. if len(color_values) > 0:
  835. for color in color_values:
  836. key = generate_color_key(color)
  837. if key not in colors_dictionary:
  838. colors_dictionary[key] = ncolors
  839. ncolors += 1
  840. return colors_dictionary
  841. def generate_unique_uvs_dictionary_layers(mesh_list):
  842. uvs_dictionary_layers = []
  843. nuvs_list = []
  844. # Merge meshes, remove duplicate data
  845. for mesh in mesh_list:
  846. uv_values, uv_indices = extract_fbx_vertex_uvs(mesh)
  847. if len(uv_values) > 0:
  848. nuvs_list = append_non_duplicate_uvs(uv_values, uvs_dictionary_layers, nuvs_list)
  849. return uvs_dictionary_layers
  850. def generate_normals_from_dictionary(normals_dictionary):
  851. normal_values = []
  852. for key, index in sorted(normals_dictionary.items(), key = operator.itemgetter(1)):
  853. normal_values.append(key)
  854. return normal_values
  855. def generate_colors_from_dictionary(colors_dictionary):
  856. color_values = []
  857. for key, index in sorted(colors_dictionary.items(), key = operator.itemgetter(1)):
  858. color_values.append(key)
  859. return color_values
  860. def generate_uvs_from_dictionary_layers(uvs_dictionary_layers):
  861. uv_values = []
  862. for uvs_dictionary in uvs_dictionary_layers:
  863. uv_values_layer = []
  864. for key, index in sorted(uvs_dictionary.items(), key = operator.itemgetter(1)):
  865. uv_values_layer.append(key)
  866. uv_values.append(uv_values_layer)
  867. return uv_values
  868. def generate_normal_indices_for_poly(poly_index, mesh_normal_values, mesh_normal_indices, normals_to_indices):
  869. if len(mesh_normal_indices) <= 0:
  870. return []
  871. poly_normal_indices = mesh_normal_indices[poly_index]
  872. poly_size = len(poly_normal_indices)
  873. output_poly_normal_indices = []
  874. for v in range(poly_size):
  875. normal_index = poly_normal_indices[v]
  876. normal_value = mesh_normal_values[normal_index]
  877. key = generate_normal_key(normal_value)
  878. output_index = normals_to_indices[key]
  879. output_poly_normal_indices.append(output_index)
  880. return output_poly_normal_indices
  881. def generate_color_indices_for_poly(poly_index, mesh_color_values, mesh_color_indices, colors_to_indices):
  882. if len(mesh_color_indices) <= 0:
  883. return []
  884. poly_color_indices = mesh_color_indices[poly_index]
  885. poly_size = len(poly_color_indices)
  886. output_poly_color_indices = []
  887. for v in range(poly_size):
  888. color_index = poly_color_indices[v]
  889. color_value = mesh_color_values[color_index]
  890. key = generate_color_key(color_value)
  891. output_index = colors_to_indices[key]
  892. output_poly_color_indices.append(output_index)
  893. return output_poly_color_indices
  894. def generate_uv_indices_for_poly(poly_index, mesh_uv_values, mesh_uv_indices, uvs_to_indices):
  895. if len(mesh_uv_indices) <= 0:
  896. return []
  897. poly_uv_indices = mesh_uv_indices[poly_index]
  898. poly_size = len(poly_uv_indices)
  899. output_poly_uv_indices = []
  900. for v in range(poly_size):
  901. uv_index = poly_uv_indices[v]
  902. uv_value = mesh_uv_values[uv_index]
  903. key = generate_uv_key(uv_value)
  904. output_index = uvs_to_indices[key]
  905. output_poly_uv_indices.append(output_index)
  906. return output_poly_uv_indices
  907. def process_mesh_vertices(mesh_list):
  908. vertex_offset = 0
  909. vertex_offset_list = [0]
  910. vertices = []
  911. for mesh in mesh_list:
  912. node = mesh.GetNode()
  913. mesh_vertices = extract_fbx_vertex_positions(mesh)
  914. vertices.extend(mesh_vertices[:])
  915. vertex_offset += len(mesh_vertices)
  916. vertex_offset_list.append(vertex_offset)
  917. return vertices, vertex_offset_list
  918. def process_mesh_materials(mesh_list):
  919. material_offset = 0
  920. material_offset_list = [0]
  921. materials_list = []
  922. #TODO: remove duplicate mesh references
  923. for mesh in mesh_list:
  924. node = mesh.GetNode()
  925. material_count = node.GetMaterialCount()
  926. if material_count > 0:
  927. for l in range(mesh.GetLayerCount()):
  928. materials = mesh.GetLayer(l).GetMaterials()
  929. if materials:
  930. if materials.GetReferenceMode() == FbxLayerElement.eIndex:
  931. #Materials are in an undefined external table
  932. continue
  933. for i in range(material_count):
  934. material = node.GetMaterial(i)
  935. materials_list.append( material )
  936. material_offset += material_count
  937. material_offset_list.append(material_offset)
  938. return materials_list, material_offset_list
  939. def process_mesh_polygons(mesh_list, normals_to_indices, colors_to_indices, uvs_to_indices_list, vertex_offset_list, material_offset_list):
  940. faces = []
  941. for mesh_index in range(len(mesh_list)):
  942. mesh = mesh_list[mesh_index]
  943. flipWindingOrder = False
  944. node = mesh.GetNode()
  945. if node:
  946. local_scale = node.EvaluateLocalScaling()
  947. if local_scale[0] < 0 or local_scale[1] < 0 or local_scale[2] < 0:
  948. flipWindingOrder = True
  949. poly_count = mesh.GetPolygonCount()
  950. control_points = mesh.GetControlPoints()
  951. normal_values, normal_indices = extract_fbx_vertex_normals(mesh)
  952. color_values, color_indices = extract_fbx_vertex_colors(mesh)
  953. uv_values_layers, uv_indices_layers = extract_fbx_vertex_uvs(mesh)
  954. for poly_index in range(poly_count):
  955. poly_size = mesh.GetPolygonSize(poly_index)
  956. face_normals = generate_normal_indices_for_poly(poly_index, normal_values, normal_indices, normals_to_indices)
  957. face_colors = generate_color_indices_for_poly(poly_index, color_values, color_indices, colors_to_indices)
  958. face_uv_layers = []
  959. for l in range(len(uv_indices_layers)):
  960. uv_values = uv_values_layers[l]
  961. uv_indices = uv_indices_layers[l]
  962. face_uv_indices = generate_uv_indices_for_poly(poly_index, uv_values, uv_indices, uvs_to_indices_list[l])
  963. face_uv_layers.append(face_uv_indices)
  964. face_vertices = []
  965. for vertex_index in range(poly_size):
  966. control_point_index = mesh.GetPolygonVertex(poly_index, vertex_index)
  967. face_vertices.append(control_point_index)
  968. #TODO: assign a default material to any mesh without one
  969. if len(material_offset_list) <= mesh_index:
  970. material_offset = 0
  971. else:
  972. material_offset = material_offset_list[mesh_index]
  973. vertex_offset = vertex_offset_list[mesh_index]
  974. if poly_size > 4:
  975. new_face_normals = []
  976. new_face_colors = []
  977. new_face_uv_layers = []
  978. for i in range(poly_size - 2):
  979. new_face_vertices = [face_vertices[0], face_vertices[i+1], face_vertices[i+2]]
  980. if len(face_normals):
  981. new_face_normals = [face_normals[0], face_normals[i+1], face_normals[i+2]]
  982. if len(face_colors):
  983. new_face_colors = [face_colors[0], face_colors[i+1], face_colors[i+2]]
  984. if len(face_uv_layers):
  985. new_face_uv_layers = []
  986. for layer in face_uv_layers:
  987. new_face_uv_layers.append([layer[0], layer[i+1], layer[i+2]])
  988. face = generate_mesh_face(mesh,
  989. poly_index,
  990. new_face_vertices,
  991. new_face_normals,
  992. new_face_colors,
  993. new_face_uv_layers,
  994. vertex_offset,
  995. material_offset,
  996. flipWindingOrder)
  997. faces.append(face)
  998. else:
  999. face = generate_mesh_face(mesh,
  1000. poly_index,
  1001. face_vertices,
  1002. face_normals,
  1003. face_colors,
  1004. face_uv_layers,
  1005. vertex_offset,
  1006. material_offset,
  1007. flipWindingOrder)
  1008. faces.append(face)
  1009. return faces
  1010. def generate_mesh_face(mesh, polygon_index, vertex_indices, normals, colors, uv_layers, vertex_offset, material_offset, flipOrder):
  1011. isTriangle = ( len(vertex_indices) == 3 )
  1012. nVertices = 3 if isTriangle else 4
  1013. hasMaterial = False
  1014. for l in range(mesh.GetLayerCount()):
  1015. materials = mesh.GetLayer(l).GetMaterials()
  1016. if materials:
  1017. hasMaterial = True
  1018. break
  1019. hasFaceUvs = False
  1020. hasFaceVertexUvs = len(uv_layers) > 0
  1021. hasFaceNormals = False
  1022. hasFaceVertexNormals = len(normals) > 0
  1023. hasFaceColors = False
  1024. hasFaceVertexColors = len(colors) > 0
  1025. faceType = 0
  1026. faceType = setBit(faceType, 0, not isTriangle)
  1027. faceType = setBit(faceType, 1, hasMaterial)
  1028. faceType = setBit(faceType, 2, hasFaceUvs)
  1029. faceType = setBit(faceType, 3, hasFaceVertexUvs)
  1030. faceType = setBit(faceType, 4, hasFaceNormals)
  1031. faceType = setBit(faceType, 5, hasFaceVertexNormals)
  1032. faceType = setBit(faceType, 6, hasFaceColors)
  1033. faceType = setBit(faceType, 7, hasFaceVertexColors)
  1034. faceData = []
  1035. # order is important, must match order in JSONLoader
  1036. # face type
  1037. # vertex indices
  1038. # material index
  1039. # face uvs index
  1040. # face vertex uvs indices
  1041. # face color index
  1042. # face vertex colors indices
  1043. faceData.append(faceType)
  1044. if flipOrder:
  1045. if nVertices == 3:
  1046. vertex_indices = [vertex_indices[0], vertex_indices[2], vertex_indices[1]]
  1047. if hasFaceVertexNormals:
  1048. normals = [normals[0], normals[2], normals[1]]
  1049. if hasFaceVertexColors:
  1050. colors = [colors[0], colors[2], colors[1]]
  1051. if hasFaceVertexUvs:
  1052. tmp = []
  1053. for polygon_uvs in uv_layers:
  1054. tmp.append([polygon_uvs[0], polygon_uvs[2], polygon_uvs[1]])
  1055. uv_layers = tmp
  1056. else:
  1057. vertex_indices = [vertex_indices[0], vertex_indices[3], vertex_indices[2], vertex_indices[1]]
  1058. if hasFaceVertexNormals:
  1059. normals = [normals[0], normals[3], normals[2], normals[1]]
  1060. if hasFaceVertexColors:
  1061. colors = [colors[0], colors[3], colors[2], colors[1]]
  1062. if hasFaceVertexUvs:
  1063. tmp = []
  1064. for polygon_uvs in uv_layers:
  1065. tmp.append([polygon_uvs[0], polygon_uvs[3], polygon_uvs[2], polygon_uvs[3]])
  1066. uv_layers = tmp
  1067. for i in range(nVertices):
  1068. index = vertex_indices[i] + vertex_offset
  1069. faceData.append(index)
  1070. if hasMaterial:
  1071. material_id = 0
  1072. for l in range(mesh.GetLayerCount()):
  1073. materials = mesh.GetLayer(l).GetMaterials()
  1074. if materials:
  1075. material_id = materials.GetIndexArray().GetAt(polygon_index)
  1076. break
  1077. material_id += material_offset
  1078. faceData.append( material_id )
  1079. if hasFaceVertexUvs:
  1080. for polygon_uvs in uv_layers:
  1081. for i in range(nVertices):
  1082. index = polygon_uvs[i]
  1083. faceData.append(index)
  1084. if hasFaceVertexNormals:
  1085. for i in range(nVertices):
  1086. index = normals[i]
  1087. faceData.append(index)
  1088. if hasFaceVertexColors:
  1089. for i in range(nVertices):
  1090. index = colors[i]
  1091. faceData.append(index)
  1092. return faceData
  1093. # #####################################################
  1094. # Generate Mesh Object (for scene output format)
  1095. # #####################################################
  1096. def generate_scene_output(node):
  1097. mesh = node.GetNodeAttribute()
  1098. # This is done in order to keep the scene output and non-scene output code DRY
  1099. mesh_list = [ mesh ]
  1100. # Extract the mesh data into arrays
  1101. vertices, vertex_offsets = process_mesh_vertices(mesh_list)
  1102. materials, material_offsets = process_mesh_materials(mesh_list)
  1103. normals_to_indices = generate_unique_normals_dictionary(mesh_list)
  1104. colors_to_indices = generate_unique_colors_dictionary(mesh_list)
  1105. uvs_to_indices_list = generate_unique_uvs_dictionary_layers(mesh_list)
  1106. normal_values = generate_normals_from_dictionary(normals_to_indices)
  1107. color_values = generate_colors_from_dictionary(colors_to_indices)
  1108. uv_values = generate_uvs_from_dictionary_layers(uvs_to_indices_list)
  1109. # Generate mesh faces for the Three.js file format
  1110. faces = process_mesh_polygons(mesh_list,
  1111. normals_to_indices,
  1112. colors_to_indices,
  1113. uvs_to_indices_list,
  1114. vertex_offsets,
  1115. material_offsets)
  1116. # Generate counts for uvs, vertices, normals, colors, and faces
  1117. nuvs = []
  1118. for layer_index, uvs in enumerate(uv_values):
  1119. nuvs.append(str(len(uvs)))
  1120. nvertices = len(vertices)
  1121. nnormals = len(normal_values)
  1122. ncolors = len(color_values)
  1123. nfaces = len(faces)
  1124. # Flatten the arrays, currently they are in the form of [[0, 1, 2], [3, 4, 5], ...]
  1125. vertices = [val for v in vertices for val in v]
  1126. normal_values = [val for n in normal_values for val in n]
  1127. color_values = [c for c in color_values]
  1128. faces = [val for f in faces for val in f]
  1129. uv_values = generate_uvs(uv_values)
  1130. # Disable automatic json indenting when pretty printing for the arrays
  1131. if option_pretty_print:
  1132. nuvs = NoIndent(nuvs)
  1133. vertices = ChunkedIndent(vertices, 15, True)
  1134. normal_values = ChunkedIndent(normal_values, 15, True)
  1135. color_values = ChunkedIndent(color_values, 15)
  1136. faces = ChunkedIndent(faces, 30)
  1137. metadata = {
  1138. 'vertices' : nvertices,
  1139. 'normals' : nnormals,
  1140. 'colors' : ncolors,
  1141. 'faces' : nfaces,
  1142. 'uvs' : nuvs
  1143. }
  1144. output = {
  1145. 'scale' : 1,
  1146. 'materials' : [],
  1147. 'vertices' : vertices,
  1148. 'normals' : [] if nnormals <= 0 else normal_values,
  1149. 'colors' : [] if ncolors <= 0 else color_values,
  1150. 'uvs' : uv_values,
  1151. 'faces' : faces
  1152. }
  1153. if option_pretty_print:
  1154. output['0metadata'] = metadata
  1155. else:
  1156. output['metadata'] = metadata
  1157. return output
  1158. # #####################################################
  1159. # Generate Mesh Object (for non-scene output)
  1160. # #####################################################
  1161. def generate_non_scene_output(scene):
  1162. mesh_list = generate_mesh_list(scene)
  1163. # Extract the mesh data into arrays
  1164. vertices, vertex_offsets = process_mesh_vertices(mesh_list)
  1165. materials, material_offsets = process_mesh_materials(mesh_list)
  1166. normals_to_indices = generate_unique_normals_dictionary(mesh_list)
  1167. colors_to_indices = generate_unique_colors_dictionary(mesh_list)
  1168. uvs_to_indices_list = generate_unique_uvs_dictionary_layers(mesh_list)
  1169. normal_values = generate_normals_from_dictionary(normals_to_indices)
  1170. color_values = generate_colors_from_dictionary(colors_to_indices)
  1171. uv_values = generate_uvs_from_dictionary_layers(uvs_to_indices_list)
  1172. # Generate mesh faces for the Three.js file format
  1173. faces = process_mesh_polygons(mesh_list,
  1174. normals_to_indices,
  1175. colors_to_indices,
  1176. uvs_to_indices_list,
  1177. vertex_offsets,
  1178. material_offsets)
  1179. # Generate counts for uvs, vertices, normals, colors, and faces
  1180. nuvs = []
  1181. for layer_index, uvs in enumerate(uv_values):
  1182. nuvs.append(str(len(uvs)))
  1183. nvertices = len(vertices)
  1184. nnormals = len(normal_values)
  1185. ncolors = len(color_values)
  1186. nfaces = len(faces)
  1187. # Flatten the arrays, currently they are in the form of [[0, 1, 2], [3, 4, 5], ...]
  1188. vertices = [val for v in vertices for val in v]
  1189. normal_values = [val for n in normal_values for val in n]
  1190. color_values = [c for c in color_values]
  1191. faces = [val for f in faces for val in f]
  1192. uv_values = generate_uvs(uv_values)
  1193. # Disable json indenting when pretty printing for the arrays
  1194. if option_pretty_print:
  1195. nuvs = NoIndent(nuvs)
  1196. vertices = NoIndent(vertices)
  1197. normal_values = NoIndent(normal_values)
  1198. color_values = NoIndent(color_values)
  1199. faces = NoIndent(faces)
  1200. metadata = {
  1201. 'formatVersion' : 3,
  1202. 'type' : 'geometry',
  1203. 'generatedBy' : 'convert-to-threejs.py',
  1204. 'vertices' : nvertices,
  1205. 'normals' : nnormals,
  1206. 'colors' : ncolors,
  1207. 'faces' : nfaces,
  1208. 'uvs' : nuvs
  1209. }
  1210. output = {
  1211. 'scale' : 1,
  1212. 'materials' : [],
  1213. 'vertices' : vertices,
  1214. 'normals' : [] if nnormals <= 0 else normal_values,
  1215. 'colors' : [] if ncolors <= 0 else color_values,
  1216. 'uvs' : uv_values,
  1217. 'faces' : faces
  1218. }
  1219. if option_pretty_print:
  1220. output['0metadata'] = metadata
  1221. else:
  1222. output['metadata'] = metadata
  1223. return output
  1224. def generate_mesh_list_from_hierarchy(node, mesh_list):
  1225. if node.GetNodeAttribute() == None:
  1226. pass
  1227. else:
  1228. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  1229. if attribute_type == FbxNodeAttribute.eMesh or \
  1230. attribute_type == FbxNodeAttribute.eNurbs or \
  1231. attribute_type == FbxNodeAttribute.eNurbsSurface or \
  1232. attribute_type == FbxNodeAttribute.ePatch:
  1233. if attribute_type != FbxNodeAttribute.eMesh:
  1234. converter.TriangulateInPlace(node);
  1235. mesh_list.append(node.GetNodeAttribute())
  1236. for i in range(node.GetChildCount()):
  1237. generate_mesh_list_from_hierarchy(node.GetChild(i), mesh_list)
  1238. def generate_mesh_list(scene):
  1239. mesh_list = []
  1240. node = scene.GetRootNode()
  1241. if node:
  1242. for i in range(node.GetChildCount()):
  1243. generate_mesh_list_from_hierarchy(node.GetChild(i), mesh_list)
  1244. return mesh_list
  1245. # #####################################################
  1246. # Generate Embed Objects
  1247. # #####################################################
  1248. def generate_embed_dict_from_hierarchy(node, embed_dict):
  1249. if node.GetNodeAttribute() == None:
  1250. pass
  1251. else:
  1252. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  1253. if attribute_type == FbxNodeAttribute.eMesh or \
  1254. attribute_type == FbxNodeAttribute.eNurbs or \
  1255. attribute_type == FbxNodeAttribute.eNurbsSurface or \
  1256. attribute_type == FbxNodeAttribute.ePatch:
  1257. if attribute_type != FbxNodeAttribute.eMesh:
  1258. converter.TriangulateInPlace(node);
  1259. embed_object = generate_scene_output(node)
  1260. embed_name = getPrefixedName(node, 'Embed')
  1261. embed_dict[embed_name] = embed_object
  1262. for i in range(node.GetChildCount()):
  1263. generate_embed_dict_from_hierarchy(node.GetChild(i), embed_dict)
  1264. def generate_embed_dict(scene):
  1265. embed_dict = {}
  1266. node = scene.GetRootNode()
  1267. if node:
  1268. for i in range(node.GetChildCount()):
  1269. generate_embed_dict_from_hierarchy(node.GetChild(i), embed_dict)
  1270. return embed_dict
  1271. # #####################################################
  1272. # Generate Geometry Objects
  1273. # #####################################################
  1274. def generate_geometry_object(node):
  1275. output = {
  1276. 'type' : 'embedded',
  1277. 'id' : getPrefixedName( node, 'Embed' )
  1278. }
  1279. return output
  1280. def generate_geometry_dict_from_hierarchy(node, geometry_dict):
  1281. if node.GetNodeAttribute() == None:
  1282. pass
  1283. else:
  1284. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  1285. if attribute_type == FbxNodeAttribute.eMesh:
  1286. geometry_object = generate_geometry_object(node)
  1287. geometry_name = getPrefixedName( node, 'Geometry' )
  1288. geometry_dict[geometry_name] = geometry_object
  1289. for i in range(node.GetChildCount()):
  1290. generate_geometry_dict_from_hierarchy(node.GetChild(i), geometry_dict)
  1291. def generate_geometry_dict(scene):
  1292. geometry_dict = {}
  1293. node = scene.GetRootNode()
  1294. if node:
  1295. for i in range(node.GetChildCount()):
  1296. generate_geometry_dict_from_hierarchy(node.GetChild(i), geometry_dict)
  1297. return geometry_dict
  1298. # #####################################################
  1299. # Generate Light Node Objects
  1300. # #####################################################
  1301. def generate_default_light():
  1302. direction = (1,1,1)
  1303. color = (1,1,1)
  1304. intensity = 80.0
  1305. output = {
  1306. 'type': 'DirectionalLight',
  1307. 'color': getHex(color),
  1308. 'intensity': intensity/100.00,
  1309. 'direction': serializeVector3( direction ),
  1310. 'target': getObjectName( None )
  1311. }
  1312. return output
  1313. def generate_light_object(node):
  1314. light = node.GetNodeAttribute()
  1315. light_types = ["point", "directional", "spot", "area", "volume"]
  1316. light_type = light_types[light.LightType.Get()]
  1317. transform = node.EvaluateLocalTransform()
  1318. position = transform.GetT()
  1319. output = None
  1320. if light_type == "directional":
  1321. # Three.js directional lights emit light from a point in 3d space to a target node or the origin.
  1322. # When there is no target, we need to take a point, one unit away from the origin, and move it
  1323. # into the right location so that the origin acts like the target
  1324. if node.GetTarget():
  1325. direction = position
  1326. else:
  1327. translation = FbxVector4(0,0,0,0)
  1328. scale = FbxVector4(1,1,1,1)
  1329. rotation = transform.GetR()
  1330. matrix = FbxMatrix(translation, rotation, scale)
  1331. direction = matrix.MultNormalize(FbxVector4(0,1,0,1))
  1332. output = {
  1333. 'type': 'DirectionalLight',
  1334. 'color': getHex(light.Color.Get()),
  1335. 'intensity': light.Intensity.Get()/100.0,
  1336. 'direction': serializeVector3( direction ),
  1337. 'target': getObjectName( node.GetTarget() )
  1338. }
  1339. elif light_type == "point":
  1340. output = {
  1341. 'type': 'PointLight',
  1342. 'color': getHex(light.Color.Get()),
  1343. 'intensity': light.Intensity.Get()/100.0,
  1344. 'position': serializeVector3( position ),
  1345. 'distance': light.FarAttenuationEnd.Get()
  1346. }
  1347. elif light_type == "spot":
  1348. output = {
  1349. 'type': 'SpotLight',
  1350. 'color': getHex(light.Color.Get()),
  1351. 'intensity': light.Intensity.Get()/100.0,
  1352. 'position': serializeVector3( position ),
  1353. 'distance': light.FarAttenuationEnd.Get(),
  1354. 'angle': light.OuterAngle.Get()*math.pi/180,
  1355. 'exponent': light.DecayType.Get(),
  1356. 'target': getObjectName( node.GetTarget() )
  1357. }
  1358. return output
  1359. def generate_ambient_light(scene):
  1360. scene_settings = scene.GetGlobalSettings()
  1361. ambient_color = scene_settings.GetAmbientColor()
  1362. ambient_color = (ambient_color.mRed, ambient_color.mGreen, ambient_color.mBlue)
  1363. if ambient_color[0] == 0 and ambient_color[1] == 0 and ambient_color[2] == 0:
  1364. return None
  1365. output = {
  1366. 'type': 'AmbientLight',
  1367. 'color': getHex(ambient_color)
  1368. }
  1369. return output
  1370. # #####################################################
  1371. # Generate Camera Node Objects
  1372. # #####################################################
  1373. def generate_default_camera():
  1374. position = (100, 100, 100)
  1375. near = 0.1
  1376. far = 1000
  1377. fov = 75
  1378. output = {
  1379. 'type': 'PerspectiveCamera',
  1380. 'fov': fov,
  1381. 'near': near,
  1382. 'far': far,
  1383. 'position': serializeVector3( position )
  1384. }
  1385. return output
  1386. def generate_camera_object(node):
  1387. camera = node.GetNodeAttribute()
  1388. position = camera.Position.Get()
  1389. projection_types = [ "perspective", "orthogonal" ]
  1390. projection = projection_types[camera.ProjectionType.Get()]
  1391. near = camera.NearPlane.Get()
  1392. far = camera.FarPlane.Get()
  1393. name = getObjectName( node )
  1394. output = {}
  1395. if projection == "perspective":
  1396. aspect = camera.PixelAspectRatio.Get()
  1397. fov = camera.FieldOfView.Get()
  1398. output = {
  1399. 'type': 'PerspectiveCamera',
  1400. 'fov': fov,
  1401. 'aspect': aspect,
  1402. 'near': near,
  1403. 'far': far,
  1404. 'position': serializeVector3( position )
  1405. }
  1406. elif projection == "orthogonal":
  1407. left = ""
  1408. right = ""
  1409. top = ""
  1410. bottom = ""
  1411. output = {
  1412. 'type': 'PerspectiveCamera',
  1413. 'left': left,
  1414. 'right': right,
  1415. 'top': top,
  1416. 'bottom': bottom,
  1417. 'near': near,
  1418. 'far': far,
  1419. 'position': serializeVector3( position )
  1420. }
  1421. return output
  1422. # #####################################################
  1423. # Generate Camera Names
  1424. # #####################################################
  1425. def generate_camera_name_list_from_hierarchy(node, camera_list):
  1426. if node.GetNodeAttribute() == None:
  1427. pass
  1428. else:
  1429. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  1430. if attribute_type == FbxNodeAttribute.eCamera:
  1431. camera_string = getObjectName(node)
  1432. camera_list.append(camera_string)
  1433. for i in range(node.GetChildCount()):
  1434. generate_camera_name_list_from_hierarchy(node.GetChild(i), camera_list)
  1435. def generate_camera_name_list(scene):
  1436. camera_list = []
  1437. node = scene.GetRootNode()
  1438. if node:
  1439. for i in range(node.GetChildCount()):
  1440. generate_camera_name_list_from_hierarchy(node.GetChild(i), camera_list)
  1441. return camera_list
  1442. # #####################################################
  1443. # Generate Mesh Node Object
  1444. # #####################################################
  1445. def generate_mesh_object(node):
  1446. mesh = node.GetNodeAttribute()
  1447. transform = node.EvaluateLocalTransform()
  1448. position = transform.GetT()
  1449. scale = transform.GetS()
  1450. rotation = getRadians(transform.GetR())
  1451. quaternion = transform.GetQ()
  1452. material_count = node.GetMaterialCount()
  1453. material_name = ""
  1454. if material_count > 0:
  1455. material_names = []
  1456. for l in range(mesh.GetLayerCount()):
  1457. materials = mesh.GetLayer(l).GetMaterials()
  1458. if materials:
  1459. if materials.GetReferenceMode() == FbxLayerElement.eIndex:
  1460. #Materials are in an undefined external table
  1461. continue
  1462. for i in range(material_count):
  1463. material = node.GetMaterial(i)
  1464. material_names.append( getMaterialName(material) )
  1465. if not material_count > 1 and not len(material_names) > 0:
  1466. material_names.append('')
  1467. #If this mesh has more than one material, use a proxy material
  1468. material_name = getMaterialName( node, True) if material_count > 1 else material_names[0]
  1469. output = {
  1470. 'geometry': getPrefixedName( node, 'Geometry' ),
  1471. 'material': material_name,
  1472. 'position': serializeVector3( position ),
  1473. 'quaternion': serializeVector4( quaternion ),
  1474. 'scale': serializeVector3( scale ),
  1475. 'visible': True,
  1476. }
  1477. return output
  1478. # #####################################################
  1479. # Generate Node Object
  1480. # #####################################################
  1481. def generate_object(node):
  1482. node_types = ["Unknown", "Null", "Marker", "Skeleton", "Mesh", "Nurbs", "Patch", "Camera",
  1483. "CameraStereo", "CameraSwitcher", "Light", "OpticalReference", "OpticalMarker", "NurbsCurve",
  1484. "TrimNurbsSurface", "Boundary", "NurbsSurface", "Shape", "LODGroup", "SubDiv", "CachedEffect", "Line"]
  1485. transform = node.EvaluateLocalTransform()
  1486. position = transform.GetT()
  1487. scale = transform.GetS()
  1488. rotation = getRadians(transform.GetR())
  1489. quaternion = transform.GetQ()
  1490. node_type = ""
  1491. if node.GetNodeAttribute() == None:
  1492. node_type = "Null"
  1493. else:
  1494. node_type = node_types[node.GetNodeAttribute().GetAttributeType()]
  1495. name = getObjectName( node )
  1496. output = {
  1497. 'fbx_type': node_type,
  1498. 'position': serializeVector3( position ),
  1499. 'quaternion': serializeVector4( quaternion ),
  1500. 'scale': serializeVector3( scale ),
  1501. 'visible': True
  1502. }
  1503. return output
  1504. # #####################################################
  1505. # Parse Scene Node Objects
  1506. # #####################################################
  1507. def generate_object_hierarchy(node, object_dict):
  1508. object_count = 0
  1509. if node.GetNodeAttribute() == None:
  1510. object_data = generate_object(node)
  1511. else:
  1512. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  1513. if attribute_type == FbxNodeAttribute.eMesh:
  1514. object_data = generate_mesh_object(node)
  1515. elif attribute_type == FbxNodeAttribute.eLight:
  1516. object_data = generate_light_object(node)
  1517. elif attribute_type == FbxNodeAttribute.eCamera:
  1518. object_data = generate_camera_object(node)
  1519. else:
  1520. object_data = generate_object(node)
  1521. object_count += 1
  1522. object_name = getObjectName(node)
  1523. object_children = {}
  1524. for i in range(node.GetChildCount()):
  1525. object_count += generate_object_hierarchy(node.GetChild(i), object_children)
  1526. if node.GetChildCount() > 0:
  1527. # Having 'children' above other attributes is hard to read.
  1528. # We can send it to the bottom using the last letter of the alphabet 'z'.
  1529. # This letter is removed from the final output.
  1530. if option_pretty_print:
  1531. object_data['zchildren'] = object_children
  1532. else:
  1533. object_data['children'] = object_children
  1534. object_dict[object_name] = object_data
  1535. return object_count
  1536. def generate_scene_objects(scene):
  1537. object_count = 0
  1538. object_dict = {}
  1539. ambient_light = generate_ambient_light(scene)
  1540. if ambient_light:
  1541. object_dict['AmbientLight'] = ambient_light
  1542. object_count += 1
  1543. if option_default_light:
  1544. default_light = generate_default_light()
  1545. object_dict['DefaultLight'] = default_light
  1546. object_count += 1
  1547. if option_default_camera:
  1548. default_camera = generate_default_camera()
  1549. object_dict['DefaultCamera'] = default_camera
  1550. object_count += 1
  1551. node = scene.GetRootNode()
  1552. if node:
  1553. for i in range(node.GetChildCount()):
  1554. object_count += generate_object_hierarchy(node.GetChild(i), object_dict)
  1555. return object_dict, object_count
  1556. # #####################################################
  1557. # Generate Scene Output
  1558. # #####################################################
  1559. def extract_scene(scene, filename):
  1560. global_settings = scene.GetGlobalSettings()
  1561. objects, nobjects = generate_scene_objects(scene)
  1562. textures = generate_texture_dict(scene)
  1563. materials = generate_material_dict(scene)
  1564. geometries = generate_geometry_dict(scene)
  1565. embeds = generate_embed_dict(scene)
  1566. ntextures = len(textures)
  1567. nmaterials = len(materials)
  1568. ngeometries = len(geometries)
  1569. position = serializeVector3( (0,0,0) )
  1570. rotation = serializeVector3( (0,0,0) )
  1571. scale = serializeVector3( (1,1,1) )
  1572. camera_names = generate_camera_name_list(scene)
  1573. scene_settings = scene.GetGlobalSettings()
  1574. # This does not seem to be any help here
  1575. # global_settings.GetDefaultCamera()
  1576. defcamera = camera_names[0] if len(camera_names) > 0 else ""
  1577. if option_default_camera:
  1578. defcamera = 'default_camera'
  1579. metadata = {
  1580. 'formatVersion': 3.2,
  1581. 'type': 'scene',
  1582. 'generatedBy': 'convert-to-threejs.py',
  1583. 'objects': nobjects,
  1584. 'geometries': ngeometries,
  1585. 'materials': nmaterials,
  1586. 'textures': ntextures
  1587. }
  1588. transform = {
  1589. 'position' : position,
  1590. 'rotation' : rotation,
  1591. 'scale' : scale
  1592. }
  1593. defaults = {
  1594. 'bgcolor' : 0,
  1595. 'camera' : defcamera,
  1596. 'fog' : ''
  1597. }
  1598. output = {
  1599. 'objects': objects,
  1600. 'geometries': geometries,
  1601. 'materials': materials,
  1602. 'textures': textures,
  1603. 'embeds': embeds,
  1604. 'transform': transform,
  1605. 'defaults': defaults,
  1606. }
  1607. if option_pretty_print:
  1608. output['0metadata'] = metadata
  1609. else:
  1610. output['metadata'] = metadata
  1611. return output
  1612. # #####################################################
  1613. # Generate Non-Scene Output
  1614. # #####################################################
  1615. def extract_geometry(scene, filename):
  1616. output = generate_non_scene_output(scene)
  1617. return output
  1618. # #####################################################
  1619. # File Helpers
  1620. # #####################################################
  1621. def write_file(filepath, content):
  1622. index = filepath.rfind('/')
  1623. dir = filepath[0:index]
  1624. if not os.path.exists(dir):
  1625. os.makedirs(dir)
  1626. out = open(filepath, "w")
  1627. out.write(content.encode('utf8', 'replace'))
  1628. out.close()
  1629. def read_file(filepath):
  1630. f = open(filepath)
  1631. content = f.readlines()
  1632. f.close()
  1633. return content
  1634. def copy_textures(textures):
  1635. texture_dict = {}
  1636. for key in textures:
  1637. url = textures[key]['url']
  1638. src = replace_OutFolder2inFolder(url)
  1639. if url in texture_dict: # texture has been copied
  1640. continue
  1641. if not os.path.exists(src):
  1642. print("copy_texture error: we can't find this texture at " + src)
  1643. continue
  1644. try:
  1645. index = url.rfind('/')
  1646. folder = url[0:index]
  1647. if len(folder) and not os.path.exists(folder):
  1648. os.makedirs(folder)
  1649. shutil.copyfile(src, url)
  1650. texture_dict[url] = True
  1651. except IOError as e:
  1652. print "I/O error({0}): {1} {2}".format(e.errno, e.strerror, src)
  1653. def findFilesWithExt(directory, ext, include_path = True):
  1654. ext = ext.lower()
  1655. found = []
  1656. for root, dirs, files in os.walk(directory):
  1657. for filename in files:
  1658. current_ext = os.path.splitext(filename)[1].lower()
  1659. if current_ext == ext:
  1660. if include_path:
  1661. found.append(os.path.join(root, filename))
  1662. else:
  1663. found.append(filename)
  1664. return found
  1665. # #####################################################
  1666. # main
  1667. # #####################################################
  1668. if __name__ == "__main__":
  1669. from optparse import OptionParser
  1670. try:
  1671. from FbxCommon import *
  1672. except ImportError:
  1673. import platform
  1674. msg = 'Could not locate the python FBX SDK!\n'
  1675. msg += 'You need to copy the FBX SDK into your python install folder such as '
  1676. if platform.system() == 'Windows' or platform.system() == 'Microsoft':
  1677. msg += '"Python26/Lib/site-packages"'
  1678. elif platform.system() == 'Linux':
  1679. msg += '"/usr/local/lib/python2.6/site-packages"'
  1680. elif platform.system() == 'Darwin':
  1681. msg += '"/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages"'
  1682. msg += ' folder.'
  1683. print(msg)
  1684. sys.exit(1)
  1685. usage = "Usage: %prog [source_file.fbx] [output_file.js] [options]"
  1686. parser = OptionParser(usage=usage)
  1687. parser.add_option('-t', '--triangulate', action='store_true', dest='triangulate', help="force quad geometry into triangles", default=False)
  1688. parser.add_option('-x', '--ignore-textures', action='store_true', dest='notextures', help="don't include texture references in output file", default=False)
  1689. parser.add_option('-u', '--force-prefix', action='store_true', dest='prefix', help="prefix all object names in output file to ensure uniqueness", default=False)
  1690. parser.add_option('-f', '--flatten-scene', action='store_true', dest='geometry', help="merge all geometries and apply node transforms", default=False)
  1691. parser.add_option('-c', '--add-camera', action='store_true', dest='defcamera', help="include default camera in output scene", default=False)
  1692. parser.add_option('-l', '--add-light', action='store_true', dest='deflight', help="include default light in output scene", default=False)
  1693. parser.add_option('-p', '--pretty-print', action='store_true', dest='pretty', help="prefix all object names in output file", default=False)
  1694. (options, args) = parser.parse_args()
  1695. option_triangulate = options.triangulate
  1696. option_textures = True if not options.notextures else False
  1697. option_prefix = options.prefix
  1698. option_geometry = options.geometry
  1699. option_default_camera = options.defcamera
  1700. option_default_light = options.deflight
  1701. option_pretty_print = options.pretty
  1702. # Prepare the FBX SDK.
  1703. sdk_manager, scene = InitializeSdkObjects()
  1704. converter = FbxGeometryConverter(sdk_manager)
  1705. # The converter takes an FBX file as an argument.
  1706. if len(args) > 1:
  1707. print("\nLoading file: %s" % args[0])
  1708. result = LoadScene(sdk_manager, scene, args[0])
  1709. else:
  1710. result = False
  1711. print("\nUsage: convert_fbx_to_threejs [source_file.fbx] [output_file.js]\n")
  1712. if not result:
  1713. print("\nAn error occurred while loading the file...")
  1714. else:
  1715. if option_triangulate:
  1716. print("\nForcing geometry to triangles")
  1717. triangulate_scene(scene)
  1718. # According to asset's coordinate to convert scene
  1719. upVector = scene.GetGlobalSettings().GetAxisSystem().GetUpVector();
  1720. axis_system = FbxAxisSystem.MayaYUp
  1721. if upVector[0] == 3:
  1722. axis_system = FbxAxisSystem.MayaZUp
  1723. axis_system.ConvertScene(scene)
  1724. inputFolder = args[0].replace( "\\", "/" );
  1725. index = args[0].rfind( "/" );
  1726. inputFolder = inputFolder[:index]
  1727. outputFolder = args[1].replace( "\\", "/" );
  1728. index = args[1].rfind( "/" );
  1729. outputFolder = outputFolder[:index]
  1730. if option_geometry:
  1731. output_content = extract_geometry(scene, os.path.basename(args[0]))
  1732. else:
  1733. output_content = extract_scene(scene, os.path.basename(args[0]))
  1734. if option_pretty_print:
  1735. output_string = json.dumps(output_content, indent=4, cls=CustomEncoder, separators=(',', ': '), sort_keys=True)
  1736. output_string = executeRegexHacks(output_string)
  1737. else:
  1738. output_string = json.dumps(output_content, separators=(',', ': '), sort_keys=True)
  1739. output_path = os.path.join(os.getcwd(), args[1])
  1740. write_file(output_path, output_string)
  1741. copy_textures( output_content['textures'] )
  1742. print("\nExported Three.js file to:\n%s\n" % output_path)
  1743. # Destroy all objects created by the FBX SDK.
  1744. sdk_manager.Destroy()
  1745. sys.exit(0)