FBXLoader.js 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250
  1. /**
  2. * @author yamahigashi https://github.com/yamahigashi
  3. * @author Kyle-Larson https://github.com/Kyle-Larson
  4. *
  5. * This loader loads FBX file in *ASCII and version 7 format*.
  6. *
  7. * Support
  8. * - mesh
  9. * - skinning
  10. * - normal / uv
  11. * - material (Multi-Material too)
  12. * - textures (Must be in same directory)
  13. * - nurbs (Open, Closed and Periodic forms)
  14. *
  15. * No Support
  16. * - morph
  17. */
  18. ( function () {
  19. THREE.FBXLoader = function ( manager ) {
  20. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  21. this.textureLoader = null;
  22. this.textureBasePath = null;
  23. };
  24. Object.assign( THREE.FBXLoader.prototype, {
  25. load: function ( url, onLoad, onProgress, onError ) {
  26. var scope = this;
  27. var loader = new THREE.FileLoader( scope.manager );
  28. // loader.setCrossOrigin( this.crossOrigin );
  29. loader.load( url, function ( text ) {
  30. if ( ! scope.isFbxFormatASCII( text ) ) {
  31. console.warn( 'FBXLoader: !!! FBX Binary format not supported !!!' );
  32. } else if ( ! scope.isFbxVersionSupported( text ) ) {
  33. console.warn( 'FBXLoader: !!! FBX Version below 7 not supported !!!' );
  34. } else {
  35. scope.textureBasePath = scope.extractUrlBase( url );
  36. onLoad( scope.parse( text ) );
  37. }
  38. }, onProgress, onError );
  39. },
  40. setCrossOrigin: function ( value ) {
  41. this.crossOrigin = value;
  42. },
  43. isFbxFormatASCII: function ( body ) {
  44. var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  45. var cursor = 0;
  46. var read = function ( offset ) {
  47. var result = body[ offset - 1 ];
  48. body = body.slice( cursor + offset );
  49. cursor ++;
  50. return result;
  51. };
  52. for ( var i = 0; i < CORRECT.length; ++ i ) {
  53. var num = read( 1 );
  54. if ( num == CORRECT[ i ] ) {
  55. return false;
  56. }
  57. }
  58. return true;
  59. },
  60. isFbxVersionSupported: function ( body ) {
  61. var versionExp = /FBXVersion: (\d+)/;
  62. var match = body.match( versionExp );
  63. if ( match ) {
  64. var version = parseInt( match[ 1 ] );
  65. console.log( 'FBXLoader: FBX version ' + version );
  66. return version >= 7000;
  67. }
  68. return false;
  69. },
  70. parse: function ( text ) {
  71. var scope = this;
  72. console.time( 'FBXLoader' );
  73. console.time( 'FBXLoader: TextParser' );
  74. var nodes = new FBXParser().parse( text );
  75. console.timeEnd( 'FBXLoader: TextParser' );
  76. console.time( 'FBXLoader: ObjectParser' );
  77. scope.hierarchy = ( new Bones() ).parseHierarchy( nodes );
  78. scope.weights = ( new Weights() ).parse( nodes, scope.hierarchy );
  79. scope.animations = ( new Animation() ).parse( nodes, scope.hierarchy );
  80. scope.textures = ( new Textures() ).parse( nodes, scope.hierarchy );
  81. scope.materials = ( new Materials() ).parse( nodes, scope.hierarchy );
  82. scope.geometries = ( new Geometries() ).parse( nodes, scope.hierarchy );
  83. console.timeEnd( 'FBXLoader: ObjectParser' );
  84. this.texture_cache = {};
  85. this.material_cache = {};
  86. this.geometry_cache = {};
  87. console.time( 'FBXLoader: MeshParser' );
  88. var meshes = this.parseMeshes( nodes );
  89. console.timeEnd( 'FBXLoader: MeshParser' );
  90. var container = new THREE.Group();
  91. for ( var i = 0; i < meshes.length; ++ i ) {
  92. if ( meshes[ i ] === undefined ) {
  93. continue;
  94. }
  95. container.add( meshes[ i ] );
  96. //wireframe = new THREE.WireframeHelper( geometries[i], 0x00ff00 );
  97. //container.add( wireframe );
  98. //vnh = new THREE.VertexNormalsHelper( geometries[i], 0.6 );
  99. //container.add( vnh );
  100. //skh = new THREE.SkeletonHelper( geometries[i] );
  101. //container.add( skh );
  102. // container.add( new THREE.BoxHelper( geometries[i] ) );
  103. }
  104. console.timeEnd( 'FBXLoader' );
  105. return container;
  106. },
  107. getTexture: function ( texNode ) {
  108. if ( ! ( texNode.id in this.texture_cache ) ) {
  109. if ( this.textureLoader === null ) {
  110. this.textureLoader = new THREE.TextureLoader();
  111. }
  112. this.texture_cache[ texNode.id ] = this.textureLoader.load( this.textureBasePath + '/' + texNode.fileName );
  113. }
  114. return this.texture_cache[ texNode.id ];
  115. },
  116. getMaterial: function ( matNode, nodes ) {
  117. if ( ! ( matNode.id in this.material_cache ) ) {
  118. // TODO:
  119. // Cannot find a list of possible ShadingModel values.
  120. // If someone finds a list, please add additional cases
  121. // and map to appropriate materials.
  122. var tmpMat;
  123. switch ( matNode.type ) {
  124. case "phong":
  125. tmpMat = new THREE.MeshPhongMaterial();
  126. break;
  127. case "lambert":
  128. tmpMat = new THREE.MeshLambertMaterial();
  129. break;
  130. default:
  131. console.warn( "No implementation given for material type " + matNode.type + " in FBXLoader.js. Defaulting to basic material" );
  132. tmpMat = new THREE.MeshBasicMaterial( { color: 0x3300ff } );
  133. break;
  134. }
  135. var children = nodes.searchConnectionChildren( matNode.id );
  136. for ( var i = 0; i < children.length; ++ i ) {
  137. var type = nodes.searchConnectionType( children[ i ], matNode.id );
  138. switch ( type ) {
  139. case " \"AmbientColor":
  140. //TODO: Support AmbientColor textures
  141. break;
  142. case " \"DiffuseColor":
  143. matNode.parameters.map = this.getTexture( this.textures.textures[ children[ i ] ] );
  144. break;
  145. default:
  146. console.warn( 'Unknown texture application of type ' + type + ', skipping texture' );
  147. break;
  148. }
  149. }
  150. tmpMat.setValues( matNode.parameters );
  151. this.material_cache[ matNode.id ] = tmpMat;
  152. }
  153. return this.material_cache[ matNode.id ];
  154. },
  155. getGeometry: function ( geoNode ) {
  156. if ( ! ( geoNode.id in this.geometry_cache ) ) {
  157. var tmpGeo = new THREE.BufferGeometry();
  158. tmpGeo.name = geoNode.name;
  159. tmpGeo.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( geoNode.vertices ), 3 ) );
  160. if ( geoNode.normals !== undefined && geoNode.normals.length > 0 ) {
  161. tmpGeo.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( geoNode.normals ), 3 ) );
  162. }
  163. if ( geoNode.uvs !== undefined && geoNode.uvs.length > 0 ) {
  164. tmpGeo.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( geoNode.uvs ), 2 ) );
  165. }
  166. if ( geoNode.indices !== undefined && geoNode.indices.length > 0 ) {
  167. tmpGeo.setIndex( geoNode.indices );
  168. }
  169. tmpGeo.verticesNeedUpdate = true;
  170. tmpGeo.computeBoundingSphere();
  171. tmpGeo.computeBoundingBox();
  172. //Material groupings
  173. if ( geoNode.materialIndices.length > 1 ) {
  174. tmpGeo.groups = [];
  175. for ( var i = 0, prevIndex = - 1; i < geoNode.materialIndices.length; ++ i ) {
  176. if ( geoNode.materialIndices[ i ] !== prevIndex ) {
  177. tmpGeo.groups.push( { start: i * 3, count: 0, materialIndex: geoNode.materialIndices[ i ] } );
  178. prevIndex = geoNode.materialIndices[ i ];
  179. }
  180. tmpGeo.groups[ tmpGeo.groups.length - 1 ].count += 3;
  181. }
  182. }
  183. this.geometry_cache[ geoNode.id ] = new THREE.Geometry().fromBufferGeometry( tmpGeo );
  184. this.geometry_cache[ geoNode.id ].bones = geoNode.bones;
  185. this.geometry_cache[ geoNode.id ].skinIndices = this.weights.skinIndices;
  186. this.geometry_cache[ geoNode.id ].skinWeights = this.weights.skinWeights;
  187. }
  188. return this.geometry_cache[ geoNode.id ];
  189. },
  190. parseMeshes: function ( node ) {
  191. var modelNode = node.Objects.subNodes.Model;
  192. var meshes = [];
  193. for ( var ID in modelNode ) {
  194. if ( modelNode[ ID ].attrType === 'Mesh' ) {
  195. //Parse Mesh
  196. meshes.push( this.parseMesh( modelNode[ ID ], node ) );
  197. } else if ( modelNode[ ID ].attrType === 'NurbsCurve' ) {
  198. //Parse NURBS
  199. meshes.push( this.parseNURBS( modelNode[ ID ], node ) );
  200. }
  201. }
  202. return meshes;
  203. },
  204. parseFloatList: function ( floatList ) {
  205. return floatList.split( ',' ).map( function ( number ) {
  206. return parseFloat( number );
  207. } );
  208. },
  209. parseNURBS: function ( meshNode, FBXNodes ) {
  210. if ( THREE.NURBSCurve === undefined ) {
  211. console.error( "THREE.FBXLoader relies on THREE.NURBSCurve" );
  212. return;
  213. }
  214. var geoNodes = FBXNodes.Objects.subNodes.Geometry;
  215. var children = FBXNodes.searchConnectionChildren( meshNode.id );
  216. var nurbsInfo;
  217. for ( var i = 0; i < children.length; ++ i ) {
  218. if ( children[ i ] in geoNodes ) {
  219. nurbsInfo = geoNodes[ children[ i ] ];
  220. break;
  221. }
  222. }
  223. if ( nurbsInfo === undefined ) {
  224. return;
  225. }
  226. var order = parseInt( nurbsInfo.properties.Order );
  227. if ( isNaN( order ) ) {
  228. console.error( "Invalid Order: `" + nurbsInfo.properties.Order + "` (should be an integer)" );
  229. return;
  230. }
  231. var degree = order - 1;
  232. var knots = this.parseFloatList( nurbsInfo.subNodes.KnotVector.properties.a );
  233. var controlPoints = [];
  234. var pointsValues = this.parseFloatList( nurbsInfo.subNodes.Points.properties.a );
  235. for ( var i = 0; i < pointsValues.length; i += 4 ) {
  236. // NURBSCurve recreates a Vector4, so no need to construct it twice
  237. controlPoints.push( { x: pointsValues[ i ], y: pointsValues[ i + 1 ], z: pointsValues[ i + 2 ], w: pointsValues[ i + 3 ] } );
  238. }
  239. var startKnot, endKnot;
  240. if ( nurbsInfo.properties.Form == "Closed" ) {
  241. controlPoints.push( controlPoints[ 0 ] );
  242. } else if ( nurbsInfo.properties.Form === 'Periodic' ) {
  243. startKnot = degree;
  244. endKnot = knots.length - 1 - startKnot;
  245. for ( var i = 0; i < degree; ++ i ) {
  246. controlPoints.push( controlPoints[ i ] );
  247. }
  248. }
  249. var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
  250. // Pre-generate a geometry
  251. var geometry = new THREE.Geometry();
  252. geometry.vertices = curve.getPoints( controlPoints.length * 7 );
  253. var mesh = new THREE.Line( geometry );
  254. // Store the THREE.NURBSCurve class so the user can recreate a new geometry with a different number of points
  255. mesh.userData.curve = curve;
  256. return mesh;
  257. },
  258. parseMesh: function ( meshNode, FBXNodes ) {
  259. var geoNodes = FBXNodes.Objects.subNodes.Geometry;
  260. var matNodes = FBXNodes.Objects.subNodes.Material;
  261. var children = FBXNodes.searchConnectionChildren( meshNode.id );
  262. var geometry;
  263. var materials = [];
  264. var material;
  265. var mesh;
  266. for ( var i = 0; i < children.length; ++ i ) {
  267. if ( children[ i ] in geoNodes ) {
  268. geometry = this.getGeometry( this.geometries.geometries[ children[ i ] ] );
  269. continue;
  270. }
  271. if ( children[ i ] in matNodes ) {
  272. materials.push( this.getMaterial( this.materials.materials[ children[ i ] ], FBXNodes ) );
  273. continue;
  274. }
  275. }
  276. if ( materials.length > 1 ) {
  277. material = new THREE.MultiMaterial( materials );
  278. //material = materials[ 0 ];
  279. } else {
  280. material = materials[ 0 ];
  281. }
  282. if ( geometry.bones !== undefined && geometry.skinWeights !== undefined && geometry.skinWeights.length > 0 ) {
  283. if ( material instanceof THREE.MultiMaterial ) {
  284. for ( var i = 0; i < material.materials.length; ++ i ) {
  285. material.materials[ i ].skinning = true;
  286. }
  287. } else {
  288. material.skinning = true;
  289. }
  290. mesh = new THREE.SkinnedMesh( geometry, material );
  291. } else {
  292. mesh = new THREE.Mesh( geometry, material );
  293. }
  294. if ( this.animations !== undefined ) {
  295. this.addAnimation( mesh, this.weights.matrices, this.animations );
  296. }
  297. return mesh;
  298. },
  299. addAnimation: function ( mesh, matrices, animations ) {
  300. for ( var key in animations.stacks ) {
  301. var animationData = {
  302. name: animations.stacks[ key ].name,
  303. fps: 30,
  304. length: animations.stacks[ key ].length,
  305. hierarchy: []
  306. };
  307. for ( var i = 0; i < mesh.geometry.bones.length; ++ i ) {
  308. var name = mesh.geometry.bones[ i ].name;
  309. name = name.replace( /.*:/, '' );
  310. animationData.hierarchy.push( { parent: mesh.geometry.bones[ i ].parent, name: name, keys: [] } );
  311. }
  312. function hasCurve( animNode, attr ) {
  313. if ( animNode === undefined ) {
  314. return false;
  315. }
  316. var attrNode;
  317. switch ( attr ) {
  318. case 'S':
  319. if ( ! ( animNode.S ) ) {
  320. return false;
  321. }
  322. attrNode = animNode.S;
  323. break;
  324. case 'R':
  325. if ( ! ( animNode.R ) ) {
  326. return false;
  327. }
  328. attrNode = animNode.R;
  329. break;
  330. case 'T':
  331. if ( ! ( animNode.T ) ) {
  332. return false;
  333. }
  334. attrNode = animNode.T;
  335. break;
  336. }
  337. if ( attrNode.curves.x === undefined ) {
  338. return false;
  339. }
  340. if ( attrNode.curves.y === undefined ) {
  341. return false;
  342. }
  343. if ( attrNode.curves.z === undefined ) {
  344. return false;
  345. }
  346. return true;
  347. }
  348. function hasKeyOnFrame( attrNode, frame ) {
  349. var x = isKeyExistOnFrame( attrNode.curves.x, frame );
  350. var y = isKeyExistOnFrame( attrNode.curves.y, frame );
  351. var z = isKeyExistOnFrame( attrNode.curves.z, frame );
  352. return x && y && z;
  353. }
  354. function isKeyExistOnFrame( curve, frame ) {
  355. var value = curve.values[ frame ];
  356. return value !== undefined;
  357. }
  358. function genKey( animNode, bone ) {
  359. // key initialize with its bone's bind pose at first
  360. var key = {};
  361. key.time = frame / animations.fps; // TODO:
  362. key.pos = bone.pos;
  363. key.rot = bone.rotq;
  364. key.scl = bone.scl;
  365. if ( animNode === undefined ) {
  366. return key;
  367. }
  368. try {
  369. if ( hasCurve( animNode, 'T' ) && hasKeyOnFrame( animNode.T, frame ) ) {
  370. var pos = new THREE.Vector3(
  371. animNode.T.curves.x.values[ frame ],
  372. animNode.T.curves.y.values[ frame ],
  373. animNode.T.curves.z.values[ frame ] );
  374. key.pos = [ pos.x, pos.y, pos.z ];
  375. }
  376. if ( hasCurve( animNode, 'R' ) && hasKeyOnFrame( animNode.R, frame ) ) {
  377. var rx = degToRad( animNode.R.curves.x.values[ frame ] );
  378. var ry = degToRad( animNode.R.curves.y.values[ frame ] );
  379. var rz = degToRad( animNode.R.curves.z.values[ frame ] );
  380. var eul = new THREE.Vector3( rx, ry, rz );
  381. var rot = quatFromVec( eul.x, eul.y, eul.z );
  382. key.rot = [ rot.x, rot.y, rot.z, rot.w ];
  383. }
  384. if ( hasCurve( animNode, 'S' ) && hasKeyOnFrame( animNode.S, frame ) ) {
  385. var scl = new THREE.Vector3(
  386. animNode.S.curves.x.values[ frame ],
  387. animNode.S.curves.y.values[ frame ],
  388. animNode.S.curves.z.values[ frame ] );
  389. key.scl = [ scl.x, scl.y, scl.z ];
  390. }
  391. } catch ( e ) {
  392. // curve is not full plotted
  393. console.log( bone );
  394. console.log( e );
  395. }
  396. return key;
  397. }
  398. var bones = mesh.geometry.bones;
  399. for ( var frame = 0; frame < animations.stacks[ key ].frames; frame ++ ) {
  400. for ( i = 0; i < bones.length; i ++ ) {
  401. var bone = bones[ i ];
  402. var animNode = animations.stacks[ key ].layers[ 0 ][ i ];
  403. for ( var j = 0; j < animationData.hierarchy.length; j ++ ) {
  404. if ( animationData.hierarchy[ j ].name === bone.name ) {
  405. animationData.hierarchy[ j ].keys.push( genKey( animNode, bone ) );
  406. }
  407. }
  408. }
  409. }
  410. if ( mesh.geometry.animations === undefined ) {
  411. mesh.geometry.animations = [];
  412. }
  413. mesh.geometry.animations.push( THREE.AnimationClip.parseAnimation( animationData, mesh.geometry.bones ) );
  414. }
  415. },
  416. loadFile: function ( url, onLoad, onProgress, onError, responseType ) {
  417. var loader = new THREE.FileLoader( this.manager );
  418. loader.setResponseType( responseType );
  419. var request = loader.load( url, onLoad, onProgress, onError );
  420. return request;
  421. },
  422. loadFileAsBuffer: function ( url, onLoad, onProgress, onError ) {
  423. this.loadFile( url, onLoad, onProgress, onError, 'arraybuffer' );
  424. },
  425. loadFileAsText: function ( url, onLoad, onProgress, onError ) {
  426. this.loadFile( url, onLoad, onProgress, onError, 'text' );
  427. }
  428. } );
  429. /* ----------------------------------------------------------------- */
  430. function FBXNodes() {}
  431. Object.assign( FBXNodes.prototype, {
  432. add: function ( key, val ) {
  433. this[ key ] = val;
  434. },
  435. searchConnectionParent: function ( id ) {
  436. if ( this.__cache_search_connection_parent === undefined ) {
  437. this.__cache_search_connection_parent = [];
  438. }
  439. if ( this.__cache_search_connection_parent[ id ] !== undefined ) {
  440. return this.__cache_search_connection_parent[ id ];
  441. } else {
  442. this.__cache_search_connection_parent[ id ] = [];
  443. }
  444. var conns = this.Connections.properties.connections;
  445. var results = [];
  446. for ( var i = 0; i < conns.length; ++ i ) {
  447. if ( conns[ i ][ 0 ] == id ) {
  448. // 0 means scene root
  449. var res = conns[ i ][ 1 ] === 0 ? - 1 : conns[ i ][ 1 ];
  450. results.push( res );
  451. }
  452. }
  453. if ( results.length > 0 ) {
  454. this.__cache_search_connection_parent[ id ] = this.__cache_search_connection_parent[ id ].concat( results );
  455. return results;
  456. } else {
  457. this.__cache_search_connection_parent[ id ] = [ - 1 ];
  458. return [ - 1 ];
  459. }
  460. },
  461. searchConnectionChildren: function ( id ) {
  462. if ( this.__cache_search_connection_children === undefined ) {
  463. this.__cache_search_connection_children = [];
  464. }
  465. if ( this.__cache_search_connection_children[ id ] !== undefined ) {
  466. return this.__cache_search_connection_children[ id ];
  467. } else {
  468. this.__cache_search_connection_children[ id ] = [];
  469. }
  470. var conns = this.Connections.properties.connections;
  471. var res = [];
  472. for ( var i = 0; i < conns.length; ++ i ) {
  473. if ( conns[ i ][ 1 ] == id ) {
  474. // 0 means scene root
  475. res.push( conns[ i ][ 0 ] === 0 ? - 1 : conns[ i ][ 0 ] );
  476. // there may more than one kid, then search to the end
  477. }
  478. }
  479. if ( res.length > 0 ) {
  480. this.__cache_search_connection_children[ id ] = this.__cache_search_connection_children[ id ].concat( res );
  481. return res;
  482. } else {
  483. this.__cache_search_connection_children[ id ] = [ ];
  484. return [ ];
  485. }
  486. },
  487. searchConnectionType: function ( id, to ) {
  488. var key = id + ',' + to; // TODO: to hash
  489. if ( this.__cache_search_connection_type === undefined ) {
  490. this.__cache_search_connection_type = {};
  491. }
  492. if ( this.__cache_search_connection_type[ key ] !== undefined ) {
  493. return this.__cache_search_connection_type[ key ];
  494. } else {
  495. this.__cache_search_connection_type[ key ] = '';
  496. }
  497. var conns = this.Connections.properties.connections;
  498. for ( var i = 0; i < conns.length; ++ i ) {
  499. if ( conns[ i ][ 0 ] == id && conns[ i ][ 1 ] == to ) {
  500. // 0 means scene root
  501. this.__cache_search_connection_type[ key ] = conns[ i ][ 2 ];
  502. return conns[ i ][ 2 ];
  503. }
  504. }
  505. this.__cache_search_connection_type[ id ] = null;
  506. return null;
  507. }
  508. } );
  509. function FBXParser() {}
  510. Object.assign( FBXParser.prototype, {
  511. getPrevNode: function () {
  512. return this.nodeStack[ this.currentIndent - 2 ];
  513. },
  514. getCurrentNode: function () {
  515. return this.nodeStack[ this.currentIndent - 1 ];
  516. },
  517. getCurrentProp: function () {
  518. return this.currentProp;
  519. },
  520. pushStack: function ( node ) {
  521. this.nodeStack.push( node );
  522. this.currentIndent += 1;
  523. },
  524. popStack: function () {
  525. this.nodeStack.pop();
  526. this.currentIndent -= 1;
  527. },
  528. setCurrentProp: function ( val, name ) {
  529. this.currentProp = val;
  530. this.currentPropName = name;
  531. },
  532. // ----------parse ---------------------------------------------------
  533. parse: function ( text ) {
  534. this.currentIndent = 0;
  535. this.allNodes = new FBXNodes();
  536. this.nodeStack = [];
  537. this.currentProp = [];
  538. this.currentPropName = '';
  539. var split = text.split( "\n" );
  540. for ( var line in split ) {
  541. var l = split[ line ];
  542. // short cut
  543. if ( l.match( /^[\s\t]*;/ ) ) {
  544. continue;
  545. } // skip comment line
  546. if ( l.match( /^[\s\t]*$/ ) ) {
  547. continue;
  548. } // skip empty line
  549. // beginning of node
  550. var beginningOfNodeExp = new RegExp( "^\\t{" + this.currentIndent + "}(\\w+):(.*){", '' );
  551. var match = l.match( beginningOfNodeExp );
  552. if ( match ) {
  553. var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, "" );
  554. var nodeAttrs = match[ 2 ].split( ',' ).map( function ( element ) {
  555. return element.trim().replace( /^"/, '' ).replace( /"$/, '' );
  556. } );
  557. this.parseNodeBegin( l, nodeName, nodeAttrs || null );
  558. continue;
  559. }
  560. // node's property
  561. var propExp = new RegExp( "^\\t{" + ( this.currentIndent ) + "}(\\w+):[\\s\\t\\r\\n](.*)" );
  562. var match = l.match( propExp );
  563. if ( match ) {
  564. var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, "" ).trim();
  565. var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, "" ).trim();
  566. this.parseNodeProperty( l, propName, propValue );
  567. continue;
  568. }
  569. // end of node
  570. var endOfNodeExp = new RegExp( "^\\t{" + ( this.currentIndent - 1 ) + "}}" );
  571. if ( l.match( endOfNodeExp ) ) {
  572. this.nodeEnd();
  573. continue;
  574. }
  575. // for special case,
  576. //
  577. // Vertices: *8670 {
  578. // a: 0.0356229953467846,13.9599733352661,-0.399196773.....(snip)
  579. // -0.0612030513584614,13.960485458374,-0.409748703241348,-0.10.....
  580. // 0.12490539252758,13.7450733184814,-0.454119384288788,0.09272.....
  581. // 0.0836158767342567,13.5432004928589,-0.435397416353226,0.028.....
  582. //
  583. // these case the lines must contiue with previous line
  584. if ( l.match( /^[^\s\t}]/ ) ) {
  585. this.parseNodePropertyContinued( l );
  586. }
  587. }
  588. return this.allNodes;
  589. },
  590. parseNodeBegin: function ( line, nodeName, nodeAttrs ) {
  591. // var nodeName = match[1];
  592. var node = { 'name': nodeName, properties: {}, 'subNodes': {} };
  593. var attrs = this.parseNodeAttr( nodeAttrs );
  594. var currentNode = this.getCurrentNode();
  595. // a top node
  596. if ( this.currentIndent === 0 ) {
  597. this.allNodes.add( nodeName, node );
  598. } else {
  599. // a subnode
  600. // already exists subnode, then append it
  601. if ( nodeName in currentNode.subNodes ) {
  602. var tmp = currentNode.subNodes[ nodeName ];
  603. // console.log( "duped entry found\nkey: " + nodeName + "\nvalue: " + propValue );
  604. if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) {
  605. if ( attrs.id === '' ) {
  606. currentNode.subNodes[ nodeName ] = [];
  607. currentNode.subNodes[ nodeName ].push( tmp );
  608. } else {
  609. currentNode.subNodes[ nodeName ] = {};
  610. currentNode.subNodes[ nodeName ][ tmp.id ] = tmp;
  611. }
  612. }
  613. if ( attrs.id === '' ) {
  614. currentNode.subNodes[ nodeName ].push( node );
  615. } else {
  616. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  617. }
  618. } else if ( typeof attrs.id === 'number' || attrs.id.match( /^\d+$/ ) ) {
  619. currentNode.subNodes[ nodeName ] = {};
  620. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  621. } else {
  622. currentNode.subNodes[ nodeName ] = node;
  623. }
  624. }
  625. // for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
  626. // NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" {
  627. if ( nodeAttrs ) {
  628. node.id = attrs.id;
  629. node.attrName = attrs.name;
  630. node.attrType = attrs.type;
  631. }
  632. this.pushStack( node );
  633. },
  634. parseNodeAttr: function ( attrs ) {
  635. var id = attrs[ 0 ];
  636. if ( attrs[ 0 ] !== "" ) {
  637. id = parseInt( attrs[ 0 ] );
  638. if ( isNaN( id ) ) {
  639. // PolygonVertexIndex: *16380 {
  640. id = attrs[ 0 ];
  641. }
  642. }
  643. var name;
  644. var type;
  645. if ( attrs.length > 1 ) {
  646. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  647. type = attrs[ 2 ];
  648. }
  649. return { id: id, name: name || '', type: type || '' };
  650. },
  651. parseNodeProperty: function ( line, propName, propValue ) {
  652. var currentNode = this.getCurrentNode();
  653. var parentName = currentNode.name;
  654. // special case parent node's is like "Properties70"
  655. // these chilren nodes must treat with careful
  656. if ( parentName !== undefined ) {
  657. var propMatch = parentName.match( /Properties(\d)+/ );
  658. if ( propMatch ) {
  659. this.parseNodeSpecialProperty( line, propName, propValue );
  660. return;
  661. }
  662. }
  663. // special case Connections
  664. if ( propName == 'C' ) {
  665. var connProps = propValue.split( ',' ).slice( 1 );
  666. var from = parseInt( connProps[ 0 ] );
  667. var to = parseInt( connProps[ 1 ] );
  668. var rest = propValue.split( ',' ).slice( 3 );
  669. propName = 'connections';
  670. propValue = [ from, to ];
  671. propValue = propValue.concat( rest );
  672. if ( currentNode.properties[ propName ] === undefined ) {
  673. currentNode.properties[ propName ] = [];
  674. }
  675. }
  676. // special case Connections
  677. if ( propName == 'Node' ) {
  678. var id = parseInt( propValue );
  679. currentNode.properties.id = id;
  680. currentNode.id = id;
  681. }
  682. // already exists in properties, then append this
  683. if ( propName in currentNode.properties ) {
  684. // console.log( "duped entry found\nkey: " + propName + "\nvalue: " + propValue );
  685. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  686. currentNode.properties[ propName ].push( propValue );
  687. } else {
  688. currentNode.properties[ propName ] += propValue;
  689. }
  690. } else {
  691. // console.log( propName + ": " + propValue );
  692. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  693. currentNode.properties[ propName ].push( propValue );
  694. } else {
  695. currentNode.properties[ propName ] = propValue;
  696. }
  697. }
  698. this.setCurrentProp( currentNode.properties, propName );
  699. },
  700. // TODO:
  701. parseNodePropertyContinued: function ( line ) {
  702. this.currentProp[ this.currentPropName ] += line;
  703. },
  704. parseNodeSpecialProperty: function ( line, propName, propValue ) {
  705. // split this
  706. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  707. // into array like below
  708. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  709. var props = propValue.split( '",' ).map( function ( element ) {
  710. return element.trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  711. } );
  712. var innerPropName = props[ 0 ];
  713. var innerPropType1 = props[ 1 ];
  714. var innerPropType2 = props[ 2 ];
  715. var innerPropFlag = props[ 3 ];
  716. var innerPropValue = props[ 4 ];
  717. /*
  718. if ( innerPropValue === undefined ) {
  719. innerPropValue = props[3];
  720. }
  721. */
  722. // cast value in its type
  723. switch ( innerPropType1 ) {
  724. case "int":
  725. innerPropValue = parseInt( innerPropValue );
  726. break;
  727. case "double":
  728. innerPropValue = parseFloat( innerPropValue );
  729. break;
  730. case "ColorRGB":
  731. case "Vector3D":
  732. var tmp = innerPropValue.split( ',' );
  733. innerPropValue = new THREE.Vector3( tmp[ 0 ], tmp[ 1 ], tmp[ 2 ] );
  734. break;
  735. }
  736. // CAUTION: these props must append to parent's parent
  737. this.getPrevNode().properties[ innerPropName ] = {
  738. 'type': innerPropType1,
  739. 'type2': innerPropType2,
  740. 'flag': innerPropFlag,
  741. 'value': innerPropValue
  742. };
  743. this.setCurrentProp( this.getPrevNode().properties, innerPropName );
  744. },
  745. nodeEnd: function () {
  746. this.popStack();
  747. },
  748. /* ---------------------------------------------------------------- */
  749. /* util */
  750. isFlattenNode: function ( node ) {
  751. return ( 'subNodes' in node && 'properties' in node ) ? true : false;
  752. }
  753. } );
  754. // generate skinIndices, skinWeights
  755. // @skinIndices: per vertex data, this represents the bone indexes affects that vertex
  756. // @skinWeights: per vertex data, this represents the Weight Values affects that vertex
  757. // @matrices: per `bones` data
  758. function Weights() {
  759. this.skinIndices = [];
  760. this.skinWeights = [];
  761. this.matrices = [];
  762. }
  763. Weights.prototype.parseCluster = function ( node, id, entry ) {
  764. var _p = node.searchConnectionParent( id );
  765. var _indices = parseArrayToInt( entry.subNodes.Indexes.properties.a );
  766. var _weights = parseArrayToFloat( entry.subNodes.Weights.properties.a );
  767. var _transform = parseArrayToMatrix( entry.subNodes.Transform.properties.a );
  768. var _link = parseArrayToMatrix( entry.subNodes.TransformLink.properties.a );
  769. return {
  770. 'parent': _p,
  771. 'id': parseInt( id ),
  772. 'indices': _indices,
  773. 'weights': _weights,
  774. 'transform': _transform,
  775. 'transformlink': _link,
  776. 'linkMode': entry.properties.Mode
  777. };
  778. };
  779. Weights.prototype.parse = function ( node, bones ) {
  780. this.skinIndices = [];
  781. this.skinWeights = [];
  782. this.matrices = [];
  783. var deformers = node.Objects.subNodes.Deformer;
  784. var clusters = {};
  785. for ( var id in deformers ) {
  786. if ( deformers[ id ].attrType === 'Cluster' ) {
  787. if ( ! ( 'Indexes' in deformers[ id ].subNodes ) ) {
  788. continue;
  789. }
  790. //clusters.push( this.parseCluster( node, id, deformers[id] ) );
  791. var cluster = this.parseCluster( node, id, deformers[ id ] );
  792. var boneId = node.searchConnectionChildren( cluster.id )[ 0 ];
  793. clusters[ boneId ] = cluster;
  794. }
  795. }
  796. // this clusters is per Bone data, thus we make this into per vertex data
  797. var weights = [];
  798. var hi = bones.hierarchy;
  799. for ( var b = 0; b < hi.length; ++ b ) {
  800. var bid = hi[ b ].internalId;
  801. if ( clusters[ bid ] === undefined ) {
  802. //console.log( bid );
  803. this.matrices.push( new THREE.Matrix4() );
  804. continue;
  805. }
  806. var clst = clusters[ bid ];
  807. // store transform matrix per bones
  808. this.matrices.push( clst.transform );
  809. //this.matrices.push( clst.transformlink );
  810. for ( var v = 0; v < clst.indices.length; ++ v ) {
  811. if ( weights[ clst.indices[ v ] ] === undefined ) {
  812. weights[ clst.indices[ v ] ] = {};
  813. weights[ clst.indices[ v ] ].joint = [];
  814. weights[ clst.indices[ v ] ].weight = [];
  815. }
  816. // indices
  817. var affect = node.searchConnectionChildren( clst.id );
  818. if ( affect.length > 1 ) {
  819. console.warn( "FBXLoader: node " + clst.id + " have many weight kids: " + affect );
  820. }
  821. weights[ clst.indices[ v ] ].joint.push( bones.getBoneIdfromInternalId( node, affect[ 0 ] ) );
  822. // weight value
  823. weights[ clst.indices[ v ] ].weight.push( clst.weights[ v ] );
  824. }
  825. }
  826. // normalize the skin weights
  827. // TODO - this might be a good place to choose greatest 4 weights
  828. for ( var i = 0; i < weights.length; i ++ ) {
  829. if ( weights[ i ] === undefined ) {
  830. this.skinIndices.push( new THREE.Vector4( 0, 0, 0, 0 ) );
  831. this.skinWeights.push( new THREE.Vector4( 0, 0, 0, 0 ) );
  832. continue;
  833. }
  834. var indicies = new THREE.Vector4(
  835. weights[ i ].joint[ 0 ] ? weights[ i ].joint[ 0 ] : 0,
  836. weights[ i ].joint[ 1 ] ? weights[ i ].joint[ 1 ] : 0,
  837. weights[ i ].joint[ 2 ] ? weights[ i ].joint[ 2 ] : 0,
  838. weights[ i ].joint[ 3 ] ? weights[ i ].joint[ 3 ] : 0 );
  839. var weight = new THREE.Vector4(
  840. weights[ i ].weight[ 0 ] ? weights[ i ].weight[ 0 ] : 0,
  841. weights[ i ].weight[ 1 ] ? weights[ i ].weight[ 1 ] : 0,
  842. weights[ i ].weight[ 2 ] ? weights[ i ].weight[ 2 ] : 0,
  843. weights[ i ].weight[ 3 ] ? weights[ i ].weight[ 3 ] : 0 );
  844. this.skinIndices.push( indicies );
  845. this.skinWeights.push( weight );
  846. }
  847. //console.log( this );
  848. return this;
  849. };
  850. function Bones() {
  851. // returns bones hierarchy tree.
  852. // [
  853. // {
  854. // "parent": id,
  855. // "name": name,
  856. // "pos": pos,
  857. // "rotq": quat
  858. // },
  859. // ...
  860. // {},
  861. // ...
  862. // ]
  863. //
  864. /* sample response
  865. "bones" : [
  866. {"parent":-1, "name":"Fbx01", "pos":[-0.002, 98.739, 1.6e-05], "rotq":[0, 0, 0, 1]},
  867. {"parent":0, "name":"Fbx01_Pelvis", "pos":[0.00015963, 0, 7.33107e-08], "rotq":[0, 0, 0, 1]},
  868. {"parent":1, "name":"Fbx01_Spine", "pos":[6.577e-06, 10.216, 0.0106811], "rotq":[0, 0, 0, 1]},
  869. {"parent":2, "name":"Fbx01_R_Thigh", "pos":[14.6537, -10.216, -0.00918758], "rotq":[0, 0, 0, 1]},
  870. {"parent":3, "name":"Fbx01_R_Calf", "pos":[-3.70047, -42.9681, -7.78158], "rotq":[0, 0, 0, 1]},
  871. {"parent":4, "name":"Fbx01_R_Foot", "pos":[-2.0696, -46.0488, 9.42052], "rotq":[0, 0, 0, 1]},
  872. {"parent":5, "name":"Fbx01_R_Toe0", "pos":[-0.0234785, -9.46233, -15.3187], "rotq":[0, 0, 0, 1]},
  873. {"parent":2, "name":"Fbx01_L_Thigh", "pos":[-14.6537, -10.216, -0.00918314], "rotq":[0, 0, 0, 1]},
  874. {"parent":7, "name":"Fbx01_L_Calf", "pos":[3.70037, -42.968, -7.78155], "rotq":[0, 0, 0, 1]},
  875. {"parent":8, "name":"Fbx01_L_Foot", "pos":[2.06954, -46.0488, 9.42052], "rotq":[0, 0, 0, 1]},
  876. {"parent":9, "name":"Fbx01_L_Toe0", "pos":[0.0234566, -9.46235, -15.3187], "rotq":[0, 0, 0, 1]},
  877. {"parent":2, "name":"Fbx01_Spine1", "pos":[-2.97523e-05, 11.5892, -9.81027e-05], "rotq":[0, 0, 0, 1]},
  878. {"parent":11, "name":"Fbx01_Spine2", "pos":[-2.91292e-05, 11.4685, 8.27126e-05], "rotq":[0, 0, 0, 1]},
  879. {"parent":12, "name":"Fbx01_Spine3", "pos":[-4.48857e-05, 11.5783, 8.35108e-05], "rotq":[0, 0, 0, 1]},
  880. {"parent":13, "name":"Fbx01_Neck", "pos":[1.22987e-05, 11.5582, -0.0044775], "rotq":[0, 0, 0, 1]},
  881. {"parent":14, "name":"Fbx01_Head", "pos":[-3.50709e-05, 6.62915, -0.00523254], "rotq":[0, 0, 0, 1]},
  882. {"parent":15, "name":"Fbx01_R_Eye", "pos":[3.31681, 12.739, -10.5267], "rotq":[0, 0, 0, 1]},
  883. {"parent":15, "name":"Fbx01_L_Eye", "pos":[-3.32038, 12.7391, -10.5267], "rotq":[0, 0, 0, 1]},
  884. {"parent":15, "name":"Jaw", "pos":[-0.0017738, 7.43481, -4.08114], "rotq":[0, 0, 0, 1]},
  885. {"parent":14, "name":"Fbx01_R_Clavicle", "pos":[3.10919, 2.46577, -0.0115284], "rotq":[0, 0, 0, 1]},
  886. {"parent":19, "name":"Fbx01_R_UpperArm", "pos":[16.014, 4.57764e-05, 3.10405], "rotq":[0, 0, 0, 1]},
  887. {"parent":20, "name":"Fbx01_R_Forearm", "pos":[22.7068, -1.66322, -2.13803], "rotq":[0, 0, 0, 1]},
  888. {"parent":21, "name":"Fbx01_R_Hand", "pos":[25.5881, -0.80249, -6.37307], "rotq":[0, 0, 0, 1]},
  889. ...
  890. {"parent":27, "name":"Fbx01_R_Finger32", "pos":[2.15572, -0.548737, -0.539604], "rotq":[0, 0, 0, 1]},
  891. {"parent":22, "name":"Fbx01_R_Finger2", "pos":[9.79318, 0.132553, -2.97845], "rotq":[0, 0, 0, 1]},
  892. {"parent":29, "name":"Fbx01_R_Finger21", "pos":[2.74037, 0.0483093, -0.650531], "rotq":[0, 0, 0, 1]},
  893. {"parent":55, "name":"Fbx01_L_Finger02", "pos":[-1.65308, -1.43208, -1.82885], "rotq":[0, 0, 0, 1]}
  894. ]
  895. */
  896. this.hierarchy = [];
  897. }
  898. Bones.prototype.parseHierarchy = function ( node ) {
  899. var objects = node.Objects;
  900. var models = objects.subNodes.Model;
  901. var bones = [];
  902. for ( var id in models ) {
  903. if ( models[ id ].attrType === undefined ) {
  904. continue;
  905. }
  906. bones.push( models[ id ] );
  907. }
  908. this.hierarchy = [];
  909. for ( var i = 0; i < bones.length; ++ i ) {
  910. var bone = bones[ i ];
  911. var p = node.searchConnectionParent( bone.id )[ 0 ];
  912. var t = [ 0.0, 0.0, 0.0 ];
  913. var r = [ 0.0, 0.0, 0.0, 1.0 ];
  914. var s = [ 1.0, 1.0, 1.0 ];
  915. if ( 'Lcl_Translation' in bone.properties ) {
  916. t = parseArrayToFloat( bone.properties.Lcl_Translation.value );
  917. }
  918. if ( 'Lcl_Rotation' in bone.properties ) {
  919. r = parseArrayToRadians( bone.properties.Lcl_Rotation.value );
  920. var q = new THREE.Quaternion();
  921. q.setFromEuler( new THREE.Euler( r[ 0 ], r[ 1 ], r[ 2 ], 'ZYX' ) );
  922. r = [ q.x, q.y, q.z, q.w ];
  923. }
  924. if ( 'Lcl_Scaling' in bone.properties ) {
  925. s = parseArrayToFloat( bone.properties.Lcl_Scaling.value );
  926. }
  927. // replace unsafe character
  928. var name = bone.attrName;
  929. name = name.replace( /:/, '' );
  930. name = name.replace( /_/, '' );
  931. name = name.replace( /-/, '' );
  932. this.hierarchy.push( { "parent": p, "name": name, "pos": t, "rotq": r, "scl": s, "internalId": bone.id } );
  933. }
  934. this.reindexParentId();
  935. this.restoreBindPose( node );
  936. return this;
  937. };
  938. Bones.prototype.reindexParentId = function () {
  939. for ( var h = 0; h < this.hierarchy.length; h ++ ) {
  940. for ( var ii = 0; ii < this.hierarchy.length; ++ ii ) {
  941. if ( this.hierarchy[ h ].parent == this.hierarchy[ ii ].internalId ) {
  942. this.hierarchy[ h ].parent = ii;
  943. break;
  944. }
  945. }
  946. }
  947. };
  948. Bones.prototype.restoreBindPose = function ( node ) {
  949. var bindPoseNode = node.Objects.subNodes.Pose;
  950. if ( bindPoseNode === undefined ) {
  951. return;
  952. }
  953. for ( var key in bindPoseNode ) {
  954. if ( bindPoseNode[ key ].attrType === 'BindPose' ) {
  955. bindPoseNode = bindPoseNode[ key ];
  956. break;
  957. }
  958. }
  959. var poseNode = bindPoseNode.subNodes.PoseNode;
  960. var localMatrices = {}; // store local matrices, modified later( initialy world space )
  961. var worldMatrices = {}; // store world matrices
  962. for ( var i = 0; i < poseNode.length; ++ i ) {
  963. var rawMatLcl = parseArrayToMatrix( poseNode[ i ].subNodes.Matrix.properties.a );
  964. var rawMatWrd = parseArrayToMatrix( poseNode[ i ].subNodes.Matrix.properties.a );
  965. localMatrices[ poseNode[ i ].id ] = rawMatLcl;
  966. worldMatrices[ poseNode[ i ].id ] = rawMatWrd;
  967. }
  968. for ( var h = 0; h < this.hierarchy.length; ++ h ) {
  969. var bone = this.hierarchy[ h ];
  970. var inId = bone.internalId;
  971. if ( worldMatrices[ inId ] === undefined ) {
  972. // has no bind pose node, possibly be mesh
  973. // console.log( bone );
  974. continue;
  975. }
  976. var t = new THREE.Vector3( 0, 0, 0 );
  977. var r = new THREE.Quaternion();
  978. var s = new THREE.Vector3( 1, 1, 1 );
  979. var parentId;
  980. var parentNodes = node.searchConnectionParent( inId );
  981. for ( var pn = 0; pn < parentNodes.length; ++ pn ) {
  982. if ( this.isBoneNode( parentNodes[ pn ] ) ) {
  983. parentId = parentNodes[ pn ];
  984. break;
  985. }
  986. }
  987. if ( parentId !== undefined && localMatrices[ parentId ] !== undefined ) {
  988. // convert world space matrix into local space
  989. var inv = new THREE.Matrix4();
  990. inv.getInverse( worldMatrices[ parentId ] );
  991. inv.multiply( localMatrices[ inId ] );
  992. localMatrices[ inId ] = inv;
  993. } else {
  994. //console.log( bone );
  995. }
  996. localMatrices[ inId ].decompose( t, r, s );
  997. bone.pos = [ t.x, t.y, t.z ];
  998. bone.rotq = [ r.x, r.y, r.z, r.w ];
  999. bone.scl = [ s.x, s.y, s.z ];
  1000. }
  1001. };
  1002. Bones.prototype.searchRealId = function ( internalId ) {
  1003. for ( var h = 0; h < this.hierarchy.length; h ++ ) {
  1004. if ( internalId == this.hierarchy[ h ].internalId ) {
  1005. return h;
  1006. }
  1007. }
  1008. // console.warn( 'FBXLoader: notfound internalId in bones: ' + internalId);
  1009. return - 1;
  1010. };
  1011. Bones.prototype.getByInternalId = function ( internalId ) {
  1012. for ( var h = 0; h < this.hierarchy.length; h ++ ) {
  1013. if ( internalId == this.hierarchy[ h ].internalId ) {
  1014. return this.hierarchy[ h ];
  1015. }
  1016. }
  1017. return null;
  1018. };
  1019. Bones.prototype.isBoneNode = function ( id ) {
  1020. for ( var i = 0; i < this.hierarchy.length; ++ i ) {
  1021. if ( id === this.hierarchy[ i ].internalId ) {
  1022. return true;
  1023. }
  1024. }
  1025. return false;
  1026. };
  1027. Bones.prototype.getBoneIdfromInternalId = function ( node, id ) {
  1028. if ( node.__cache_get_boneid_from_internalid === undefined ) {
  1029. node.__cache_get_boneid_from_internalid = [];
  1030. }
  1031. if ( node.__cache_get_boneid_from_internalid[ id ] !== undefined ) {
  1032. return node.__cache_get_boneid_from_internalid[ id ];
  1033. }
  1034. for ( var i = 0; i < this.hierarchy.length; ++ i ) {
  1035. if ( this.hierarchy[ i ].internalId == id ) {
  1036. node.__cache_get_boneid_from_internalid[ id ] = i;
  1037. return i;
  1038. }
  1039. }
  1040. // console.warn( 'FBXLoader: bone internalId(' + id + ') not found in bone hierarchy' );
  1041. return - 1;
  1042. };
  1043. function Geometries() {
  1044. this.geometries = {};
  1045. }
  1046. Object.assign( Geometries.prototype, {
  1047. parse: function ( FBXNodes, hierarchy ) {
  1048. if ( ! ( 'Geometry' in FBXNodes.Objects.subNodes ) ) {
  1049. return this;
  1050. }
  1051. for ( var geo in FBXNodes.Objects.subNodes.Geometry ) {
  1052. if ( FBXNodes.Objects.subNodes.Geometry[ geo ].attrType === 'Mesh' ) {
  1053. this.geometries[ geo ] = ( new Geometry() ).parse( FBXNodes.Objects.subNodes.Geometry[ geo ] );
  1054. this.geometries[ geo ].addBones( hierarchy.hierarchy );
  1055. }
  1056. }
  1057. return this;
  1058. }
  1059. } );
  1060. function Geometry() {
  1061. this.node = null;
  1062. this.name = null;
  1063. this.id = null;
  1064. this.vertices = [];
  1065. this.indices = [];
  1066. this.normals = [];
  1067. this.uvs = [];
  1068. this.bones = [];
  1069. }
  1070. Geometry.prototype.parse = function ( geoNode ) {
  1071. this.node = geoNode;
  1072. this.name = geoNode.attrName;
  1073. this.id = geoNode.id;
  1074. this.vertices = this.getVertices();
  1075. if ( this.vertices === undefined ) {
  1076. console.log( 'FBXLoader: Geometry.parse(): pass' + this.node.id );
  1077. return;
  1078. }
  1079. this.indices = this.getPolygonVertexIndices();
  1080. this.uvs = ( new UV() ).parse( this.node, this );
  1081. this.normals = ( new Normal() ).parse( this.node, this );
  1082. this.materialIndices = ( new MaterialIndex() ).parse( this.node );
  1083. if ( this.getPolygonTopologyMax() > 3 ) {
  1084. var indexInfo = this.convertPolyIndicesToTri(
  1085. this.indices,
  1086. this.materialIndices,
  1087. this.getPolygonTopologyArray() );
  1088. this.indices = indexInfo.res;
  1089. this.materialIndices = indexInfo.materialIndices;
  1090. this.polyIndices = indexInfo.polyIndices;
  1091. }
  1092. return this;
  1093. };
  1094. Geometry.prototype.getVertices = function () {
  1095. if ( this.node.__cache_vertices ) {
  1096. return this.node.__cache_vertices;
  1097. }
  1098. if ( this.node.subNodes.Vertices === undefined ) {
  1099. console.warn( 'this.node: ' + this.node.attrName + "(" + this.node.id + ") does not have Vertices" );
  1100. this.node.__cache_vertices = undefined;
  1101. return null;
  1102. }
  1103. var rawTextVert = this.node.subNodes.Vertices.properties.a;
  1104. var vertices = rawTextVert.split( ',' ).map( function ( element ) {
  1105. return parseFloat( element );
  1106. } );
  1107. this.node.__cache_vertices = vertices;
  1108. return this.node.__cache_vertices;
  1109. };
  1110. Geometry.prototype.getPolygonVertexIndices = function () {
  1111. if ( this.node.__cache_indices && this.node.__cache_poly_topology_max ) {
  1112. return this.node.__cache_indices;
  1113. }
  1114. if ( this.node.subNodes === undefined ) {
  1115. console.error( 'this.node.subNodes undefined' );
  1116. console.log( this.node );
  1117. return;
  1118. }
  1119. if ( this.node.subNodes.PolygonVertexIndex === undefined ) {
  1120. console.warn( 'this.node: ' + this.node.attrName + "(" + this.node.id + ") does not have PolygonVertexIndex " );
  1121. this.node.__cache_indices = undefined;
  1122. return;
  1123. }
  1124. var rawTextIndices = this.node.subNodes.PolygonVertexIndex.properties.a;
  1125. var indices = rawTextIndices.split( ',' );
  1126. var currentTopo = 1;
  1127. var topologyN = null;
  1128. var topologyArr = [];
  1129. // The indices that make up the polygon are in order and a negative index
  1130. // means that it’s the last index of the polygon. That index needs
  1131. // to be made positive and then you have to subtract 1 from it!
  1132. for ( var i = 0; i < indices.length; ++ i ) {
  1133. var tmpI = parseInt( indices[ i ] );
  1134. // found n
  1135. if ( tmpI < 0 ) {
  1136. if ( currentTopo > topologyN ) {
  1137. topologyN = currentTopo;
  1138. }
  1139. indices[ i ] = tmpI ^ - 1;
  1140. topologyArr.push( currentTopo );
  1141. currentTopo = 1;
  1142. } else {
  1143. indices[ i ] = tmpI;
  1144. currentTopo ++;
  1145. }
  1146. }
  1147. if ( topologyN === null ) {
  1148. console.warn( "FBXLoader: topology N not found: " + this.node.attrName );
  1149. console.warn( this.node );
  1150. topologyN = 3;
  1151. }
  1152. this.node.__cache_poly_topology_max = topologyN;
  1153. this.node.__cache_poly_topology_arr = topologyArr;
  1154. this.node.__cache_indices = indices;
  1155. return this.node.__cache_indices;
  1156. };
  1157. Geometry.prototype.getPolygonTopologyMax = function () {
  1158. if ( this.node.__cache_indices && this.node.__cache_poly_topology_max ) {
  1159. return this.node.__cache_poly_topology_max;
  1160. }
  1161. this.getPolygonVertexIndices( this.node );
  1162. return this.node.__cache_poly_topology_max;
  1163. };
  1164. Geometry.prototype.getPolygonTopologyArray = function () {
  1165. if ( this.node.__cache_indices && this.node.__cache_poly_topology_max ) {
  1166. return this.node.__cache_poly_topology_arr;
  1167. }
  1168. this.getPolygonVertexIndices( this.node );
  1169. return this.node.__cache_poly_topology_arr;
  1170. };
  1171. // a - d
  1172. // | |
  1173. // b - c
  1174. //
  1175. // [( a, b, c, d ) ...........
  1176. // [( a, b, c ), (a, c, d )....
  1177. // Also keep track of original poly index.
  1178. Geometry.prototype.convertPolyIndicesToTri = function ( indices, materialIndices, strides ) {
  1179. var res = [];
  1180. var i = 0;
  1181. var currentPolyNum = 0;
  1182. var currentStride = 0;
  1183. var polyIndices = [];
  1184. while ( i < indices.length ) {
  1185. currentStride = strides[ currentPolyNum ];
  1186. // CAUTIN: NG over 6gon
  1187. for ( var j = 0; j <= ( currentStride - 3 ); j ++ ) {
  1188. res.push( indices[ i ] );
  1189. res.push( indices[ i + ( currentStride - 2 - j ) ] );
  1190. res.push( indices[ i + ( currentStride - 1 - j ) ] );
  1191. polyIndices.push( currentPolyNum );
  1192. }
  1193. currentPolyNum ++;
  1194. i += currentStride;
  1195. }
  1196. var newMaterialIndices = [ materialIndices[ 0 ] ];
  1197. if ( materialIndices.length > 1 ) {
  1198. for ( var i = 0; i < polyIndices.length; ++ i ) {
  1199. newMaterialIndices[ i ] = materialIndices[ polyIndices[ i ] ];
  1200. }
  1201. }
  1202. return {
  1203. res: res,
  1204. materialIndices: newMaterialIndices,
  1205. polyIndices: polyIndices };
  1206. };
  1207. Geometry.prototype.addBones = function ( bones ) {
  1208. this.bones = bones;
  1209. };
  1210. function UV() {
  1211. this.uv = null;
  1212. this.map = null;
  1213. this.ref = null;
  1214. this.node = null;
  1215. this.index = null;
  1216. }
  1217. UV.prototype.getUV = function ( node ) {
  1218. if ( this.node && this.uv && this.map && this.ref ) {
  1219. return this.uv;
  1220. } else {
  1221. return this._parseText( node );
  1222. }
  1223. };
  1224. UV.prototype.getMap = function ( node ) {
  1225. if ( this.node && this.uv && this.map && this.ref ) {
  1226. return this.map;
  1227. } else {
  1228. this._parseText( node );
  1229. return this.map;
  1230. }
  1231. };
  1232. UV.prototype.getRef = function ( node ) {
  1233. if ( this.node && this.uv && this.map && this.ref ) {
  1234. return this.ref;
  1235. } else {
  1236. this._parseText( node );
  1237. return this.ref;
  1238. }
  1239. };
  1240. UV.prototype.getIndex = function ( node ) {
  1241. if ( this.node && this.uv && this.map && this.ref ) {
  1242. return this.index;
  1243. } else {
  1244. this._parseText( node );
  1245. return this.index;
  1246. }
  1247. };
  1248. UV.prototype.getNode = function ( topnode ) {
  1249. if ( this.node !== null ) {
  1250. return this.node;
  1251. }
  1252. this.node = topnode.subNodes.LayerElementUV;
  1253. return this.node;
  1254. };
  1255. UV.prototype._parseText = function ( node ) {
  1256. var uvNode = this.getNode( node )[ 0 ];
  1257. if ( uvNode === undefined ) {
  1258. // console.log( node.attrName + "(" + node.id + ")" + " has no LayerElementUV." );
  1259. return [];
  1260. }
  1261. var count = 0;
  1262. for ( var n in uvNode ) {
  1263. if ( n.match( /^\d+$/ ) ) {
  1264. count ++;
  1265. }
  1266. }
  1267. if ( count > 0 ) {
  1268. console.warn( 'multi uv not supported' );
  1269. uvNode = uvNode[ n ];
  1270. }
  1271. var uvIndex = uvNode.subNodes.UVIndex.properties.a;
  1272. var uvs = uvNode.subNodes.UV.properties.a;
  1273. var uvMap = uvNode.properties.MappingInformationType;
  1274. var uvRef = uvNode.properties.ReferenceInformationType;
  1275. this.uv = parseArrayToFloat( uvs );
  1276. this.index = parseArrayToInt( uvIndex );
  1277. this.map = uvMap; // TODO: normalize notation shaking... FOR BLENDER
  1278. this.ref = uvRef;
  1279. return this.uv;
  1280. };
  1281. UV.prototype.parse = function ( node, geo ) {
  1282. if ( ! ( 'LayerElementUV' in node.subNodes ) ) {
  1283. return;
  1284. }
  1285. this.uvNode = this.getNode( node );
  1286. this.uv = this.getUV( node );
  1287. var mappingType = this.getMap( node );
  1288. var refType = this.getRef( node );
  1289. var indices = this.getIndex( node );
  1290. var strides = geo.getPolygonTopologyArray();
  1291. // it means that there is a normal for every vertex of every polygon of the model.
  1292. // For example, if the models has 8 vertices that make up four quads, then there
  1293. // will be 16 normals (one normal * 4 polygons * 4 vertices of the polygon). Note
  1294. // that generally a game engine needs the vertices to have only one normal defined.
  1295. // So, if you find a vertex has more tha one normal, you can either ignore the normals
  1296. // you find after the first, or calculate the mean from all of them (normal smoothing).
  1297. //if ( mappingType == "ByPolygonVertex" ){
  1298. switch ( mappingType ) {
  1299. case "ByPolygonVertex":
  1300. switch ( refType ) {
  1301. // Direct
  1302. // The this.uv are in order.
  1303. case "Direct":
  1304. this.uv = this.parseUV_ByPolygonVertex_Direct( this.uv, indices, strides, 2 );
  1305. break;
  1306. // IndexToDirect
  1307. // The order of the this.uv is given by the uvsIndex property.
  1308. case "IndexToDirect":
  1309. this.uv = this.parseUV_ByPolygonVertex_IndexToDirect( this.uv, indices );
  1310. break;
  1311. }
  1312. // convert from by polygon(vert) data into by verts data
  1313. this.uv = mapByPolygonVertexToByVertex( this.uv, geo.getPolygonVertexIndices( node ), 2 );
  1314. break;
  1315. case "ByPolygon":
  1316. switch ( refType ) {
  1317. // Direct
  1318. // The this.uv are in order.
  1319. case "Direct":
  1320. this.uv = this.parseUV_ByPolygon_Direct();
  1321. break;
  1322. // IndexToDirect
  1323. // The order of the this.uv is given by the uvsIndex property.
  1324. case "IndexToDirect":
  1325. this.uv = this.parseUV_ByPolygon_IndexToDirect();
  1326. break;
  1327. }
  1328. break;
  1329. }
  1330. return this.uv;
  1331. };
  1332. UV.prototype.parseUV_ByPolygonVertex_Direct = function ( node, indices, strides, itemSize ) {
  1333. return parse_Data_ByPolygonVertex_Direct( node, indices, strides, itemSize );
  1334. };
  1335. UV.prototype.parseUV_ByPolygonVertex_IndexToDirect = function ( node, indices ) {
  1336. return parse_Data_ByPolygonVertex_IndexToDirect( node, indices, 2 );
  1337. };
  1338. UV.prototype.parseUV_ByPolygon_Direct = function ( node ) {
  1339. console.warn( "not implemented" );
  1340. return node;
  1341. };
  1342. UV.prototype.parseUV_ByPolygon_IndexToDirect = function ( node ) {
  1343. console.warn( "not implemented" );
  1344. return node;
  1345. };
  1346. UV.prototype.parseUV_ByVertex_Direct = function ( node ) {
  1347. console.warn( "not implemented" );
  1348. return node;
  1349. };
  1350. function Normal() {
  1351. this.normal = null;
  1352. this.map = null;
  1353. this.ref = null;
  1354. this.node = null;
  1355. this.index = null;
  1356. }
  1357. Normal.prototype.getNormal = function ( node ) {
  1358. if ( this.node && this.normal && this.map && this.ref ) {
  1359. return this.normal;
  1360. } else {
  1361. this._parseText( node );
  1362. return this.normal;
  1363. }
  1364. };
  1365. // mappingType: possible variant
  1366. // ByPolygon
  1367. // ByPolygonVertex
  1368. // ByVertex (or also ByVertice, as the Blender exporter writes)
  1369. // ByEdge
  1370. // AllSame
  1371. // var mappingType = node.properties.MappingInformationType;
  1372. Normal.prototype.getMap = function ( node ) {
  1373. if ( this.node && this.normal && this.map && this.ref ) {
  1374. return this.map;
  1375. } else {
  1376. this._parseText( node );
  1377. return this.map;
  1378. }
  1379. };
  1380. // refType: possible variants
  1381. // Direct
  1382. // IndexToDirect (or Index for older versions)
  1383. // var refType = node.properties.ReferenceInformationType;
  1384. Normal.prototype.getRef = function ( node ) {
  1385. if ( this.node && this.normal && this.map && this.ref ) {
  1386. return this.ref;
  1387. } else {
  1388. this._parseText( node );
  1389. return this.ref;
  1390. }
  1391. };
  1392. Normal.prototype.getNode = function ( node ) {
  1393. if ( this.node ) {
  1394. return this.node;
  1395. }
  1396. this.node = node.subNodes.LayerElementNormal;
  1397. return this.node;
  1398. };
  1399. Normal.prototype._parseText = function ( node ) {
  1400. var normalNode = this.getNode( node )[ 0 ];
  1401. if ( normalNode === undefined ) {
  1402. console.warn( 'node: ' + node.attrName + "(" + node.id + ") does not have LayerElementNormal" );
  1403. return;
  1404. }
  1405. var mappingType = normalNode.properties.MappingInformationType;
  1406. var refType = normalNode.properties.ReferenceInformationType;
  1407. var rawTextNormals = normalNode.subNodes.Normals.properties.a;
  1408. this.normal = parseArrayToFloat( rawTextNormals );
  1409. // TODO: normalize notation shaking, vertex / vertice... blender...
  1410. this.map = mappingType;
  1411. this.ref = refType;
  1412. };
  1413. Normal.prototype.parse = function ( topnode, geo ) {
  1414. var normals = this.getNormal( topnode );
  1415. //var normalNode = this.getNode( topnode );
  1416. var mappingType = this.getMap( topnode );
  1417. var refType = this.getRef( topnode );
  1418. var indices = geo.getPolygonVertexIndices( topnode );
  1419. var strides = geo.getPolygonTopologyArray( topnode );
  1420. // it means that there is a normal for every vertex of every polygon of the model.
  1421. // For example, if the models has 8 vertices that make up four quads, then there
  1422. // will be 16 normals (one normal * 4 polygons * 4 vertices of the polygon). Note
  1423. // that generally a game engine needs the vertices to have only one normal defined.
  1424. // So, if you find a vertex has more tha one normal, you can either ignore the normals
  1425. // you find after the first, or calculate the mean from all of them (normal smoothing).
  1426. //if ( mappingType == "ByPolygonVertex" ){
  1427. switch ( mappingType ) {
  1428. case "ByPolygonVertex":
  1429. switch ( refType ) {
  1430. // Direct
  1431. // The normals are in order.
  1432. case "Direct":
  1433. normals = this.parseNormal_ByPolygonVertex_Direct( normals, indices, strides, 3 );
  1434. break;
  1435. // IndexToDirect
  1436. // The order of the normals is given by the NormalsIndex property.
  1437. case "IndexToDirect":
  1438. normals = this.parseNormal_ByPolygonVertex_IndexToDirect();
  1439. break;
  1440. }
  1441. break;
  1442. case "ByPolygon":
  1443. switch ( refType ) {
  1444. // Direct
  1445. // The normals are in order.
  1446. case "Direct":
  1447. normals = this.parseNormal_ByPolygon_Direct();
  1448. break;
  1449. // IndexToDirect
  1450. // The order of the normals is given by the NormalsIndex property.
  1451. case "IndexToDirect":
  1452. normals = this.parseNormal_ByPolygon_IndexToDirect();
  1453. break;
  1454. }
  1455. break;
  1456. }
  1457. return normals;
  1458. };
  1459. Normal.prototype.parseNormal_ByPolygonVertex_Direct = function ( node, indices, strides, itemSize ) {
  1460. return parse_Data_ByPolygonVertex_Direct( node, indices, strides, itemSize );
  1461. };
  1462. Normal.prototype.parseNormal_ByPolygonVertex_IndexToDirect = function ( node ) {
  1463. console.warn( "not implemented" );
  1464. return node;
  1465. };
  1466. Normal.prototype.parseNormal_ByPolygon_Direct = function ( node ) {
  1467. console.warn( "not implemented" );
  1468. return node;
  1469. };
  1470. Normal.prototype.parseNormal_ByPolygon_IndexToDirect = function ( node ) {
  1471. console.warn( "not implemented" );
  1472. return node;
  1473. };
  1474. Normal.prototype.parseNormal_ByVertex_Direct = function ( node ) {
  1475. console.warn( "not implemented" );
  1476. return node;
  1477. };
  1478. function MaterialIndex() {
  1479. this.indexBuffer = [];
  1480. }
  1481. Object.assign( MaterialIndex.prototype, {
  1482. parse: function ( node ) {
  1483. if ( ! ( 'LayerElementMaterial' in node.subNodes ) ) {
  1484. return;
  1485. }
  1486. var indexNode = node.subNodes.LayerElementMaterial[ 0 ];
  1487. var mappingType = indexNode.properties.MappingInformationType;
  1488. var refType = indexNode.properties.ReferenceInformationType;
  1489. var indices = parseArrayToInt( indexNode.subNodes.Materials.properties.a );
  1490. // it means that there is a normal for every vertex of every polygon of the model.
  1491. // For example, if the models has 8 vertices that make up four quads, then there
  1492. // will be 16 normals (one normal * 4 polygons * 4 vertices of the polygon). Note
  1493. // that generally a game engine needs the vertices to have only one normal defined.
  1494. // So, if you find a vertex has more tha one normal, you can either ignore the normals
  1495. // you find after the first, or calculate the mean from all of them (normal smoothing).
  1496. //if ( mappingType == "ByPolygonVertex" ){
  1497. switch ( mappingType ) {
  1498. case "ByPolygon":
  1499. switch ( refType ) {
  1500. // Direct
  1501. // The material indices are in order.
  1502. case "IndexToDirect":
  1503. this.indexBuffer = this.parse_ByPolygon_IndexToDirect( indices );
  1504. break;
  1505. default:
  1506. this.indexBuffer = [ 0 ];
  1507. break;
  1508. }
  1509. break;
  1510. default:
  1511. this.indexBuffer = [ 0 ];
  1512. break;
  1513. }
  1514. return this.indexBuffer;
  1515. },
  1516. parse_ByPolygon_IndexToDirect: function ( indices ) {
  1517. return indices;
  1518. },
  1519. } );
  1520. function AnimationCurve() {
  1521. this.version = null;
  1522. this.id = null;
  1523. this.internalId = null;
  1524. this.times = null;
  1525. this.values = null;
  1526. this.attrFlag = null; // tangeant
  1527. this.attrData = null; // slope, weight
  1528. }
  1529. AnimationCurve.prototype.fromNode = function ( curveNode ) {
  1530. this.id = curveNode.id;
  1531. this.internalId = curveNode.id;
  1532. this.times = curveNode.subNodes.KeyTime.properties.a;
  1533. this.values = curveNode.subNodes.KeyValueFloat.properties.a;
  1534. this.attrFlag = curveNode.subNodes.KeyAttrFlags.properties.a;
  1535. this.attrData = curveNode.subNodes.KeyAttrDataFloat.properties.a;
  1536. this.times = parseArrayToFloat( this.times );
  1537. this.values = parseArrayToFloat( this.values );
  1538. this.attrData = parseArrayToFloat( this.attrData );
  1539. this.attrFlag = parseArrayToInt( this.attrFlag );
  1540. this.times = this.times.map( function ( element ) {
  1541. return FBXTimeToSeconds( element );
  1542. } );
  1543. return this;
  1544. };
  1545. AnimationCurve.prototype.getLength = function () {
  1546. return this.times[ this.times.length - 1 ];
  1547. };
  1548. function AnimationNode() {
  1549. this.id = null;
  1550. this.attr = null; // S, R, T
  1551. this.attrX = false;
  1552. this.attrY = false;
  1553. this.attrZ = false;
  1554. this.internalId = null;
  1555. this.containerInternalId = null; // bone, null etc Id
  1556. this.containerBoneId = null; // bone, null etc Id
  1557. this.curveIdx = null; // AnimationCurve's indices
  1558. this.curves = {}; // AnimationCurve refs
  1559. }
  1560. AnimationNode.prototype.fromNode = function ( allNodes, node, bones ) {
  1561. this.id = node.id;
  1562. this.attr = node.attrName;
  1563. this.internalId = node.id;
  1564. if ( this.attr.match( /S|R|T/ ) ) {
  1565. for ( var attrKey in node.properties ) {
  1566. if ( attrKey.match( /X/ ) ) {
  1567. this.attrX = true;
  1568. }
  1569. if ( attrKey.match( /Y/ ) ) {
  1570. this.attrY = true;
  1571. }
  1572. if ( attrKey.match( /Z/ ) ) {
  1573. this.attrZ = true;
  1574. }
  1575. }
  1576. } else {
  1577. // may be deform percent nodes
  1578. return null;
  1579. }
  1580. this.containerIndices = allNodes.searchConnectionParent( this.id );
  1581. this.curveIdx = allNodes.searchConnectionChildren( this.id );
  1582. for ( var i = this.containerIndices.length - 1; i >= 0; -- i ) {
  1583. var boneId = bones.searchRealId( this.containerIndices[ i ] );
  1584. if ( boneId >= 0 ) {
  1585. this.containerBoneId = boneId;
  1586. this.containerId = this.containerIndices[ i ];
  1587. }
  1588. if ( boneId >= 0 ) {
  1589. break;
  1590. }
  1591. }
  1592. // this.containerBoneId = bones.searchRealId( this.containerIndices );
  1593. return this;
  1594. };
  1595. AnimationNode.prototype.setCurve = function ( curve ) {
  1596. this.curves.push( curve );
  1597. };
  1598. function Animation() {
  1599. this.curves = {};
  1600. this.length = 0.0;
  1601. this.fps = 30.0;
  1602. this.frames = 0.0;
  1603. }
  1604. Animation.prototype.parse = function ( node, bones ) {
  1605. var rawNodes = node.Objects.subNodes.AnimationCurveNode;
  1606. var rawCurves = node.Objects.subNodes.AnimationCurve;
  1607. var rawLayers = node.Objects.subNodes.AnimationLayer;
  1608. var rawStacks = node.Objects.subNodes.AnimationStack;
  1609. // first: expand AnimationCurveNode into curve nodes
  1610. var curveNodes = [];
  1611. for ( var key in rawNodes ) {
  1612. if ( key.match( /\d+/ ) ) {
  1613. var a = ( new AnimationNode() ).fromNode( node, rawNodes[ key ], bones );
  1614. curveNodes.push( a );
  1615. }
  1616. }
  1617. // second: gen dict, mapped by internalId
  1618. var tmp = {};
  1619. for ( var i = 0; i < curveNodes.length; ++ i ) {
  1620. if ( curveNodes[ i ] === null ) {
  1621. continue;
  1622. }
  1623. tmp[ curveNodes[ i ].id ] = curveNodes[ i ];
  1624. }
  1625. // third: insert curves into the dict
  1626. var ac = [];
  1627. for ( key in rawCurves ) {
  1628. if ( key.match( /\d+/ ) ) {
  1629. var c = ( new AnimationCurve() ).fromNode( rawCurves[ key ] );
  1630. ac.push( c );
  1631. var parentId = node.searchConnectionParent( c.id )[ 0 ];
  1632. var axis = node.searchConnectionType( c.id, parentId );
  1633. if ( axis.match( /X/ ) ) {
  1634. axis = 'x';
  1635. } else if ( axis.match( /Y/ ) ) {
  1636. axis = 'y';
  1637. } else if ( axis.match( /Z/ ) ) {
  1638. axis = 'z';
  1639. } else {
  1640. continue;
  1641. }
  1642. tmp[ parentId ].curves[ axis ] = c;
  1643. }
  1644. }
  1645. // forth:
  1646. for ( var t in tmp ) {
  1647. var id = tmp[ t ].containerBoneId;
  1648. if ( this.curves[ id ] === undefined ) {
  1649. this.curves[ id ] = {
  1650. T: null,
  1651. R: null,
  1652. S: null
  1653. };
  1654. }
  1655. this.curves[ id ][ tmp[ t ].attr ] = tmp[ t ];
  1656. }
  1657. //Layers
  1658. this.layers = {};
  1659. for ( var key in rawLayers ) {
  1660. var layer = [];
  1661. var children = node.searchConnectionChildren( key );
  1662. for ( var i = 0; i < children.length; ++ i ) {
  1663. //Skip lockInfluenceWeights
  1664. if ( tmp[ children[ i ] ] ) {
  1665. if ( layer[ tmp[ children[ i ] ].containerBoneId ] === undefined ) {
  1666. layer[ tmp[ children[ i ] ].containerBoneId ] = {
  1667. T: null,
  1668. R: null,
  1669. S: null
  1670. };
  1671. }
  1672. layer[ tmp[ children[ i ] ].containerBoneId ][ tmp[ children[ i ] ].attr ] = tmp[ children[ i ] ];
  1673. }
  1674. }
  1675. this.layers[ key ] = layer;
  1676. }
  1677. //Takes
  1678. this.stacks = {};
  1679. for ( var key in rawStacks ) {
  1680. var layers = [];
  1681. var children = node.searchConnectionChildren( key );
  1682. var max = 0.0;
  1683. var min = Number.MAX_VALUE;
  1684. for ( var i = 0; i < children.length; ++ i ) {
  1685. if ( children[ i ] in this.layers ) {
  1686. layers.push( this.layers[ children[ i ] ] );
  1687. for ( var j = 0; j < this.layers[ children[ i ] ].length; ++ j ) {
  1688. function getMaxMin( layer ) {
  1689. function _getMaxMin( curves ) {
  1690. if ( curves.x ) {
  1691. max = curves.x.getLength() > max ? curves.x.getLength() : max;
  1692. min = curves.x.times[ 0 ] < min ? curves.x.times[ 0 ] : min;
  1693. }
  1694. if ( curves.y ) {
  1695. max = curves.y.getLength() > max ? curves.y.getLength() : max;
  1696. min = curves.y.times[ 0 ] < min ? curves.y.times[ 0 ] : min;
  1697. }
  1698. if ( curves.z ) {
  1699. max = curves.z.getLength() > max ? curves.z.getLength() : max;
  1700. min = curves.z.times[ 0 ] < min ? curves.z.times[ 0 ] : min;
  1701. }
  1702. }
  1703. if ( layer.R ) {
  1704. _getMaxMin( layer.R.curves );
  1705. }
  1706. if ( layer.S ) {
  1707. _getMaxMin( layer.S.curves );
  1708. }
  1709. if ( layer.T ) {
  1710. _getMaxMin( layer.T.curves );
  1711. }
  1712. }
  1713. var layer = this.layers[ children[ i ] ][ j ];
  1714. if ( layer ) {
  1715. getMaxMin( layer );
  1716. }
  1717. }
  1718. }
  1719. }
  1720. //Do we have an animation clip with an actual length?
  1721. if ( max > min ) {
  1722. this.stacks[ key ] = {
  1723. name: rawStacks[ key ].attrName,
  1724. layers: layers,
  1725. length: max - min,
  1726. frames: ( max - min ) * 30,
  1727. };
  1728. }
  1729. }
  1730. return this;
  1731. };
  1732. function Textures() {
  1733. this.textures = {};
  1734. //this.perGeoMap = {};
  1735. }
  1736. Textures.prototype.add = function ( tex ) {
  1737. debugger;
  1738. if ( this.textures === undefined ) {
  1739. this.textures = [];
  1740. }
  1741. this.textures.push( tex );
  1742. for ( var i = 0; i < tex.parentIds.length; ++ i ) {
  1743. if ( this.perGeoMap[ tex.parentIds[ i ] ] === undefined ) {
  1744. this.perGeoMap[ tex.parentIds[ i ] ] = [];
  1745. }
  1746. this.perGeoMap[ tex.parentIds[ i ] ].push( this.textures[ this.textures.length - 1 ] );
  1747. }
  1748. };
  1749. Textures.prototype.parse = function ( node ) {
  1750. var rawNodes = node.Objects.subNodes.Texture;
  1751. for ( var n in rawNodes ) {
  1752. var tex = ( new Texture() ).parse( rawNodes[ n ], node );
  1753. this.textures[ n ] = tex;
  1754. }
  1755. return this;
  1756. };
  1757. Textures.prototype.getById = function ( id ) {
  1758. return this.perGeoMap[ id ];
  1759. };
  1760. function Texture() {
  1761. this.fileName = "";
  1762. this.name = "";
  1763. this.id = null;
  1764. this.parentIds = [];
  1765. }
  1766. Texture.prototype.parse = function ( node, nodes ) {
  1767. this.id = node.id;
  1768. this.name = node.attrName;
  1769. this.fileName = this.parseFileName( node.properties.FileName );
  1770. this.parentIds = this.searchParents( this.id, nodes );
  1771. return this;
  1772. };
  1773. // TODO: support directory
  1774. Texture.prototype.parseFileName = function ( fname ) {
  1775. if ( fname === undefined ) {
  1776. return "";
  1777. }
  1778. // ignore directory structure, flatten path
  1779. var splitted = fname.split( /[\\\/]/ );
  1780. if ( splitted.length > 0 ) {
  1781. return splitted[ splitted.length - 1 ];
  1782. } else {
  1783. return fname;
  1784. }
  1785. };
  1786. Texture.prototype.searchParents = function ( id, nodes ) {
  1787. var p = nodes.searchConnectionParent( id );
  1788. return p;
  1789. };
  1790. function Materials() {
  1791. this.materials = {};
  1792. this.perGeoMap = {};
  1793. }
  1794. Object.assign( Materials.prototype, {
  1795. parse: function ( node ) {
  1796. var rawNodes = node.Objects.subNodes.Material;
  1797. for ( var n in rawNodes ) {
  1798. var mat = ( new Material() ).parse( rawNodes[ n ], node );
  1799. this.materials[ n ] = mat;
  1800. }
  1801. return this;
  1802. }
  1803. } );
  1804. function Material() {
  1805. this.fileName = "";
  1806. this.name = "";
  1807. this.id = null;
  1808. this.parentIds = [];
  1809. }
  1810. Object.assign( Material.prototype, {
  1811. parse: function ( node, nodes ) {
  1812. this.id = node.id;
  1813. this.name = node.attrName;
  1814. this.type = node.properties.ShadingModel;
  1815. this.parameters = this.parseParameters( node.properties );
  1816. this.parentIds = this.searchParents( this.id, nodes );
  1817. return this;
  1818. },
  1819. parseParameters: function ( properties ) {
  1820. var parameters = {};
  1821. //TODO: Missing parameters:
  1822. // - Ambient
  1823. // - MultiLayer
  1824. // - ShininessExponent (Same vals as Shininess)
  1825. // - Specular (Same vals as SpecularColor)
  1826. // - TransparencyFactor (Maybe same as Opacity?).
  1827. if ( properties.Diffuse ) {
  1828. parameters.color = new THREE.Color().fromArray( [ parseFloat( properties.Diffuse.value.x ), parseFloat( properties.Diffuse.value.y ), parseFloat( properties.Diffuse.value.z ) ] );
  1829. }
  1830. if ( properties.Specular ) {
  1831. parameters.specular = new THREE.Color().fromArray( [ parseFloat( properties.Specular.value.x ), parseFloat( properties.Specular.value.y ), parseFloat( properties.Specular.value.z ) ] );
  1832. }
  1833. if ( properties.Shininess ) {
  1834. parameters.shininess = properties.Shininess.value;
  1835. }
  1836. if ( properties.Emissive ) {
  1837. parameters.emissive = new THREE.Color().fromArray( [ parseFloat( properties.Emissive.value.x ), parseFloat( properties.Emissive.value.y ), parseFloat( properties.Emissive.value.z ) ] );
  1838. }
  1839. if ( properties.EmissiveFactor ) {
  1840. parameters.emissiveIntensity = properties.EmissiveFactor.value;
  1841. }
  1842. if ( properties.Reflectivity ) {
  1843. parameters.reflectivity = properties.Reflectivity.value;
  1844. }
  1845. if ( properties.Opacity ) {
  1846. parameters.opacity = properties.Opacity.value;
  1847. }
  1848. if ( parameters.opacity < 1.0 ) {
  1849. parameters.transparent = true;
  1850. }
  1851. //Assigning textures
  1852. return parameters;
  1853. },
  1854. searchParents: function ( id, nodes ) {
  1855. return nodes.searchConnectionParent( id );
  1856. }
  1857. } );
  1858. /* --------------------------------------------------------------------- */
  1859. /* --------------------------------------------------------------------- */
  1860. /* --------------------------------------------------------------------- */
  1861. /* --------------------------------------------------------------------- */
  1862. // LayerElementUV: 0 {
  1863. // Version: 101
  1864. // Name: "Texture_Projection"
  1865. // MappingInformationType: "ByPolygonVertex"
  1866. // ReferenceInformationType: "IndexToDirect"
  1867. // UV: *1746 {
  1868. // UVIndex: *7068 {
  1869. //
  1870. // The order of the uvs is given by the UVIndex property.
  1871. function parse_Data_ByPolygonVertex_IndexToDirect( node, indices, itemSize ) {
  1872. var res = [];
  1873. for ( var i = 0; i < indices.length; ++ i ) {
  1874. for ( var j = 0; j < itemSize; ++ j ) {
  1875. res.push( node[ ( indices[ i ] * itemSize ) + j ] );
  1876. }
  1877. }
  1878. return res;
  1879. }
  1880. // what want: normal per vertex, order vertice
  1881. // i have: normal per polygon
  1882. // i have: indice per polygon
  1883. function parse_Data_ByPolygonVertex_Direct( node, indices, strides, itemSize ) {
  1884. // *21204 > 3573
  1885. // Geometry: 690680816, "Geometry::", "Mesh" {
  1886. // Vertices: *3573 {
  1887. // PolygonVertexIndex: *7068 {
  1888. var tmp = [];
  1889. var currentIndex = 0;
  1890. // first: sort to per vertex
  1891. for ( var i = 0; i < indices.length; ++ i ) {
  1892. tmp[ indices[ i ] ] = [];
  1893. // TODO: duped entry? blend or something?
  1894. for ( var s = 0; s < itemSize; ++ s ) {
  1895. tmp[ indices[ i ] ][ s ] = node[ currentIndex + s ];
  1896. }
  1897. currentIndex += itemSize;
  1898. }
  1899. // second: expand x,y,z into serial array
  1900. var res = [];
  1901. for ( var jj = 0; jj < tmp.length; ++ jj ) {
  1902. if ( tmp[ jj ] === undefined ) {
  1903. continue;
  1904. }
  1905. for ( var t = 0; t < itemSize; ++ t ) {
  1906. if ( tmp[ jj ][ t ] === undefined ) {
  1907. continue;
  1908. }
  1909. res.push( tmp[ jj ][ t ] );
  1910. }
  1911. }
  1912. return res;
  1913. }
  1914. // convert from by polygon(vert) data into by verts data
  1915. function mapByPolygonVertexToByVertex( data, indices, stride ) {
  1916. var tmp = {};
  1917. var res = [];
  1918. var max = 0;
  1919. for ( var i = 0; i < indices.length; ++ i ) {
  1920. if ( indices[ i ] in tmp ) {
  1921. continue;
  1922. }
  1923. tmp[ indices[ i ] ] = {};
  1924. for ( var j = 0; j < stride; ++ j ) {
  1925. tmp[ indices[ i ] ][ j ] = data[ i * stride + j ];
  1926. }
  1927. max = max < indices[ i ] ? indices[ i ] : max;
  1928. }
  1929. try {
  1930. for ( i = 0; i <= max; i ++ ) {
  1931. for ( var s = 0; s < stride; s ++ ) {
  1932. res.push( tmp[ i ][ s ] );
  1933. }
  1934. }
  1935. } catch ( e ) {
  1936. //console.log( max );
  1937. //console.log( tmp );
  1938. //console.log( i );
  1939. //console.log( e );
  1940. }
  1941. return res;
  1942. }
  1943. // AUTODESK uses broken clock. i guess
  1944. function FBXTimeToSeconds( adskTime ) {
  1945. return adskTime / 46186158000;
  1946. }
  1947. function degToRad( degrees ) {
  1948. return degrees * Math.PI / 180;
  1949. }
  1950. function quatFromVec( x, y, z ) {
  1951. var euler = new THREE.Euler( x, y, z, 'ZYX' );
  1952. var quat = new THREE.Quaternion();
  1953. quat.setFromEuler( euler );
  1954. return quat;
  1955. }
  1956. function parseArrayToInt( string ) {
  1957. return string.split( ',' ).map( function ( element ) {
  1958. return parseInt( element );
  1959. } );
  1960. }
  1961. function parseArrayToFloat( string ) {
  1962. return string.split( ',' ).map( function ( element ) {
  1963. return parseFloat( element );
  1964. } );
  1965. }
  1966. function parseArrayToRadians( string ) {
  1967. return string.split( ',' ).map( function ( element ) {
  1968. return degToRad( parseFloat( element ) );
  1969. } );
  1970. }
  1971. function parseArrayToMatrix( string ) {
  1972. var arr = parseArrayToFloat( string );
  1973. return new THREE.Matrix4().fromArray( arr );
  1974. }
  1975. } )();