convert_to_threejs.py 76 KB

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