convert_to_threejs.py 76 KB

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