FBXLoader.js 68 KB

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