convert_to_threejs.py 75 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(class_id)
  162. for i in range(object_count):
  163. other = scene.GetSrcObject(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(FbxLayeredTexture.ClassId)
  259. if layered_texture_count > 0:
  260. for j in range(layered_texture_count):
  261. layered_texture = material_property.GetSrcObject(FbxLayeredTexture.ClassId, j)
  262. texture_count = layered_texture.GetSrcObjectCount(FbxTexture.ClassId)
  263. for k in range(texture_count):
  264. texture = layered_texture.GetSrcObject(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(FbxTexture.ClassId)
  271. for j in range(texture_count):
  272. texture = material_property.GetSrcObject(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(FbxSurfaceMaterial.ClassId)
  410. for i in range(material_count):
  411. material = scene.GetSrcObject(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(FbxLayeredTexture.ClassId)
  476. if layered_texture_count > 0:
  477. for j in range(layered_texture_count):
  478. layered_texture = material_property.GetSrcObject(FbxLayeredTexture.ClassId, j)
  479. texture_count = layered_texture.GetSrcObjectCount(FbxTexture.ClassId)
  480. for k in range(texture_count):
  481. texture = layered_texture.GetSrcObject(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(FbxTexture.ClassId)
  489. for j in range(texture_count):
  490. texture = material_property.GetSrcObject(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(FbxSurfaceMaterial.ClassId)
  500. for material_index in range(material_count):
  501. material = mesh.GetNode().GetSrcObject(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. return output
  1369. def generate_ambient_light(scene):
  1370. scene_settings = scene.GetGlobalSettings()
  1371. ambient_color = scene_settings.GetAmbientColor()
  1372. ambient_color = (ambient_color.mRed, ambient_color.mGreen, ambient_color.mBlue)
  1373. if ambient_color[0] == 0 and ambient_color[1] == 0 and ambient_color[2] == 0:
  1374. return None
  1375. output = {
  1376. 'type': 'AmbientLight',
  1377. 'color': getHex(ambient_color)
  1378. }
  1379. return output
  1380. # #####################################################
  1381. # Generate Camera Node Objects
  1382. # #####################################################
  1383. def generate_default_camera():
  1384. position = (100, 100, 100)
  1385. near = 0.1
  1386. far = 1000
  1387. fov = 75
  1388. output = {
  1389. 'type': 'PerspectiveCamera',
  1390. 'fov': fov,
  1391. 'near': near,
  1392. 'far': far,
  1393. 'position': serializeVector3( position )
  1394. }
  1395. return output
  1396. def generate_camera_object(node):
  1397. camera = node.GetNodeAttribute()
  1398. position = camera.Position.Get()
  1399. projection_types = [ "perspective", "orthogonal" ]
  1400. projection = projection_types[camera.ProjectionType.Get()]
  1401. near = camera.NearPlane.Get()
  1402. far = camera.FarPlane.Get()
  1403. name = getObjectName( node )
  1404. output = {}
  1405. if projection == "perspective":
  1406. aspect = camera.PixelAspectRatio.Get()
  1407. fov = camera.FieldOfView.Get()
  1408. output = {
  1409. 'type': 'PerspectiveCamera',
  1410. 'fov': fov,
  1411. 'aspect': aspect,
  1412. 'near': near,
  1413. 'far': far,
  1414. 'position': serializeVector3( position )
  1415. }
  1416. elif projection == "orthogonal":
  1417. left = ""
  1418. right = ""
  1419. top = ""
  1420. bottom = ""
  1421. output = {
  1422. 'type': 'PerspectiveCamera',
  1423. 'left': left,
  1424. 'right': right,
  1425. 'top': top,
  1426. 'bottom': bottom,
  1427. 'near': near,
  1428. 'far': far,
  1429. 'position': serializeVector3( position )
  1430. }
  1431. return output
  1432. # #####################################################
  1433. # Generate Camera Names
  1434. # #####################################################
  1435. def generate_camera_name_list_from_hierarchy(node, camera_list):
  1436. if node.GetNodeAttribute() == None:
  1437. pass
  1438. else:
  1439. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  1440. if attribute_type == FbxNodeAttribute.eCamera:
  1441. camera_string = getObjectName(node)
  1442. camera_list.append(camera_string)
  1443. for i in range(node.GetChildCount()):
  1444. generate_camera_name_list_from_hierarchy(node.GetChild(i), camera_list)
  1445. def generate_camera_name_list(scene):
  1446. camera_list = []
  1447. node = scene.GetRootNode()
  1448. if node:
  1449. for i in range(node.GetChildCount()):
  1450. generate_camera_name_list_from_hierarchy(node.GetChild(i), camera_list)
  1451. return camera_list
  1452. # #####################################################
  1453. # Generate Mesh Node Object
  1454. # #####################################################
  1455. def generate_mesh_object(node):
  1456. mesh = node.GetNodeAttribute()
  1457. transform = node.EvaluateLocalTransform()
  1458. position = transform.GetT()
  1459. scale = transform.GetS()
  1460. rotation = getRadians(transform.GetR())
  1461. quaternion = transform.GetQ()
  1462. material_count = node.GetMaterialCount()
  1463. material_name = ""
  1464. if material_count > 0:
  1465. material_names = []
  1466. for l in range(mesh.GetLayerCount()):
  1467. materials = mesh.GetLayer(l).GetMaterials()
  1468. if materials:
  1469. if materials.GetReferenceMode() == FbxLayerElement.eIndex:
  1470. #Materials are in an undefined external table
  1471. continue
  1472. for i in range(material_count):
  1473. material = node.GetMaterial(i)
  1474. material_names.append( getMaterialName(material) )
  1475. if not material_count > 1 and not len(material_names) > 0:
  1476. material_names.append('')
  1477. #If this mesh has more than one material, use a proxy material
  1478. material_name = getMaterialName( node, True) if material_count > 1 else material_names[0]
  1479. output = {
  1480. 'geometry': getPrefixedName( node, 'Geometry' ),
  1481. 'material': material_name,
  1482. 'position': serializeVector3( position ),
  1483. 'quaternion': serializeVector4( quaternion ),
  1484. 'scale': serializeVector3( scale ),
  1485. 'visible': True,
  1486. }
  1487. return output
  1488. # #####################################################
  1489. # Generate Node Object
  1490. # #####################################################
  1491. def generate_object(node):
  1492. node_types = ["Unknown", "Null", "Marker", "Skeleton", "Mesh", "Nurbs", "Patch", "Camera",
  1493. "CameraStereo", "CameraSwitcher", "Light", "OpticalReference", "OpticalMarker", "NurbsCurve",
  1494. "TrimNurbsSurface", "Boundary", "NurbsSurface", "Shape", "LODGroup", "SubDiv", "CachedEffect", "Line"]
  1495. transform = node.EvaluateLocalTransform()
  1496. position = transform.GetT()
  1497. scale = transform.GetS()
  1498. rotation = getRadians(transform.GetR())
  1499. quaternion = transform.GetQ()
  1500. node_type = ""
  1501. if node.GetNodeAttribute() == None:
  1502. node_type = "Null"
  1503. else:
  1504. node_type = node_types[node.GetNodeAttribute().GetAttributeType()]
  1505. name = getObjectName( node )
  1506. output = {
  1507. 'fbx_type': node_type,
  1508. 'position': serializeVector3( position ),
  1509. 'quaternion': serializeVector4( quaternion ),
  1510. 'scale': serializeVector3( scale ),
  1511. 'visible': True
  1512. }
  1513. return output
  1514. # #####################################################
  1515. # Parse Scene Node Objects
  1516. # #####################################################
  1517. def generate_object_hierarchy(node, object_dict):
  1518. object_count = 0
  1519. if node.GetNodeAttribute() == None:
  1520. object_data = generate_object(node)
  1521. else:
  1522. attribute_type = (node.GetNodeAttribute().GetAttributeType())
  1523. if attribute_type == FbxNodeAttribute.eMesh:
  1524. object_data = generate_mesh_object(node)
  1525. elif attribute_type == FbxNodeAttribute.eLight:
  1526. object_data = generate_light_object(node)
  1527. elif attribute_type == FbxNodeAttribute.eCamera:
  1528. object_data = generate_camera_object(node)
  1529. else:
  1530. object_data = generate_object(node)
  1531. object_count += 1
  1532. object_name = getObjectName(node)
  1533. object_children = {}
  1534. for i in range(node.GetChildCount()):
  1535. object_count += generate_object_hierarchy(node.GetChild(i), object_children)
  1536. if node.GetChildCount() > 0:
  1537. # Having 'children' above other attributes is hard to read.
  1538. # We can send it to the bottom using the last letter of the alphabet 'z'.
  1539. # This letter is removed from the final output.
  1540. if option_pretty_print:
  1541. object_data['zchildren'] = object_children
  1542. else:
  1543. object_data['children'] = object_children
  1544. object_dict[object_name] = object_data
  1545. return object_count
  1546. def generate_scene_objects(scene):
  1547. object_count = 0
  1548. object_dict = {}
  1549. ambient_light = generate_ambient_light(scene)
  1550. if ambient_light:
  1551. object_dict['AmbientLight'] = ambient_light
  1552. object_count += 1
  1553. if option_default_light:
  1554. default_light = generate_default_light()
  1555. object_dict['DefaultLight'] = default_light
  1556. object_count += 1
  1557. if option_default_camera:
  1558. default_camera = generate_default_camera()
  1559. object_dict['DefaultCamera'] = default_camera
  1560. object_count += 1
  1561. node = scene.GetRootNode()
  1562. if node:
  1563. for i in range(node.GetChildCount()):
  1564. object_count += generate_object_hierarchy(node.GetChild(i), object_dict)
  1565. return object_dict, object_count
  1566. # #####################################################
  1567. # Generate Scene Output
  1568. # #####################################################
  1569. def extract_scene(scene, filename):
  1570. global_settings = scene.GetGlobalSettings()
  1571. objects, nobjects = generate_scene_objects(scene)
  1572. textures = generate_texture_dict(scene)
  1573. materials = generate_material_dict(scene)
  1574. geometries = generate_geometry_dict(scene)
  1575. embeds = generate_embed_dict(scene)
  1576. ntextures = len(textures)
  1577. nmaterials = len(materials)
  1578. ngeometries = len(geometries)
  1579. position = serializeVector3( (0,0,0) )
  1580. rotation = serializeVector3( (0,0,0) )
  1581. scale = serializeVector3( (1,1,1) )
  1582. camera_names = generate_camera_name_list(scene)
  1583. scene_settings = scene.GetGlobalSettings()
  1584. # This does not seem to be any help here
  1585. # global_settings.GetDefaultCamera()
  1586. defcamera = camera_names[0] if len(camera_names) > 0 else ""
  1587. if option_default_camera:
  1588. defcamera = 'default_camera'
  1589. metadata = {
  1590. 'formatVersion': 3.2,
  1591. 'type': 'scene',
  1592. 'generatedBy': 'convert-to-threejs.py',
  1593. 'objects': nobjects,
  1594. 'geometries': ngeometries,
  1595. 'materials': nmaterials,
  1596. 'textures': ntextures
  1597. }
  1598. transform = {
  1599. 'position' : position,
  1600. 'rotation' : rotation,
  1601. 'scale' : scale
  1602. }
  1603. defaults = {
  1604. 'bgcolor' : 0,
  1605. 'camera' : defcamera,
  1606. 'fog' : ''
  1607. }
  1608. output = {
  1609. 'objects': objects,
  1610. 'geometries': geometries,
  1611. 'materials': materials,
  1612. 'textures': textures,
  1613. 'embeds': embeds,
  1614. 'transform': transform,
  1615. 'defaults': defaults,
  1616. }
  1617. if option_pretty_print:
  1618. output['0metadata'] = metadata
  1619. else:
  1620. output['metadata'] = metadata
  1621. return output
  1622. # #####################################################
  1623. # Generate Non-Scene Output
  1624. # #####################################################
  1625. def extract_geometry(scene, filename):
  1626. output = generate_non_scene_output(scene)
  1627. return output
  1628. # #####################################################
  1629. # File Helpers
  1630. # #####################################################
  1631. def write_file(filepath, content):
  1632. index = filepath.rfind('/')
  1633. dir = filepath[0:index]
  1634. #if not os.path.exists(dir):
  1635. #os.makedirs(dir)
  1636. out = open(filepath, "w")
  1637. out.write(content.encode('utf8', 'replace'))
  1638. out.close()
  1639. def read_file(filepath):
  1640. f = open(filepath)
  1641. content = f.readlines()
  1642. f.close()
  1643. return content
  1644. def copy_textures(textures):
  1645. texture_dict = {}
  1646. for key in textures:
  1647. url = textures[key]['fullpath']
  1648. #src = replace_OutFolder2inFolder(url)
  1649. #print( src )
  1650. #print( url )
  1651. if url in texture_dict: # texture has been copied
  1652. continue
  1653. if not os.path.exists(url):
  1654. print("copy_texture error: we can't find this texture at " + url)
  1655. continue
  1656. try:
  1657. index = url.rfind('/')
  1658. if index == -1:
  1659. index = url.rfind( '\\' )
  1660. filename = url[index+1:len(url)]
  1661. saveFolder = "maps"
  1662. saveFilename = saveFolder + "/" + filename
  1663. #print( src )
  1664. #print( url )
  1665. #print( saveFilename )
  1666. if not os.path.exists(saveFolder):
  1667. os.makedirs(saveFolder)
  1668. shutil.copyfile(url, saveFilename)
  1669. texture_dict[url] = True
  1670. except IOError as e:
  1671. print ("I/O error({0}): {1} {2}").format(e.errno, e.strerror, url)
  1672. def findFilesWithExt(directory, ext, include_path = True):
  1673. ext = ext.lower()
  1674. found = []
  1675. for root, dirs, files in os.walk(directory):
  1676. for filename in files:
  1677. current_ext = os.path.splitext(filename)[1].lower()
  1678. if current_ext == ext:
  1679. if include_path:
  1680. found.append(os.path.join(root, filename))
  1681. else:
  1682. found.append(filename)
  1683. return found
  1684. # #####################################################
  1685. # main
  1686. # #####################################################
  1687. if __name__ == "__main__":
  1688. from optparse import OptionParser
  1689. try:
  1690. from FbxCommon import *
  1691. except ImportError:
  1692. import platform
  1693. msg = 'Could not locate the python FBX SDK!\n'
  1694. msg += 'You need to copy the FBX SDK into your python install folder such as '
  1695. if platform.system() == 'Windows' or platform.system() == 'Microsoft':
  1696. msg += '"Python26/Lib/site-packages"'
  1697. elif platform.system() == 'Linux':
  1698. msg += '"/usr/local/lib/python2.6/site-packages"'
  1699. elif platform.system() == 'Darwin':
  1700. msg += '"/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages"'
  1701. msg += ' folder.'
  1702. print(msg)
  1703. sys.exit(1)
  1704. usage = "Usage: %prog [source_file.fbx] [output_file.js] [options]"
  1705. parser = OptionParser(usage=usage)
  1706. parser.add_option('-t', '--triangulate', action='store_true', dest='triangulate', help="force quad geometry into triangles", default=False)
  1707. parser.add_option('-x', '--ignore-textures', action='store_true', dest='notextures', help="don't include texture references in output file", default=False)
  1708. parser.add_option('-n', '--no-texture-copy', action='store_true', dest='notexturecopy', help="don't copy texture files", default=False)
  1709. parser.add_option('-u', '--force-prefix', action='store_true', dest='prefix', help="prefix all object names in output file to ensure uniqueness", default=False)
  1710. parser.add_option('-f', '--flatten-scene', action='store_true', dest='geometry', help="merge all geometries and apply node transforms", default=False)
  1711. parser.add_option('-y', '--force-y-up', action='store_true', dest='forceyup', help="ensure that the y axis shows up", default=False)
  1712. parser.add_option('-c', '--add-camera', action='store_true', dest='defcamera', help="include default camera in output scene", default=False)
  1713. parser.add_option('-l', '--add-light', action='store_true', dest='deflight', help="include default light in output scene", default=False)
  1714. parser.add_option('-p', '--pretty-print', action='store_true', dest='pretty', help="prefix all object names in output file", default=False)
  1715. (options, args) = parser.parse_args()
  1716. option_triangulate = options.triangulate
  1717. option_textures = True if not options.notextures else False
  1718. option_copy_textures = True if not options.notexturecopy else False
  1719. option_prefix = options.prefix
  1720. option_geometry = options.geometry
  1721. option_forced_y_up = options.forceyup
  1722. option_default_camera = options.defcamera
  1723. option_default_light = options.deflight
  1724. option_pretty_print = options.pretty
  1725. # Prepare the FBX SDK.
  1726. sdk_manager, scene = InitializeSdkObjects()
  1727. converter = FbxGeometryConverter(sdk_manager)
  1728. # The converter takes an FBX file as an argument.
  1729. if len(args) > 1:
  1730. print("\nLoading file: %s" % args[0])
  1731. result = LoadScene(sdk_manager, scene, args[0])
  1732. else:
  1733. result = False
  1734. print("\nUsage: convert_fbx_to_threejs [source_file.fbx] [output_file.js]\n")
  1735. if not result:
  1736. print("\nAn error occurred while loading the file...")
  1737. else:
  1738. if option_triangulate:
  1739. print("\nForcing geometry to triangles")
  1740. triangulate_scene(scene)
  1741. axis_system = FbxAxisSystem.MayaYUp
  1742. if not option_forced_y_up:
  1743. # According to asset's coordinate to convert scene
  1744. upVector = scene.GetGlobalSettings().GetAxisSystem().GetUpVector();
  1745. if upVector[0] == 3:
  1746. axis_system = FbxAxisSystem.MayaZUp
  1747. axis_system.ConvertScene(scene)
  1748. inputFolder = args[0].replace( "\\", "/" );
  1749. index = args[0].rfind( "/" );
  1750. inputFolder = inputFolder[:index]
  1751. outputFolder = args[1].replace( "\\", "/" );
  1752. index = args[1].rfind( "/" );
  1753. outputFolder = outputFolder[:index]
  1754. if option_geometry:
  1755. output_content = extract_geometry(scene, os.path.basename(args[0]))
  1756. else:
  1757. output_content = extract_scene(scene, os.path.basename(args[0]))
  1758. if option_pretty_print:
  1759. output_string = json.dumps(output_content, indent=4, cls=CustomEncoder, separators=(',', ': '), sort_keys=True)
  1760. output_string = executeRegexHacks(output_string)
  1761. else:
  1762. output_string = json.dumps(output_content, separators=(',', ': '), sort_keys=True)
  1763. output_path = os.path.join(os.getcwd(), args[1])
  1764. write_file(output_path, output_string)
  1765. if option_copy_textures:
  1766. copy_textures( output_content['textures'] )
  1767. print("\nExported Three.js file to:\n%s\n" % output_path)
  1768. # Destroy all objects created by the FBX SDK.
  1769. sdk_manager.Destroy()
  1770. sys.exit(0)