FBXLoader.js 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876
  1. ( function () {
  2. /**
  3. * THREE.Loader loads FBX file and generates THREE.Group representing FBX scene.
  4. * Requires FBX file to be >= 7.0 and in ASCII or >= 6400 in Binary format
  5. * Versions lower than this may load but will probably have errors
  6. *
  7. * Needs Support:
  8. * Morph normals / blend shape normals
  9. *
  10. * FBX format references:
  11. * https://wiki.blender.org/index.php/User:Mont29/Foundation/FBX_File_Structure
  12. * http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_index_html (C++ SDK reference)
  13. *
  14. * Binary format specification:
  15. * https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  16. */
  17. let fbxTree;
  18. let connections;
  19. let sceneGraph;
  20. class FBXLoader extends THREE.Loader {
  21. constructor( manager ) {
  22. super( manager );
  23. }
  24. load( url, onLoad, onProgress, onError ) {
  25. const scope = this;
  26. const path = scope.path === '' ? THREE.LoaderUtils.extractUrlBase( url ) : scope.path;
  27. const loader = new THREE.FileLoader( this.manager );
  28. loader.setPath( scope.path );
  29. loader.setResponseType( 'arraybuffer' );
  30. loader.setRequestHeader( scope.requestHeader );
  31. loader.setWithCredentials( scope.withCredentials );
  32. loader.load( url, function ( buffer ) {
  33. try {
  34. onLoad( scope.parse( buffer, path ) );
  35. } catch ( e ) {
  36. if ( onError ) {
  37. onError( e );
  38. } else {
  39. console.error( e );
  40. }
  41. scope.manager.itemError( url );
  42. }
  43. }, onProgress, onError );
  44. }
  45. parse( FBXBuffer, path ) {
  46. if ( isFbxFormatBinary( FBXBuffer ) ) {
  47. fbxTree = new BinaryParser().parse( FBXBuffer );
  48. } else {
  49. const FBXText = convertArrayBufferToString( FBXBuffer );
  50. if ( ! isFbxFormatASCII( FBXText ) ) {
  51. throw new Error( 'THREE.FBXLoader: Unknown format.' );
  52. }
  53. if ( getFbxVersion( FBXText ) < 7000 ) {
  54. throw new Error( 'THREE.FBXLoader: FBX version not supported, FileVersion: ' + getFbxVersion( FBXText ) );
  55. }
  56. fbxTree = new TextParser().parse( FBXText );
  57. } // console.log( fbxTree );
  58. const textureLoader = new THREE.TextureLoader( this.manager ).setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  59. return new FBXTreeParser( textureLoader, this.manager ).parse( fbxTree );
  60. }
  61. } // Parse the FBXTree object returned by the BinaryParser or TextParser and return a THREE.Group
  62. class FBXTreeParser {
  63. constructor( textureLoader, manager ) {
  64. this.textureLoader = textureLoader;
  65. this.manager = manager;
  66. }
  67. parse() {
  68. connections = this.parseConnections();
  69. const images = this.parseImages();
  70. const textures = this.parseTextures( images );
  71. const materials = this.parseMaterials( textures );
  72. const deformers = this.parseDeformers();
  73. const geometryMap = new GeometryParser().parse( deformers );
  74. this.parseScene( deformers, geometryMap, materials );
  75. return sceneGraph;
  76. } // Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry )
  77. // and details the connection type
  78. parseConnections() {
  79. const connectionMap = new Map();
  80. if ( 'Connections' in fbxTree ) {
  81. const rawConnections = fbxTree.Connections.connections;
  82. rawConnections.forEach( function ( rawConnection ) {
  83. const fromID = rawConnection[ 0 ];
  84. const toID = rawConnection[ 1 ];
  85. const relationship = rawConnection[ 2 ];
  86. if ( ! connectionMap.has( fromID ) ) {
  87. connectionMap.set( fromID, {
  88. parents: [],
  89. children: []
  90. } );
  91. }
  92. const parentRelationship = {
  93. ID: toID,
  94. relationship: relationship
  95. };
  96. connectionMap.get( fromID ).parents.push( parentRelationship );
  97. if ( ! connectionMap.has( toID ) ) {
  98. connectionMap.set( toID, {
  99. parents: [],
  100. children: []
  101. } );
  102. }
  103. const childRelationship = {
  104. ID: fromID,
  105. relationship: relationship
  106. };
  107. connectionMap.get( toID ).children.push( childRelationship );
  108. } );
  109. }
  110. return connectionMap;
  111. } // Parse FBXTree.Objects.Video for embedded image data
  112. // These images are connected to textures in FBXTree.Objects.Textures
  113. // via FBXTree.Connections.
  114. parseImages() {
  115. const images = {};
  116. const blobs = {};
  117. if ( 'Video' in fbxTree.Objects ) {
  118. const videoNodes = fbxTree.Objects.Video;
  119. for ( const nodeID in videoNodes ) {
  120. const videoNode = videoNodes[ nodeID ];
  121. const id = parseInt( nodeID );
  122. images[ id ] = videoNode.RelativeFilename || videoNode.Filename; // raw image data is in videoNode.Content
  123. if ( 'Content' in videoNode ) {
  124. const arrayBufferContent = videoNode.Content instanceof ArrayBuffer && videoNode.Content.byteLength > 0;
  125. const base64Content = typeof videoNode.Content === 'string' && videoNode.Content !== '';
  126. if ( arrayBufferContent || base64Content ) {
  127. const image = this.parseImage( videoNodes[ nodeID ] );
  128. blobs[ videoNode.RelativeFilename || videoNode.Filename ] = image;
  129. }
  130. }
  131. }
  132. }
  133. for ( const id in images ) {
  134. const filename = images[ id ];
  135. if ( blobs[ filename ] !== undefined ) images[ id ] = blobs[ filename ]; else images[ id ] = images[ id ].split( '\\' ).pop();
  136. }
  137. return images;
  138. } // Parse embedded image data in FBXTree.Video.Content
  139. parseImage( videoNode ) {
  140. const content = videoNode.Content;
  141. const fileName = videoNode.RelativeFilename || videoNode.Filename;
  142. const extension = fileName.slice( fileName.lastIndexOf( '.' ) + 1 ).toLowerCase();
  143. let type;
  144. switch ( extension ) {
  145. case 'bmp':
  146. type = 'image/bmp';
  147. break;
  148. case 'jpg':
  149. case 'jpeg':
  150. type = 'image/jpeg';
  151. break;
  152. case 'png':
  153. type = 'image/png';
  154. break;
  155. case 'tif':
  156. type = 'image/tiff';
  157. break;
  158. case 'tga':
  159. if ( this.manager.getHandler( '.tga' ) === null ) {
  160. console.warn( 'FBXLoader: TGA loader not found, skipping ', fileName );
  161. }
  162. type = 'image/tga';
  163. break;
  164. default:
  165. console.warn( 'FBXLoader: Image type "' + extension + '" is not supported.' );
  166. return;
  167. }
  168. if ( typeof content === 'string' ) {
  169. // ASCII format
  170. return 'data:' + type + ';base64,' + content;
  171. } else {
  172. // Binary Format
  173. const array = new Uint8Array( content );
  174. return window.URL.createObjectURL( new Blob( [ array ], {
  175. type: type
  176. } ) );
  177. }
  178. } // Parse nodes in FBXTree.Objects.Texture
  179. // These contain details such as UV scaling, cropping, rotation etc and are connected
  180. // to images in FBXTree.Objects.Video
  181. parseTextures( images ) {
  182. const textureMap = new Map();
  183. if ( 'Texture' in fbxTree.Objects ) {
  184. const textureNodes = fbxTree.Objects.Texture;
  185. for ( const nodeID in textureNodes ) {
  186. const texture = this.parseTexture( textureNodes[ nodeID ], images );
  187. textureMap.set( parseInt( nodeID ), texture );
  188. }
  189. }
  190. return textureMap;
  191. } // Parse individual node in FBXTree.Objects.Texture
  192. parseTexture( textureNode, images ) {
  193. const texture = this.loadTexture( textureNode, images );
  194. texture.ID = textureNode.id;
  195. texture.name = textureNode.attrName;
  196. const wrapModeU = textureNode.WrapModeU;
  197. const wrapModeV = textureNode.WrapModeV;
  198. const valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
  199. const valueV = wrapModeV !== undefined ? wrapModeV.value : 0; // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
  200. // 0: repeat(default), 1: clamp
  201. texture.wrapS = valueU === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  202. texture.wrapT = valueV === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  203. if ( 'Scaling' in textureNode ) {
  204. const values = textureNode.Scaling.value;
  205. texture.repeat.x = values[ 0 ];
  206. texture.repeat.y = values[ 1 ];
  207. }
  208. return texture;
  209. } // load a texture specified as a blob or data URI, or via an external URL using THREE.TextureLoader
  210. loadTexture( textureNode, images ) {
  211. let fileName;
  212. const currentPath = this.textureLoader.path;
  213. const children = connections.get( textureNode.id ).children;
  214. if ( children !== undefined && children.length > 0 && images[ children[ 0 ].ID ] !== undefined ) {
  215. fileName = images[ children[ 0 ].ID ];
  216. if ( fileName.indexOf( 'blob:' ) === 0 || fileName.indexOf( 'data:' ) === 0 ) {
  217. this.textureLoader.setPath( undefined );
  218. }
  219. }
  220. let texture;
  221. const extension = textureNode.FileName.slice( - 3 ).toLowerCase();
  222. if ( extension === 'tga' ) {
  223. const loader = this.manager.getHandler( '.tga' );
  224. if ( loader === null ) {
  225. console.warn( 'FBXLoader: TGA loader not found, creating placeholder texture for', textureNode.RelativeFilename );
  226. texture = new THREE.Texture();
  227. } else {
  228. texture = loader.load( fileName );
  229. }
  230. } else if ( extension === 'psd' ) {
  231. console.warn( 'FBXLoader: PSD textures are not supported, creating placeholder texture for', textureNode.RelativeFilename );
  232. texture = new THREE.Texture();
  233. } else {
  234. texture = this.textureLoader.load( fileName );
  235. }
  236. this.textureLoader.setPath( currentPath );
  237. return texture;
  238. } // Parse nodes in FBXTree.Objects.Material
  239. parseMaterials( textureMap ) {
  240. const materialMap = new Map();
  241. if ( 'Material' in fbxTree.Objects ) {
  242. const materialNodes = fbxTree.Objects.Material;
  243. for ( const nodeID in materialNodes ) {
  244. const material = this.parseMaterial( materialNodes[ nodeID ], textureMap );
  245. if ( material !== null ) materialMap.set( parseInt( nodeID ), material );
  246. }
  247. }
  248. return materialMap;
  249. } // Parse single node in FBXTree.Objects.Material
  250. // Materials are connected to texture maps in FBXTree.Objects.Textures
  251. // FBX format currently only supports Lambert and Phong shading models
  252. parseMaterial( materialNode, textureMap ) {
  253. const ID = materialNode.id;
  254. const name = materialNode.attrName;
  255. let type = materialNode.ShadingModel; // Case where FBX wraps shading model in property object.
  256. if ( typeof type === 'object' ) {
  257. type = type.value;
  258. } // Ignore unused materials which don't have any connections.
  259. if ( ! connections.has( ID ) ) return null;
  260. const parameters = this.parseParameters( materialNode, textureMap, ID );
  261. let material;
  262. switch ( type.toLowerCase() ) {
  263. case 'phong':
  264. material = new THREE.MeshPhongMaterial();
  265. break;
  266. case 'lambert':
  267. material = new THREE.MeshLambertMaterial();
  268. break;
  269. default:
  270. console.warn( 'THREE.FBXLoader: unknown material type "%s". Defaulting to THREE.MeshPhongMaterial.', type );
  271. material = new THREE.MeshPhongMaterial();
  272. break;
  273. }
  274. material.setValues( parameters );
  275. material.name = name;
  276. return material;
  277. } // Parse FBX material and return parameters suitable for a three.js material
  278. // Also parse the texture map and return any textures associated with the material
  279. parseParameters( materialNode, textureMap, ID ) {
  280. const parameters = {};
  281. if ( materialNode.BumpFactor ) {
  282. parameters.bumpScale = materialNode.BumpFactor.value;
  283. }
  284. if ( materialNode.Diffuse ) {
  285. parameters.color = new THREE.Color().fromArray( materialNode.Diffuse.value );
  286. } else if ( materialNode.DiffuseColor && ( materialNode.DiffuseColor.type === 'Color' || materialNode.DiffuseColor.type === 'ColorRGB' ) ) {
  287. // The blender exporter exports diffuse here instead of in materialNode.Diffuse
  288. parameters.color = new THREE.Color().fromArray( materialNode.DiffuseColor.value );
  289. }
  290. if ( materialNode.DisplacementFactor ) {
  291. parameters.displacementScale = materialNode.DisplacementFactor.value;
  292. }
  293. if ( materialNode.Emissive ) {
  294. parameters.emissive = new THREE.Color().fromArray( materialNode.Emissive.value );
  295. } else if ( materialNode.EmissiveColor && ( materialNode.EmissiveColor.type === 'Color' || materialNode.EmissiveColor.type === 'ColorRGB' ) ) {
  296. // The blender exporter exports emissive color here instead of in materialNode.Emissive
  297. parameters.emissive = new THREE.Color().fromArray( materialNode.EmissiveColor.value );
  298. }
  299. if ( materialNode.EmissiveFactor ) {
  300. parameters.emissiveIntensity = parseFloat( materialNode.EmissiveFactor.value );
  301. }
  302. if ( materialNode.Opacity ) {
  303. parameters.opacity = parseFloat( materialNode.Opacity.value );
  304. }
  305. if ( parameters.opacity < 1.0 ) {
  306. parameters.transparent = true;
  307. }
  308. if ( materialNode.ReflectionFactor ) {
  309. parameters.reflectivity = materialNode.ReflectionFactor.value;
  310. }
  311. if ( materialNode.Shininess ) {
  312. parameters.shininess = materialNode.Shininess.value;
  313. }
  314. if ( materialNode.Specular ) {
  315. parameters.specular = new THREE.Color().fromArray( materialNode.Specular.value );
  316. } else if ( materialNode.SpecularColor && materialNode.SpecularColor.type === 'Color' ) {
  317. // The blender exporter exports specular color here instead of in materialNode.Specular
  318. parameters.specular = new THREE.Color().fromArray( materialNode.SpecularColor.value );
  319. }
  320. const scope = this;
  321. connections.get( ID ).children.forEach( function ( child ) {
  322. const type = child.relationship;
  323. switch ( type ) {
  324. case 'Bump':
  325. parameters.bumpMap = scope.getTexture( textureMap, child.ID );
  326. break;
  327. case 'Maya|TEX_ao_map':
  328. parameters.aoMap = scope.getTexture( textureMap, child.ID );
  329. break;
  330. case 'DiffuseColor':
  331. case 'Maya|TEX_color_map':
  332. parameters.map = scope.getTexture( textureMap, child.ID );
  333. parameters.map.encoding = THREE.sRGBEncoding;
  334. break;
  335. case 'DisplacementColor':
  336. parameters.displacementMap = scope.getTexture( textureMap, child.ID );
  337. break;
  338. case 'EmissiveColor':
  339. parameters.emissiveMap = scope.getTexture( textureMap, child.ID );
  340. parameters.emissiveMap.encoding = THREE.sRGBEncoding;
  341. break;
  342. case 'NormalMap':
  343. case 'Maya|TEX_normal_map':
  344. parameters.normalMap = scope.getTexture( textureMap, child.ID );
  345. break;
  346. case 'ReflectionColor':
  347. parameters.envMap = scope.getTexture( textureMap, child.ID );
  348. parameters.envMap.mapping = THREE.EquirectangularReflectionMapping;
  349. parameters.envMap.encoding = THREE.sRGBEncoding;
  350. break;
  351. case 'SpecularColor':
  352. parameters.specularMap = scope.getTexture( textureMap, child.ID );
  353. parameters.specularMap.encoding = THREE.sRGBEncoding;
  354. break;
  355. case 'TransparentColor':
  356. case 'TransparencyFactor':
  357. parameters.alphaMap = scope.getTexture( textureMap, child.ID );
  358. parameters.transparent = true;
  359. break;
  360. case 'AmbientColor':
  361. case 'ShininessExponent': // AKA glossiness map
  362. case 'SpecularFactor': // AKA specularLevel
  363. case 'VectorDisplacementColor': // NOTE: Seems to be a copy of DisplacementColor
  364. default:
  365. console.warn( 'THREE.FBXLoader: %s map is not supported in three.js, skipping texture.', type );
  366. break;
  367. }
  368. } );
  369. return parameters;
  370. } // get a texture from the textureMap for use by a material.
  371. getTexture( textureMap, id ) {
  372. // if the texture is a layered texture, just use the first layer and issue a warning
  373. if ( 'LayeredTexture' in fbxTree.Objects && id in fbxTree.Objects.LayeredTexture ) {
  374. console.warn( 'THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer.' );
  375. id = connections.get( id ).children[ 0 ].ID;
  376. }
  377. return textureMap.get( id );
  378. } // Parse nodes in FBXTree.Objects.Deformer
  379. // Deformer node can contain skinning or Vertex Cache animation data, however only skinning is supported here
  380. // Generates map of THREE.Skeleton-like objects for use later when generating and binding skeletons.
  381. parseDeformers() {
  382. const skeletons = {};
  383. const morphTargets = {};
  384. if ( 'Deformer' in fbxTree.Objects ) {
  385. const DeformerNodes = fbxTree.Objects.Deformer;
  386. for ( const nodeID in DeformerNodes ) {
  387. const deformerNode = DeformerNodes[ nodeID ];
  388. const relationships = connections.get( parseInt( nodeID ) );
  389. if ( deformerNode.attrType === 'Skin' ) {
  390. const skeleton = this.parseSkeleton( relationships, DeformerNodes );
  391. skeleton.ID = nodeID;
  392. if ( relationships.parents.length > 1 ) console.warn( 'THREE.FBXLoader: skeleton attached to more than one geometry is not supported.' );
  393. skeleton.geometryID = relationships.parents[ 0 ].ID;
  394. skeletons[ nodeID ] = skeleton;
  395. } else if ( deformerNode.attrType === 'BlendShape' ) {
  396. const morphTarget = {
  397. id: nodeID
  398. };
  399. morphTarget.rawTargets = this.parseMorphTargets( relationships, DeformerNodes );
  400. morphTarget.id = nodeID;
  401. if ( relationships.parents.length > 1 ) console.warn( 'THREE.FBXLoader: morph target attached to more than one geometry is not supported.' );
  402. morphTargets[ nodeID ] = morphTarget;
  403. }
  404. }
  405. }
  406. return {
  407. skeletons: skeletons,
  408. morphTargets: morphTargets
  409. };
  410. } // Parse single nodes in FBXTree.Objects.Deformer
  411. // The top level skeleton node has type 'Skin' and sub nodes have type 'Cluster'
  412. // Each skin node represents a skeleton and each cluster node represents a bone
  413. parseSkeleton( relationships, deformerNodes ) {
  414. const rawBones = [];
  415. relationships.children.forEach( function ( child ) {
  416. const boneNode = deformerNodes[ child.ID ];
  417. if ( boneNode.attrType !== 'Cluster' ) return;
  418. const rawBone = {
  419. ID: child.ID,
  420. indices: [],
  421. weights: [],
  422. transformLink: new THREE.Matrix4().fromArray( boneNode.TransformLink.a ) // transform: new THREE.Matrix4().fromArray( boneNode.Transform.a ),
  423. // linkMode: boneNode.Mode,
  424. };
  425. if ( 'Indexes' in boneNode ) {
  426. rawBone.indices = boneNode.Indexes.a;
  427. rawBone.weights = boneNode.Weights.a;
  428. }
  429. rawBones.push( rawBone );
  430. } );
  431. return {
  432. rawBones: rawBones,
  433. bones: []
  434. };
  435. } // The top level morph deformer node has type "BlendShape" and sub nodes have type "BlendShapeChannel"
  436. parseMorphTargets( relationships, deformerNodes ) {
  437. const rawMorphTargets = [];
  438. for ( let i = 0; i < relationships.children.length; i ++ ) {
  439. const child = relationships.children[ i ];
  440. const morphTargetNode = deformerNodes[ child.ID ];
  441. const rawMorphTarget = {
  442. name: morphTargetNode.attrName,
  443. initialWeight: morphTargetNode.DeformPercent,
  444. id: morphTargetNode.id,
  445. fullWeights: morphTargetNode.FullWeights.a
  446. };
  447. if ( morphTargetNode.attrType !== 'BlendShapeChannel' ) return;
  448. rawMorphTarget.geoID = connections.get( parseInt( child.ID ) ).children.filter( function ( child ) {
  449. return child.relationship === undefined;
  450. } )[ 0 ].ID;
  451. rawMorphTargets.push( rawMorphTarget );
  452. }
  453. return rawMorphTargets;
  454. } // create the main THREE.Group() to be returned by the loader
  455. parseScene( deformers, geometryMap, materialMap ) {
  456. sceneGraph = new THREE.Group();
  457. const modelMap = this.parseModels( deformers.skeletons, geometryMap, materialMap );
  458. const modelNodes = fbxTree.Objects.Model;
  459. const scope = this;
  460. modelMap.forEach( function ( model ) {
  461. const modelNode = modelNodes[ model.ID ];
  462. scope.setLookAtProperties( model, modelNode );
  463. const parentConnections = connections.get( model.ID ).parents;
  464. parentConnections.forEach( function ( connection ) {
  465. const parent = modelMap.get( connection.ID );
  466. if ( parent !== undefined ) parent.add( model );
  467. } );
  468. if ( model.parent === null ) {
  469. sceneGraph.add( model );
  470. }
  471. } );
  472. this.bindSkeleton( deformers.skeletons, geometryMap, modelMap );
  473. this.createAmbientLight();
  474. this.setupMorphMaterials();
  475. sceneGraph.traverse( function ( node ) {
  476. if ( node.userData.transformData ) {
  477. if ( node.parent ) {
  478. node.userData.transformData.parentMatrix = node.parent.matrix;
  479. node.userData.transformData.parentMatrixWorld = node.parent.matrixWorld;
  480. }
  481. const transform = generateTransform( node.userData.transformData );
  482. node.applyMatrix4( transform );
  483. node.updateWorldMatrix();
  484. }
  485. } );
  486. const animations = new AnimationParser().parse(); // if all the models where already combined in a single group, just return that
  487. if ( sceneGraph.children.length === 1 && sceneGraph.children[ 0 ].isGroup ) {
  488. sceneGraph.children[ 0 ].animations = animations;
  489. sceneGraph = sceneGraph.children[ 0 ];
  490. }
  491. sceneGraph.animations = animations;
  492. } // parse nodes in FBXTree.Objects.Model
  493. parseModels( skeletons, geometryMap, materialMap ) {
  494. const modelMap = new Map();
  495. const modelNodes = fbxTree.Objects.Model;
  496. for ( const nodeID in modelNodes ) {
  497. const id = parseInt( nodeID );
  498. const node = modelNodes[ nodeID ];
  499. const relationships = connections.get( id );
  500. let model = this.buildSkeleton( relationships, skeletons, id, node.attrName );
  501. if ( ! model ) {
  502. switch ( node.attrType ) {
  503. case 'Camera':
  504. model = this.createCamera( relationships );
  505. break;
  506. case 'Light':
  507. model = this.createLight( relationships );
  508. break;
  509. case 'Mesh':
  510. model = this.createMesh( relationships, geometryMap, materialMap );
  511. break;
  512. case 'NurbsCurve':
  513. model = this.createCurve( relationships, geometryMap );
  514. break;
  515. case 'LimbNode':
  516. case 'Root':
  517. model = new THREE.Bone();
  518. break;
  519. case 'Null':
  520. default:
  521. model = new THREE.Group();
  522. break;
  523. }
  524. model.name = node.attrName ? THREE.PropertyBinding.sanitizeNodeName( node.attrName ) : '';
  525. model.ID = id;
  526. }
  527. this.getTransformData( model, node );
  528. modelMap.set( id, model );
  529. }
  530. return modelMap;
  531. }
  532. buildSkeleton( relationships, skeletons, id, name ) {
  533. let bone = null;
  534. relationships.parents.forEach( function ( parent ) {
  535. for ( const ID in skeletons ) {
  536. const skeleton = skeletons[ ID ];
  537. skeleton.rawBones.forEach( function ( rawBone, i ) {
  538. if ( rawBone.ID === parent.ID ) {
  539. const subBone = bone;
  540. bone = new THREE.Bone();
  541. bone.matrixWorld.copy( rawBone.transformLink ); // set name and id here - otherwise in cases where "subBone" is created it will not have a name / id
  542. bone.name = name ? THREE.PropertyBinding.sanitizeNodeName( name ) : '';
  543. bone.ID = id;
  544. skeleton.bones[ i ] = bone; // In cases where a bone is shared between multiple meshes
  545. // duplicate the bone here and and it as a child of the first bone
  546. if ( subBone !== null ) {
  547. bone.add( subBone );
  548. }
  549. }
  550. } );
  551. }
  552. } );
  553. return bone;
  554. } // create a THREE.PerspectiveCamera or THREE.OrthographicCamera
  555. createCamera( relationships ) {
  556. let model;
  557. let cameraAttribute;
  558. relationships.children.forEach( function ( child ) {
  559. const attr = fbxTree.Objects.NodeAttribute[ child.ID ];
  560. if ( attr !== undefined ) {
  561. cameraAttribute = attr;
  562. }
  563. } );
  564. if ( cameraAttribute === undefined ) {
  565. model = new THREE.Object3D();
  566. } else {
  567. let type = 0;
  568. if ( cameraAttribute.CameraProjectionType !== undefined && cameraAttribute.CameraProjectionType.value === 1 ) {
  569. type = 1;
  570. }
  571. let nearClippingPlane = 1;
  572. if ( cameraAttribute.NearPlane !== undefined ) {
  573. nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
  574. }
  575. let farClippingPlane = 1000;
  576. if ( cameraAttribute.FarPlane !== undefined ) {
  577. farClippingPlane = cameraAttribute.FarPlane.value / 1000;
  578. }
  579. let width = window.innerWidth;
  580. let height = window.innerHeight;
  581. if ( cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined ) {
  582. width = cameraAttribute.AspectWidth.value;
  583. height = cameraAttribute.AspectHeight.value;
  584. }
  585. const aspect = width / height;
  586. let fov = 45;
  587. if ( cameraAttribute.FieldOfView !== undefined ) {
  588. fov = cameraAttribute.FieldOfView.value;
  589. }
  590. const focalLength = cameraAttribute.FocalLength ? cameraAttribute.FocalLength.value : null;
  591. switch ( type ) {
  592. case 0:
  593. // Perspective
  594. model = new THREE.PerspectiveCamera( fov, aspect, nearClippingPlane, farClippingPlane );
  595. if ( focalLength !== null ) model.setFocalLength( focalLength );
  596. break;
  597. case 1:
  598. // Orthographic
  599. model = new THREE.OrthographicCamera( - width / 2, width / 2, height / 2, - height / 2, nearClippingPlane, farClippingPlane );
  600. break;
  601. default:
  602. console.warn( 'THREE.FBXLoader: Unknown camera type ' + type + '.' );
  603. model = new THREE.Object3D();
  604. break;
  605. }
  606. }
  607. return model;
  608. } // Create a THREE.DirectionalLight, THREE.PointLight or THREE.SpotLight
  609. createLight( relationships ) {
  610. let model;
  611. let lightAttribute;
  612. relationships.children.forEach( function ( child ) {
  613. const attr = fbxTree.Objects.NodeAttribute[ child.ID ];
  614. if ( attr !== undefined ) {
  615. lightAttribute = attr;
  616. }
  617. } );
  618. if ( lightAttribute === undefined ) {
  619. model = new THREE.Object3D();
  620. } else {
  621. let type; // LightType can be undefined for Point lights
  622. if ( lightAttribute.LightType === undefined ) {
  623. type = 0;
  624. } else {
  625. type = lightAttribute.LightType.value;
  626. }
  627. let color = 0xffffff;
  628. if ( lightAttribute.Color !== undefined ) {
  629. color = new THREE.Color().fromArray( lightAttribute.Color.value );
  630. }
  631. let intensity = lightAttribute.Intensity === undefined ? 1 : lightAttribute.Intensity.value / 100; // light disabled
  632. if ( lightAttribute.CastLightOnObject !== undefined && lightAttribute.CastLightOnObject.value === 0 ) {
  633. intensity = 0;
  634. }
  635. let distance = 0;
  636. if ( lightAttribute.FarAttenuationEnd !== undefined ) {
  637. if ( lightAttribute.EnableFarAttenuation !== undefined && lightAttribute.EnableFarAttenuation.value === 0 ) {
  638. distance = 0;
  639. } else {
  640. distance = lightAttribute.FarAttenuationEnd.value;
  641. }
  642. } // TODO: could this be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
  643. const decay = 1;
  644. switch ( type ) {
  645. case 0:
  646. // Point
  647. model = new THREE.PointLight( color, intensity, distance, decay );
  648. break;
  649. case 1:
  650. // Directional
  651. model = new THREE.DirectionalLight( color, intensity );
  652. break;
  653. case 2:
  654. // Spot
  655. let angle = Math.PI / 3;
  656. if ( lightAttribute.InnerAngle !== undefined ) {
  657. angle = THREE.MathUtils.degToRad( lightAttribute.InnerAngle.value );
  658. }
  659. let penumbra = 0;
  660. if ( lightAttribute.OuterAngle !== undefined ) {
  661. // TODO: this is not correct - FBX calculates outer and inner angle in degrees
  662. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  663. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  664. penumbra = THREE.MathUtils.degToRad( lightAttribute.OuterAngle.value );
  665. penumbra = Math.max( penumbra, 1 );
  666. }
  667. model = new THREE.SpotLight( color, intensity, distance, angle, penumbra, decay );
  668. break;
  669. default:
  670. console.warn( 'THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a THREE.PointLight.' );
  671. model = new THREE.PointLight( color, intensity );
  672. break;
  673. }
  674. if ( lightAttribute.CastShadows !== undefined && lightAttribute.CastShadows.value === 1 ) {
  675. model.castShadow = true;
  676. }
  677. }
  678. return model;
  679. }
  680. createMesh( relationships, geometryMap, materialMap ) {
  681. let model;
  682. let geometry = null;
  683. let material = null;
  684. const materials = []; // get geometry and materials(s) from connections
  685. relationships.children.forEach( function ( child ) {
  686. if ( geometryMap.has( child.ID ) ) {
  687. geometry = geometryMap.get( child.ID );
  688. }
  689. if ( materialMap.has( child.ID ) ) {
  690. materials.push( materialMap.get( child.ID ) );
  691. }
  692. } );
  693. if ( materials.length > 1 ) {
  694. material = materials;
  695. } else if ( materials.length > 0 ) {
  696. material = materials[ 0 ];
  697. } else {
  698. material = new THREE.MeshPhongMaterial( {
  699. color: 0xcccccc
  700. } );
  701. materials.push( material );
  702. }
  703. if ( 'color' in geometry.attributes ) {
  704. materials.forEach( function ( material ) {
  705. material.vertexColors = true;
  706. } );
  707. }
  708. if ( geometry.FBX_Deformer ) {
  709. materials.forEach( function ( material ) {
  710. material.skinning = true;
  711. } );
  712. model = new THREE.SkinnedMesh( geometry, material );
  713. model.normalizeSkinWeights();
  714. } else {
  715. model = new THREE.Mesh( geometry, material );
  716. }
  717. return model;
  718. }
  719. createCurve( relationships, geometryMap ) {
  720. const geometry = relationships.children.reduce( function ( geo, child ) {
  721. if ( geometryMap.has( child.ID ) ) geo = geometryMap.get( child.ID );
  722. return geo;
  723. }, null ); // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  724. const material = new THREE.LineBasicMaterial( {
  725. color: 0x3300ff,
  726. linewidth: 1
  727. } );
  728. return new THREE.Line( geometry, material );
  729. } // parse the model node for transform data
  730. getTransformData( model, modelNode ) {
  731. const transformData = {};
  732. if ( 'InheritType' in modelNode ) transformData.inheritType = parseInt( modelNode.InheritType.value );
  733. if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = getEulerOrder( modelNode.RotationOrder.value ); else transformData.eulerOrder = 'ZYX';
  734. if ( 'Lcl_Translation' in modelNode ) transformData.translation = modelNode.Lcl_Translation.value;
  735. if ( 'PreRotation' in modelNode ) transformData.preRotation = modelNode.PreRotation.value;
  736. if ( 'Lcl_Rotation' in modelNode ) transformData.rotation = modelNode.Lcl_Rotation.value;
  737. if ( 'PostRotation' in modelNode ) transformData.postRotation = modelNode.PostRotation.value;
  738. if ( 'Lcl_Scaling' in modelNode ) transformData.scale = modelNode.Lcl_Scaling.value;
  739. if ( 'ScalingOffset' in modelNode ) transformData.scalingOffset = modelNode.ScalingOffset.value;
  740. if ( 'ScalingPivot' in modelNode ) transformData.scalingPivot = modelNode.ScalingPivot.value;
  741. if ( 'RotationOffset' in modelNode ) transformData.rotationOffset = modelNode.RotationOffset.value;
  742. if ( 'RotationPivot' in modelNode ) transformData.rotationPivot = modelNode.RotationPivot.value;
  743. model.userData.transformData = transformData;
  744. }
  745. setLookAtProperties( model, modelNode ) {
  746. if ( 'LookAtProperty' in modelNode ) {
  747. const children = connections.get( model.ID ).children;
  748. children.forEach( function ( child ) {
  749. if ( child.relationship === 'LookAtProperty' ) {
  750. const lookAtTarget = fbxTree.Objects.Model[ child.ID ];
  751. if ( 'Lcl_Translation' in lookAtTarget ) {
  752. const pos = lookAtTarget.Lcl_Translation.value; // THREE.DirectionalLight, THREE.SpotLight
  753. if ( model.target !== undefined ) {
  754. model.target.position.fromArray( pos );
  755. sceneGraph.add( model.target );
  756. } else {
  757. // Cameras and other Object3Ds
  758. model.lookAt( new THREE.Vector3().fromArray( pos ) );
  759. }
  760. }
  761. }
  762. } );
  763. }
  764. }
  765. bindSkeleton( skeletons, geometryMap, modelMap ) {
  766. const bindMatrices = this.parsePoseNodes();
  767. for ( const ID in skeletons ) {
  768. const skeleton = skeletons[ ID ];
  769. const parents = connections.get( parseInt( skeleton.ID ) ).parents;
  770. parents.forEach( function ( parent ) {
  771. if ( geometryMap.has( parent.ID ) ) {
  772. const geoID = parent.ID;
  773. const geoRelationships = connections.get( geoID );
  774. geoRelationships.parents.forEach( function ( geoConnParent ) {
  775. if ( modelMap.has( geoConnParent.ID ) ) {
  776. const model = modelMap.get( geoConnParent.ID );
  777. model.bind( new THREE.Skeleton( skeleton.bones ), bindMatrices[ geoConnParent.ID ] );
  778. }
  779. } );
  780. }
  781. } );
  782. }
  783. }
  784. parsePoseNodes() {
  785. const bindMatrices = {};
  786. if ( 'Pose' in fbxTree.Objects ) {
  787. const BindPoseNode = fbxTree.Objects.Pose;
  788. for ( const nodeID in BindPoseNode ) {
  789. if ( BindPoseNode[ nodeID ].attrType === 'BindPose' ) {
  790. const poseNodes = BindPoseNode[ nodeID ].PoseNode;
  791. if ( Array.isArray( poseNodes ) ) {
  792. poseNodes.forEach( function ( poseNode ) {
  793. bindMatrices[ poseNode.Node ] = new THREE.Matrix4().fromArray( poseNode.Matrix.a );
  794. } );
  795. } else {
  796. bindMatrices[ poseNodes.Node ] = new THREE.Matrix4().fromArray( poseNodes.Matrix.a );
  797. }
  798. }
  799. }
  800. }
  801. return bindMatrices;
  802. } // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light
  803. createAmbientLight() {
  804. if ( 'GlobalSettings' in fbxTree && 'AmbientColor' in fbxTree.GlobalSettings ) {
  805. const ambientColor = fbxTree.GlobalSettings.AmbientColor.value;
  806. const r = ambientColor[ 0 ];
  807. const g = ambientColor[ 1 ];
  808. const b = ambientColor[ 2 ];
  809. if ( r !== 0 || g !== 0 || b !== 0 ) {
  810. const color = new THREE.Color( r, g, b );
  811. sceneGraph.add( new THREE.AmbientLight( color, 1 ) );
  812. }
  813. }
  814. }
  815. setupMorphMaterials() {
  816. const scope = this;
  817. sceneGraph.traverse( function ( child ) {
  818. if ( child.isMesh ) {
  819. if ( child.geometry.morphAttributes.position && child.geometry.morphAttributes.position.length ) {
  820. if ( Array.isArray( child.material ) ) {
  821. child.material.forEach( function ( material, i ) {
  822. scope.setupMorphMaterial( child, material, i );
  823. } );
  824. } else {
  825. scope.setupMorphMaterial( child, child.material );
  826. }
  827. }
  828. }
  829. } );
  830. }
  831. setupMorphMaterial( child, material, index ) {
  832. const uuid = child.uuid;
  833. const matUuid = material.uuid; // if a geometry has morph targets, it cannot share the material with other geometries
  834. let sharedMat = false;
  835. sceneGraph.traverse( function ( node ) {
  836. if ( node.isMesh ) {
  837. if ( Array.isArray( node.material ) ) {
  838. node.material.forEach( function ( mat ) {
  839. if ( mat.uuid === matUuid && node.uuid !== uuid ) sharedMat = true;
  840. } );
  841. } else if ( node.material.uuid === matUuid && node.uuid !== uuid ) sharedMat = true;
  842. }
  843. } );
  844. if ( sharedMat === true ) {
  845. const clonedMat = material.clone();
  846. clonedMat.morphTargets = true;
  847. if ( index === undefined ) child.material = clonedMat; else child.material[ index ] = clonedMat;
  848. } else material.morphTargets = true;
  849. }
  850. } // parse Geometry data from FBXTree and return map of BufferGeometries
  851. class GeometryParser {
  852. // Parse nodes in FBXTree.Objects.Geometry
  853. parse( deformers ) {
  854. const geometryMap = new Map();
  855. if ( 'Geometry' in fbxTree.Objects ) {
  856. const geoNodes = fbxTree.Objects.Geometry;
  857. for ( const nodeID in geoNodes ) {
  858. const relationships = connections.get( parseInt( nodeID ) );
  859. const geo = this.parseGeometry( relationships, geoNodes[ nodeID ], deformers );
  860. geometryMap.set( parseInt( nodeID ), geo );
  861. }
  862. }
  863. return geometryMap;
  864. } // Parse single node in FBXTree.Objects.Geometry
  865. parseGeometry( relationships, geoNode, deformers ) {
  866. switch ( geoNode.attrType ) {
  867. case 'Mesh':
  868. return this.parseMeshGeometry( relationships, geoNode, deformers );
  869. break;
  870. case 'NurbsCurve':
  871. return this.parseNurbsGeometry( geoNode );
  872. break;
  873. }
  874. } // Parse single node mesh geometry in FBXTree.Objects.Geometry
  875. parseMeshGeometry( relationships, geoNode, deformers ) {
  876. const skeletons = deformers.skeletons;
  877. const morphTargets = [];
  878. const modelNodes = relationships.parents.map( function ( parent ) {
  879. return fbxTree.Objects.Model[ parent.ID ];
  880. } ); // don't create geometry if it is not associated with any models
  881. if ( modelNodes.length === 0 ) return;
  882. const skeleton = relationships.children.reduce( function ( skeleton, child ) {
  883. if ( skeletons[ child.ID ] !== undefined ) skeleton = skeletons[ child.ID ];
  884. return skeleton;
  885. }, null );
  886. relationships.children.forEach( function ( child ) {
  887. if ( deformers.morphTargets[ child.ID ] !== undefined ) {
  888. morphTargets.push( deformers.morphTargets[ child.ID ] );
  889. }
  890. } ); // Assume one model and get the preRotation from that
  891. // if there is more than one model associated with the geometry this may cause problems
  892. const modelNode = modelNodes[ 0 ];
  893. const transformData = {};
  894. if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = getEulerOrder( modelNode.RotationOrder.value );
  895. if ( 'InheritType' in modelNode ) transformData.inheritType = parseInt( modelNode.InheritType.value );
  896. if ( 'GeometricTranslation' in modelNode ) transformData.translation = modelNode.GeometricTranslation.value;
  897. if ( 'GeometricRotation' in modelNode ) transformData.rotation = modelNode.GeometricRotation.value;
  898. if ( 'GeometricScaling' in modelNode ) transformData.scale = modelNode.GeometricScaling.value;
  899. const transform = generateTransform( transformData );
  900. return this.genGeometry( geoNode, skeleton, morphTargets, transform );
  901. } // Generate a THREE.BufferGeometry from a node in FBXTree.Objects.Geometry
  902. genGeometry( geoNode, skeleton, morphTargets, preTransform ) {
  903. const geo = new THREE.BufferGeometry();
  904. if ( geoNode.attrName ) geo.name = geoNode.attrName;
  905. const geoInfo = this.parseGeoNode( geoNode, skeleton );
  906. const buffers = this.genBuffers( geoInfo );
  907. const positionAttribute = new THREE.Float32BufferAttribute( buffers.vertex, 3 );
  908. positionAttribute.applyMatrix4( preTransform );
  909. geo.setAttribute( 'position', positionAttribute );
  910. if ( buffers.colors.length > 0 ) {
  911. geo.setAttribute( 'color', new THREE.Float32BufferAttribute( buffers.colors, 3 ) );
  912. }
  913. if ( skeleton ) {
  914. geo.setAttribute( 'skinIndex', new THREE.Uint16BufferAttribute( buffers.weightsIndices, 4 ) );
  915. geo.setAttribute( 'skinWeight', new THREE.Float32BufferAttribute( buffers.vertexWeights, 4 ) ); // used later to bind the skeleton to the model
  916. geo.FBX_Deformer = skeleton;
  917. }
  918. if ( buffers.normal.length > 0 ) {
  919. const normalMatrix = new THREE.Matrix3().getNormalMatrix( preTransform );
  920. const normalAttribute = new THREE.Float32BufferAttribute( buffers.normal, 3 );
  921. normalAttribute.applyNormalMatrix( normalMatrix );
  922. geo.setAttribute( 'normal', normalAttribute );
  923. }
  924. buffers.uvs.forEach( function ( uvBuffer, i ) {
  925. // subsequent uv buffers are called 'uv1', 'uv2', ...
  926. let name = 'uv' + ( i + 1 ).toString(); // the first uv buffer is just called 'uv'
  927. if ( i === 0 ) {
  928. name = 'uv';
  929. }
  930. geo.setAttribute( name, new THREE.Float32BufferAttribute( buffers.uvs[ i ], 2 ) );
  931. } );
  932. if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {
  933. // Convert the material indices of each vertex into rendering groups on the geometry.
  934. let prevMaterialIndex = buffers.materialIndex[ 0 ];
  935. let startIndex = 0;
  936. buffers.materialIndex.forEach( function ( currentIndex, i ) {
  937. if ( currentIndex !== prevMaterialIndex ) {
  938. geo.addGroup( startIndex, i - startIndex, prevMaterialIndex );
  939. prevMaterialIndex = currentIndex;
  940. startIndex = i;
  941. }
  942. } ); // the loop above doesn't add the last group, do that here.
  943. if ( geo.groups.length > 0 ) {
  944. const lastGroup = geo.groups[ geo.groups.length - 1 ];
  945. const lastIndex = lastGroup.start + lastGroup.count;
  946. if ( lastIndex !== buffers.materialIndex.length ) {
  947. geo.addGroup( lastIndex, buffers.materialIndex.length - lastIndex, prevMaterialIndex );
  948. }
  949. } // case where there are multiple materials but the whole geometry is only
  950. // using one of them
  951. if ( geo.groups.length === 0 ) {
  952. geo.addGroup( 0, buffers.materialIndex.length, buffers.materialIndex[ 0 ] );
  953. }
  954. }
  955. this.addMorphTargets( geo, geoNode, morphTargets, preTransform );
  956. return geo;
  957. }
  958. parseGeoNode( geoNode, skeleton ) {
  959. const geoInfo = {};
  960. geoInfo.vertexPositions = geoNode.Vertices !== undefined ? geoNode.Vertices.a : [];
  961. geoInfo.vertexIndices = geoNode.PolygonVertexIndex !== undefined ? geoNode.PolygonVertexIndex.a : [];
  962. if ( geoNode.LayerElementColor ) {
  963. geoInfo.color = this.parseVertexColors( geoNode.LayerElementColor[ 0 ] );
  964. }
  965. if ( geoNode.LayerElementMaterial ) {
  966. geoInfo.material = this.parseMaterialIndices( geoNode.LayerElementMaterial[ 0 ] );
  967. }
  968. if ( geoNode.LayerElementNormal ) {
  969. geoInfo.normal = this.parseNormals( geoNode.LayerElementNormal[ 0 ] );
  970. }
  971. if ( geoNode.LayerElementUV ) {
  972. geoInfo.uv = [];
  973. let i = 0;
  974. while ( geoNode.LayerElementUV[ i ] ) {
  975. if ( geoNode.LayerElementUV[ i ].UV ) {
  976. geoInfo.uv.push( this.parseUVs( geoNode.LayerElementUV[ i ] ) );
  977. }
  978. i ++;
  979. }
  980. }
  981. geoInfo.weightTable = {};
  982. if ( skeleton !== null ) {
  983. geoInfo.skeleton = skeleton;
  984. skeleton.rawBones.forEach( function ( rawBone, i ) {
  985. // loop over the bone's vertex indices and weights
  986. rawBone.indices.forEach( function ( index, j ) {
  987. if ( geoInfo.weightTable[ index ] === undefined ) geoInfo.weightTable[ index ] = [];
  988. geoInfo.weightTable[ index ].push( {
  989. id: i,
  990. weight: rawBone.weights[ j ]
  991. } );
  992. } );
  993. } );
  994. }
  995. return geoInfo;
  996. }
  997. genBuffers( geoInfo ) {
  998. const buffers = {
  999. vertex: [],
  1000. normal: [],
  1001. colors: [],
  1002. uvs: [],
  1003. materialIndex: [],
  1004. vertexWeights: [],
  1005. weightsIndices: []
  1006. };
  1007. let polygonIndex = 0;
  1008. let faceLength = 0;
  1009. let displayedWeightsWarning = false; // these will hold data for a single face
  1010. let facePositionIndexes = [];
  1011. let faceNormals = [];
  1012. let faceColors = [];
  1013. let faceUVs = [];
  1014. let faceWeights = [];
  1015. let faceWeightIndices = [];
  1016. const scope = this;
  1017. geoInfo.vertexIndices.forEach( function ( vertexIndex, polygonVertexIndex ) {
  1018. let materialIndex;
  1019. let endOfFace = false; // Face index and vertex index arrays are combined in a single array
  1020. // A cube with quad faces looks like this:
  1021. // PolygonVertexIndex: *24 {
  1022. // a: 0, 1, 3, -3, 2, 3, 5, -5, 4, 5, 7, -7, 6, 7, 1, -1, 1, 7, 5, -4, 6, 0, 2, -5
  1023. // }
  1024. // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3
  1025. // to find index of last vertex bit shift the index: ^ - 1
  1026. if ( vertexIndex < 0 ) {
  1027. vertexIndex = vertexIndex ^ - 1; // equivalent to ( x * -1 ) - 1
  1028. endOfFace = true;
  1029. }
  1030. let weightIndices = [];
  1031. let weights = [];
  1032. facePositionIndexes.push( vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2 );
  1033. if ( geoInfo.color ) {
  1034. const data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.color );
  1035. faceColors.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  1036. }
  1037. if ( geoInfo.skeleton ) {
  1038. if ( geoInfo.weightTable[ vertexIndex ] !== undefined ) {
  1039. geoInfo.weightTable[ vertexIndex ].forEach( function ( wt ) {
  1040. weights.push( wt.weight );
  1041. weightIndices.push( wt.id );
  1042. } );
  1043. }
  1044. if ( weights.length > 4 ) {
  1045. if ( ! displayedWeightsWarning ) {
  1046. console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
  1047. displayedWeightsWarning = true;
  1048. }
  1049. const wIndex = [ 0, 0, 0, 0 ];
  1050. const Weight = [ 0, 0, 0, 0 ];
  1051. weights.forEach( function ( weight, weightIndex ) {
  1052. let currentWeight = weight;
  1053. let currentIndex = weightIndices[ weightIndex ];
  1054. Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) {
  1055. if ( currentWeight > comparedWeight ) {
  1056. comparedWeightArray[ comparedWeightIndex ] = currentWeight;
  1057. currentWeight = comparedWeight;
  1058. const tmp = wIndex[ comparedWeightIndex ];
  1059. wIndex[ comparedWeightIndex ] = currentIndex;
  1060. currentIndex = tmp;
  1061. }
  1062. } );
  1063. } );
  1064. weightIndices = wIndex;
  1065. weights = Weight;
  1066. } // if the weight array is shorter than 4 pad with 0s
  1067. while ( weights.length < 4 ) {
  1068. weights.push( 0 );
  1069. weightIndices.push( 0 );
  1070. }
  1071. for ( let i = 0; i < 4; ++ i ) {
  1072. faceWeights.push( weights[ i ] );
  1073. faceWeightIndices.push( weightIndices[ i ] );
  1074. }
  1075. }
  1076. if ( geoInfo.normal ) {
  1077. const data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.normal );
  1078. faceNormals.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  1079. }
  1080. if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {
  1081. materialIndex = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.material )[ 0 ];
  1082. }
  1083. if ( geoInfo.uv ) {
  1084. geoInfo.uv.forEach( function ( uv, i ) {
  1085. const data = getData( polygonVertexIndex, polygonIndex, vertexIndex, uv );
  1086. if ( faceUVs[ i ] === undefined ) {
  1087. faceUVs[ i ] = [];
  1088. }
  1089. faceUVs[ i ].push( data[ 0 ] );
  1090. faceUVs[ i ].push( data[ 1 ] );
  1091. } );
  1092. }
  1093. faceLength ++;
  1094. if ( endOfFace ) {
  1095. scope.genFace( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength );
  1096. polygonIndex ++;
  1097. faceLength = 0; // reset arrays for the next face
  1098. facePositionIndexes = [];
  1099. faceNormals = [];
  1100. faceColors = [];
  1101. faceUVs = [];
  1102. faceWeights = [];
  1103. faceWeightIndices = [];
  1104. }
  1105. } );
  1106. return buffers;
  1107. } // Generate data for a single face in a geometry. If the face is a quad then split it into 2 tris
  1108. genFace( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength ) {
  1109. for ( let i = 2; i < faceLength; i ++ ) {
  1110. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 0 ] ] );
  1111. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 1 ] ] );
  1112. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 2 ] ] );
  1113. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 ] ] );
  1114. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 1 ] ] );
  1115. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 2 ] ] );
  1116. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 ] ] );
  1117. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 1 ] ] );
  1118. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 2 ] ] );
  1119. if ( geoInfo.skeleton ) {
  1120. buffers.vertexWeights.push( faceWeights[ 0 ] );
  1121. buffers.vertexWeights.push( faceWeights[ 1 ] );
  1122. buffers.vertexWeights.push( faceWeights[ 2 ] );
  1123. buffers.vertexWeights.push( faceWeights[ 3 ] );
  1124. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 ] );
  1125. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 1 ] );
  1126. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 2 ] );
  1127. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 3 ] );
  1128. buffers.vertexWeights.push( faceWeights[ i * 4 ] );
  1129. buffers.vertexWeights.push( faceWeights[ i * 4 + 1 ] );
  1130. buffers.vertexWeights.push( faceWeights[ i * 4 + 2 ] );
  1131. buffers.vertexWeights.push( faceWeights[ i * 4 + 3 ] );
  1132. buffers.weightsIndices.push( faceWeightIndices[ 0 ] );
  1133. buffers.weightsIndices.push( faceWeightIndices[ 1 ] );
  1134. buffers.weightsIndices.push( faceWeightIndices[ 2 ] );
  1135. buffers.weightsIndices.push( faceWeightIndices[ 3 ] );
  1136. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 ] );
  1137. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 1 ] );
  1138. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 2 ] );
  1139. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 3 ] );
  1140. buffers.weightsIndices.push( faceWeightIndices[ i * 4 ] );
  1141. buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 1 ] );
  1142. buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 2 ] );
  1143. buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 3 ] );
  1144. }
  1145. if ( geoInfo.color ) {
  1146. buffers.colors.push( faceColors[ 0 ] );
  1147. buffers.colors.push( faceColors[ 1 ] );
  1148. buffers.colors.push( faceColors[ 2 ] );
  1149. buffers.colors.push( faceColors[ ( i - 1 ) * 3 ] );
  1150. buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 1 ] );
  1151. buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 2 ] );
  1152. buffers.colors.push( faceColors[ i * 3 ] );
  1153. buffers.colors.push( faceColors[ i * 3 + 1 ] );
  1154. buffers.colors.push( faceColors[ i * 3 + 2 ] );
  1155. }
  1156. if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {
  1157. buffers.materialIndex.push( materialIndex );
  1158. buffers.materialIndex.push( materialIndex );
  1159. buffers.materialIndex.push( materialIndex );
  1160. }
  1161. if ( geoInfo.normal ) {
  1162. buffers.normal.push( faceNormals[ 0 ] );
  1163. buffers.normal.push( faceNormals[ 1 ] );
  1164. buffers.normal.push( faceNormals[ 2 ] );
  1165. buffers.normal.push( faceNormals[ ( i - 1 ) * 3 ] );
  1166. buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 1 ] );
  1167. buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 2 ] );
  1168. buffers.normal.push( faceNormals[ i * 3 ] );
  1169. buffers.normal.push( faceNormals[ i * 3 + 1 ] );
  1170. buffers.normal.push( faceNormals[ i * 3 + 2 ] );
  1171. }
  1172. if ( geoInfo.uv ) {
  1173. geoInfo.uv.forEach( function ( uv, j ) {
  1174. if ( buffers.uvs[ j ] === undefined ) buffers.uvs[ j ] = [];
  1175. buffers.uvs[ j ].push( faceUVs[ j ][ 0 ] );
  1176. buffers.uvs[ j ].push( faceUVs[ j ][ 1 ] );
  1177. buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 ] );
  1178. buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 + 1 ] );
  1179. buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 ] );
  1180. buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 + 1 ] );
  1181. } );
  1182. }
  1183. }
  1184. }
  1185. addMorphTargets( parentGeo, parentGeoNode, morphTargets, preTransform ) {
  1186. if ( morphTargets.length === 0 ) return;
  1187. parentGeo.morphTargetsRelative = true;
  1188. parentGeo.morphAttributes.position = []; // parentGeo.morphAttributes.normal = []; // not implemented
  1189. const scope = this;
  1190. morphTargets.forEach( function ( morphTarget ) {
  1191. morphTarget.rawTargets.forEach( function ( rawTarget ) {
  1192. const morphGeoNode = fbxTree.Objects.Geometry[ rawTarget.geoID ];
  1193. if ( morphGeoNode !== undefined ) {
  1194. scope.genMorphGeometry( parentGeo, parentGeoNode, morphGeoNode, preTransform, rawTarget.name );
  1195. }
  1196. } );
  1197. } );
  1198. } // a morph geometry node is similar to a standard node, and the node is also contained
  1199. // in FBXTree.Objects.Geometry, however it can only have attributes for position, normal
  1200. // and a special attribute Index defining which vertices of the original geometry are affected
  1201. // Normal and position attributes only have data for the vertices that are affected by the morph
  1202. genMorphGeometry( parentGeo, parentGeoNode, morphGeoNode, preTransform, name ) {
  1203. const vertexIndices = parentGeoNode.PolygonVertexIndex !== undefined ? parentGeoNode.PolygonVertexIndex.a : [];
  1204. const morphPositionsSparse = morphGeoNode.Vertices !== undefined ? morphGeoNode.Vertices.a : [];
  1205. const indices = morphGeoNode.Indexes !== undefined ? morphGeoNode.Indexes.a : [];
  1206. const length = parentGeo.attributes.position.count * 3;
  1207. const morphPositions = new Float32Array( length );
  1208. for ( let i = 0; i < indices.length; i ++ ) {
  1209. const morphIndex = indices[ i ] * 3;
  1210. morphPositions[ morphIndex ] = morphPositionsSparse[ i * 3 ];
  1211. morphPositions[ morphIndex + 1 ] = morphPositionsSparse[ i * 3 + 1 ];
  1212. morphPositions[ morphIndex + 2 ] = morphPositionsSparse[ i * 3 + 2 ];
  1213. } // TODO: add morph normal support
  1214. const morphGeoInfo = {
  1215. vertexIndices: vertexIndices,
  1216. vertexPositions: morphPositions
  1217. };
  1218. const morphBuffers = this.genBuffers( morphGeoInfo );
  1219. const positionAttribute = new THREE.Float32BufferAttribute( morphBuffers.vertex, 3 );
  1220. positionAttribute.name = name || morphGeoNode.attrName;
  1221. positionAttribute.applyMatrix4( preTransform );
  1222. parentGeo.morphAttributes.position.push( positionAttribute );
  1223. } // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists
  1224. parseNormals( NormalNode ) {
  1225. const mappingType = NormalNode.MappingInformationType;
  1226. const referenceType = NormalNode.ReferenceInformationType;
  1227. const buffer = NormalNode.Normals.a;
  1228. let indexBuffer = [];
  1229. if ( referenceType === 'IndexToDirect' ) {
  1230. if ( 'NormalIndex' in NormalNode ) {
  1231. indexBuffer = NormalNode.NormalIndex.a;
  1232. } else if ( 'NormalsIndex' in NormalNode ) {
  1233. indexBuffer = NormalNode.NormalsIndex.a;
  1234. }
  1235. }
  1236. return {
  1237. dataSize: 3,
  1238. buffer: buffer,
  1239. indices: indexBuffer,
  1240. mappingType: mappingType,
  1241. referenceType: referenceType
  1242. };
  1243. } // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists
  1244. parseUVs( UVNode ) {
  1245. const mappingType = UVNode.MappingInformationType;
  1246. const referenceType = UVNode.ReferenceInformationType;
  1247. const buffer = UVNode.UV.a;
  1248. let indexBuffer = [];
  1249. if ( referenceType === 'IndexToDirect' ) {
  1250. indexBuffer = UVNode.UVIndex.a;
  1251. }
  1252. return {
  1253. dataSize: 2,
  1254. buffer: buffer,
  1255. indices: indexBuffer,
  1256. mappingType: mappingType,
  1257. referenceType: referenceType
  1258. };
  1259. } // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists
  1260. parseVertexColors( ColorNode ) {
  1261. const mappingType = ColorNode.MappingInformationType;
  1262. const referenceType = ColorNode.ReferenceInformationType;
  1263. const buffer = ColorNode.Colors.a;
  1264. let indexBuffer = [];
  1265. if ( referenceType === 'IndexToDirect' ) {
  1266. indexBuffer = ColorNode.ColorIndex.a;
  1267. }
  1268. return {
  1269. dataSize: 4,
  1270. buffer: buffer,
  1271. indices: indexBuffer,
  1272. mappingType: mappingType,
  1273. referenceType: referenceType
  1274. };
  1275. } // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists
  1276. parseMaterialIndices( MaterialNode ) {
  1277. const mappingType = MaterialNode.MappingInformationType;
  1278. const referenceType = MaterialNode.ReferenceInformationType;
  1279. if ( mappingType === 'NoMappingInformation' ) {
  1280. return {
  1281. dataSize: 1,
  1282. buffer: [ 0 ],
  1283. indices: [ 0 ],
  1284. mappingType: 'AllSame',
  1285. referenceType: referenceType
  1286. };
  1287. }
  1288. const materialIndexBuffer = MaterialNode.Materials.a; // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  1289. // we expect.So we create an intermediate buffer that points to the index in the buffer,
  1290. // for conforming with the other functions we've written for other data.
  1291. const materialIndices = [];
  1292. for ( let i = 0; i < materialIndexBuffer.length; ++ i ) {
  1293. materialIndices.push( i );
  1294. }
  1295. return {
  1296. dataSize: 1,
  1297. buffer: materialIndexBuffer,
  1298. indices: materialIndices,
  1299. mappingType: mappingType,
  1300. referenceType: referenceType
  1301. };
  1302. } // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry
  1303. parseNurbsGeometry( geoNode ) {
  1304. if ( THREE.NURBSCurve === undefined ) {
  1305. console.error( 'THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.' );
  1306. return new THREE.BufferGeometry();
  1307. }
  1308. const order = parseInt( geoNode.Order );
  1309. if ( isNaN( order ) ) {
  1310. console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geoNode.Order, geoNode.id );
  1311. return new THREE.BufferGeometry();
  1312. }
  1313. const degree = order - 1;
  1314. const knots = geoNode.KnotVector.a;
  1315. const controlPoints = [];
  1316. const pointsValues = geoNode.Points.a;
  1317. for ( let i = 0, l = pointsValues.length; i < l; i += 4 ) {
  1318. controlPoints.push( new THREE.Vector4().fromArray( pointsValues, i ) );
  1319. }
  1320. let startKnot, endKnot;
  1321. if ( geoNode.Form === 'Closed' ) {
  1322. controlPoints.push( controlPoints[ 0 ] );
  1323. } else if ( geoNode.Form === 'Periodic' ) {
  1324. startKnot = degree;
  1325. endKnot = knots.length - 1 - startKnot;
  1326. for ( let i = 0; i < degree; ++ i ) {
  1327. controlPoints.push( controlPoints[ i ] );
  1328. }
  1329. }
  1330. const curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
  1331. const vertices = curve.getPoints( controlPoints.length * 7 );
  1332. const positions = new Float32Array( vertices.length * 3 );
  1333. vertices.forEach( function ( vertex, i ) {
  1334. vertex.toArray( positions, i * 3 );
  1335. } );
  1336. const geometry = new THREE.BufferGeometry();
  1337. geometry.setAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  1338. return geometry;
  1339. }
  1340. } // parse animation data from FBXTree
  1341. class AnimationParser {
  1342. // take raw animation clips and turn them into three.js animation clips
  1343. parse() {
  1344. const animationClips = [];
  1345. const rawClips = this.parseClips();
  1346. if ( rawClips !== undefined ) {
  1347. for ( const key in rawClips ) {
  1348. const rawClip = rawClips[ key ];
  1349. const clip = this.addClip( rawClip );
  1350. animationClips.push( clip );
  1351. }
  1352. }
  1353. return animationClips;
  1354. }
  1355. parseClips() {
  1356. // since the actual transformation data is stored in FBXTree.Objects.AnimationCurve,
  1357. // if this is undefined we can safely assume there are no animations
  1358. if ( fbxTree.Objects.AnimationCurve === undefined ) return undefined;
  1359. const curveNodesMap = this.parseAnimationCurveNodes();
  1360. this.parseAnimationCurves( curveNodesMap );
  1361. const layersMap = this.parseAnimationLayers( curveNodesMap );
  1362. const rawClips = this.parseAnimStacks( layersMap );
  1363. return rawClips;
  1364. } // parse nodes in FBXTree.Objects.AnimationCurveNode
  1365. // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation )
  1366. // and is referenced by an AnimationLayer
  1367. parseAnimationCurveNodes() {
  1368. const rawCurveNodes = fbxTree.Objects.AnimationCurveNode;
  1369. const curveNodesMap = new Map();
  1370. for ( const nodeID in rawCurveNodes ) {
  1371. const rawCurveNode = rawCurveNodes[ nodeID ];
  1372. if ( rawCurveNode.attrName.match( /S|R|T|DeformPercent/ ) !== null ) {
  1373. const curveNode = {
  1374. id: rawCurveNode.id,
  1375. attr: rawCurveNode.attrName,
  1376. curves: {}
  1377. };
  1378. curveNodesMap.set( curveNode.id, curveNode );
  1379. }
  1380. }
  1381. return curveNodesMap;
  1382. } // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to
  1383. // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated
  1384. // axis ( e.g. times and values of x rotation)
  1385. parseAnimationCurves( curveNodesMap ) {
  1386. const rawCurves = fbxTree.Objects.AnimationCurve; // TODO: Many values are identical up to roundoff error, but won't be optimised
  1387. // e.g. position times: [0, 0.4, 0. 8]
  1388. // position values: [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.235384487103147e-7, 93.67520904541016, -0.9982695579528809]
  1389. // clearly, this should be optimised to
  1390. // times: [0], positions [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809]
  1391. // this shows up in nearly every FBX file, and generally time array is length > 100
  1392. for ( const nodeID in rawCurves ) {
  1393. const animationCurve = {
  1394. id: rawCurves[ nodeID ].id,
  1395. times: rawCurves[ nodeID ].KeyTime.a.map( convertFBXTimeToSeconds ),
  1396. values: rawCurves[ nodeID ].KeyValueFloat.a
  1397. };
  1398. const relationships = connections.get( animationCurve.id );
  1399. if ( relationships !== undefined ) {
  1400. const animationCurveID = relationships.parents[ 0 ].ID;
  1401. const animationCurveRelationship = relationships.parents[ 0 ].relationship;
  1402. if ( animationCurveRelationship.match( /X/ ) ) {
  1403. curveNodesMap.get( animationCurveID ).curves[ 'x' ] = animationCurve;
  1404. } else if ( animationCurveRelationship.match( /Y/ ) ) {
  1405. curveNodesMap.get( animationCurveID ).curves[ 'y' ] = animationCurve;
  1406. } else if ( animationCurveRelationship.match( /Z/ ) ) {
  1407. curveNodesMap.get( animationCurveID ).curves[ 'z' ] = animationCurve;
  1408. } else if ( animationCurveRelationship.match( /d|DeformPercent/ ) && curveNodesMap.has( animationCurveID ) ) {
  1409. curveNodesMap.get( animationCurveID ).curves[ 'morph' ] = animationCurve;
  1410. }
  1411. }
  1412. }
  1413. } // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references
  1414. // to various AnimationCurveNodes and is referenced by an AnimationStack node
  1415. // note: theoretically a stack can have multiple layers, however in practice there always seems to be one per stack
  1416. parseAnimationLayers( curveNodesMap ) {
  1417. const rawLayers = fbxTree.Objects.AnimationLayer;
  1418. const layersMap = new Map();
  1419. for ( const nodeID in rawLayers ) {
  1420. const layerCurveNodes = [];
  1421. const connection = connections.get( parseInt( nodeID ) );
  1422. if ( connection !== undefined ) {
  1423. // all the animationCurveNodes used in the layer
  1424. const children = connection.children;
  1425. children.forEach( function ( child, i ) {
  1426. if ( curveNodesMap.has( child.ID ) ) {
  1427. const curveNode = curveNodesMap.get( child.ID ); // check that the curves are defined for at least one axis, otherwise ignore the curveNode
  1428. if ( curveNode.curves.x !== undefined || curveNode.curves.y !== undefined || curveNode.curves.z !== undefined ) {
  1429. if ( layerCurveNodes[ i ] === undefined ) {
  1430. const modelID = connections.get( child.ID ).parents.filter( function ( parent ) {
  1431. return parent.relationship !== undefined;
  1432. } )[ 0 ].ID;
  1433. if ( modelID !== undefined ) {
  1434. const rawModel = fbxTree.Objects.Model[ modelID.toString() ];
  1435. if ( rawModel === undefined ) {
  1436. console.warn( 'THREE.FBXLoader: Encountered a unused curve.', child );
  1437. return;
  1438. }
  1439. const node = {
  1440. modelName: rawModel.attrName ? THREE.PropertyBinding.sanitizeNodeName( rawModel.attrName ) : '',
  1441. ID: rawModel.id,
  1442. initialPosition: [ 0, 0, 0 ],
  1443. initialRotation: [ 0, 0, 0 ],
  1444. initialScale: [ 1, 1, 1 ]
  1445. };
  1446. sceneGraph.traverse( function ( child ) {
  1447. if ( child.ID === rawModel.id ) {
  1448. node.transform = child.matrix;
  1449. if ( child.userData.transformData ) node.eulerOrder = child.userData.transformData.eulerOrder;
  1450. }
  1451. } );
  1452. if ( ! node.transform ) node.transform = new THREE.Matrix4(); // if the animated model is pre rotated, we'll have to apply the pre rotations to every
  1453. // animation value as well
  1454. if ( 'PreRotation' in rawModel ) node.preRotation = rawModel.PreRotation.value;
  1455. if ( 'PostRotation' in rawModel ) node.postRotation = rawModel.PostRotation.value;
  1456. layerCurveNodes[ i ] = node;
  1457. }
  1458. }
  1459. if ( layerCurveNodes[ i ] ) layerCurveNodes[ i ][ curveNode.attr ] = curveNode;
  1460. } else if ( curveNode.curves.morph !== undefined ) {
  1461. if ( layerCurveNodes[ i ] === undefined ) {
  1462. const deformerID = connections.get( child.ID ).parents.filter( function ( parent ) {
  1463. return parent.relationship !== undefined;
  1464. } )[ 0 ].ID;
  1465. const morpherID = connections.get( deformerID ).parents[ 0 ].ID;
  1466. const geoID = connections.get( morpherID ).parents[ 0 ].ID; // assuming geometry is not used in more than one model
  1467. const modelID = connections.get( geoID ).parents[ 0 ].ID;
  1468. const rawModel = fbxTree.Objects.Model[ modelID ];
  1469. const node = {
  1470. modelName: rawModel.attrName ? THREE.PropertyBinding.sanitizeNodeName( rawModel.attrName ) : '',
  1471. morphName: fbxTree.Objects.Deformer[ deformerID ].attrName
  1472. };
  1473. layerCurveNodes[ i ] = node;
  1474. }
  1475. layerCurveNodes[ i ][ curveNode.attr ] = curveNode;
  1476. }
  1477. }
  1478. } );
  1479. layersMap.set( parseInt( nodeID ), layerCurveNodes );
  1480. }
  1481. }
  1482. return layersMap;
  1483. } // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation
  1484. // hierarchy. Each Stack node will be used to create a THREE.AnimationClip
  1485. parseAnimStacks( layersMap ) {
  1486. const rawStacks = fbxTree.Objects.AnimationStack; // connect the stacks (clips) up to the layers
  1487. const rawClips = {};
  1488. for ( const nodeID in rawStacks ) {
  1489. const children = connections.get( parseInt( nodeID ) ).children;
  1490. if ( children.length > 1 ) {
  1491. // it seems like stacks will always be associated with a single layer. But just in case there are files
  1492. // where there are multiple layers per stack, we'll display a warning
  1493. console.warn( 'THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.' );
  1494. }
  1495. const layer = layersMap.get( children[ 0 ].ID );
  1496. rawClips[ nodeID ] = {
  1497. name: rawStacks[ nodeID ].attrName,
  1498. layer: layer
  1499. };
  1500. }
  1501. return rawClips;
  1502. }
  1503. addClip( rawClip ) {
  1504. let tracks = [];
  1505. const scope = this;
  1506. rawClip.layer.forEach( function ( rawTracks ) {
  1507. tracks = tracks.concat( scope.generateTracks( rawTracks ) );
  1508. } );
  1509. return new THREE.AnimationClip( rawClip.name, - 1, tracks );
  1510. }
  1511. generateTracks( rawTracks ) {
  1512. const tracks = [];
  1513. let initialPosition = new THREE.Vector3();
  1514. let initialRotation = new THREE.Quaternion();
  1515. let initialScale = new THREE.Vector3();
  1516. if ( rawTracks.transform ) rawTracks.transform.decompose( initialPosition, initialRotation, initialScale );
  1517. initialPosition = initialPosition.toArray();
  1518. initialRotation = new THREE.Euler().setFromQuaternion( initialRotation, rawTracks.eulerOrder ).toArray();
  1519. initialScale = initialScale.toArray();
  1520. if ( rawTracks.T !== undefined && Object.keys( rawTracks.T.curves ).length > 0 ) {
  1521. const positionTrack = this.generateVectorTrack( rawTracks.modelName, rawTracks.T.curves, initialPosition, 'position' );
  1522. if ( positionTrack !== undefined ) tracks.push( positionTrack );
  1523. }
  1524. if ( rawTracks.R !== undefined && Object.keys( rawTracks.R.curves ).length > 0 ) {
  1525. const rotationTrack = this.generateRotationTrack( rawTracks.modelName, rawTracks.R.curves, initialRotation, rawTracks.preRotation, rawTracks.postRotation, rawTracks.eulerOrder );
  1526. if ( rotationTrack !== undefined ) tracks.push( rotationTrack );
  1527. }
  1528. if ( rawTracks.S !== undefined && Object.keys( rawTracks.S.curves ).length > 0 ) {
  1529. const scaleTrack = this.generateVectorTrack( rawTracks.modelName, rawTracks.S.curves, initialScale, 'scale' );
  1530. if ( scaleTrack !== undefined ) tracks.push( scaleTrack );
  1531. }
  1532. if ( rawTracks.DeformPercent !== undefined ) {
  1533. const morphTrack = this.generateMorphTrack( rawTracks );
  1534. if ( morphTrack !== undefined ) tracks.push( morphTrack );
  1535. }
  1536. return tracks;
  1537. }
  1538. generateVectorTrack( modelName, curves, initialValue, type ) {
  1539. const times = this.getTimesForAllAxes( curves );
  1540. const values = this.getKeyframeTrackValues( times, curves, initialValue );
  1541. return new THREE.VectorKeyframeTrack( modelName + '.' + type, times, values );
  1542. }
  1543. generateRotationTrack( modelName, curves, initialValue, preRotation, postRotation, eulerOrder ) {
  1544. if ( curves.x !== undefined ) {
  1545. this.interpolateRotations( curves.x );
  1546. curves.x.values = curves.x.values.map( THREE.MathUtils.degToRad );
  1547. }
  1548. if ( curves.y !== undefined ) {
  1549. this.interpolateRotations( curves.y );
  1550. curves.y.values = curves.y.values.map( THREE.MathUtils.degToRad );
  1551. }
  1552. if ( curves.z !== undefined ) {
  1553. this.interpolateRotations( curves.z );
  1554. curves.z.values = curves.z.values.map( THREE.MathUtils.degToRad );
  1555. }
  1556. const times = this.getTimesForAllAxes( curves );
  1557. const values = this.getKeyframeTrackValues( times, curves, initialValue );
  1558. if ( preRotation !== undefined ) {
  1559. preRotation = preRotation.map( THREE.MathUtils.degToRad );
  1560. preRotation.push( eulerOrder );
  1561. preRotation = new THREE.Euler().fromArray( preRotation );
  1562. preRotation = new THREE.Quaternion().setFromEuler( preRotation );
  1563. }
  1564. if ( postRotation !== undefined ) {
  1565. postRotation = postRotation.map( THREE.MathUtils.degToRad );
  1566. postRotation.push( eulerOrder );
  1567. postRotation = new THREE.Euler().fromArray( postRotation );
  1568. postRotation = new THREE.Quaternion().setFromEuler( postRotation ).invert();
  1569. }
  1570. const quaternion = new THREE.Quaternion();
  1571. const euler = new THREE.Euler();
  1572. const quaternionValues = [];
  1573. for ( let i = 0; i < values.length; i += 3 ) {
  1574. euler.set( values[ i ], values[ i + 1 ], values[ i + 2 ], eulerOrder );
  1575. quaternion.setFromEuler( euler );
  1576. if ( preRotation !== undefined ) quaternion.premultiply( preRotation );
  1577. if ( postRotation !== undefined ) quaternion.multiply( postRotation );
  1578. quaternion.toArray( quaternionValues, i / 3 * 4 );
  1579. }
  1580. return new THREE.QuaternionKeyframeTrack( modelName + '.quaternion', times, quaternionValues );
  1581. }
  1582. generateMorphTrack( rawTracks ) {
  1583. const curves = rawTracks.DeformPercent.curves.morph;
  1584. const values = curves.values.map( function ( val ) {
  1585. return val / 100;
  1586. } );
  1587. const morphNum = sceneGraph.getObjectByName( rawTracks.modelName ).morphTargetDictionary[ rawTracks.morphName ];
  1588. return new THREE.NumberKeyframeTrack( rawTracks.modelName + '.morphTargetInfluences[' + morphNum + ']', curves.times, values );
  1589. } // For all animated objects, times are defined separately for each axis
  1590. // Here we'll combine the times into one sorted array without duplicates
  1591. getTimesForAllAxes( curves ) {
  1592. let times = []; // first join together the times for each axis, if defined
  1593. if ( curves.x !== undefined ) times = times.concat( curves.x.times );
  1594. if ( curves.y !== undefined ) times = times.concat( curves.y.times );
  1595. if ( curves.z !== undefined ) times = times.concat( curves.z.times ); // then sort them
  1596. times = times.sort( function ( a, b ) {
  1597. return a - b;
  1598. } ); // and remove duplicates
  1599. if ( times.length > 1 ) {
  1600. let targetIndex = 1;
  1601. let lastValue = times[ 0 ];
  1602. for ( let i = 1; i < times.length; i ++ ) {
  1603. const currentValue = times[ i ];
  1604. if ( currentValue !== lastValue ) {
  1605. times[ targetIndex ] = currentValue;
  1606. lastValue = currentValue;
  1607. targetIndex ++;
  1608. }
  1609. }
  1610. times = times.slice( 0, targetIndex );
  1611. }
  1612. return times;
  1613. }
  1614. getKeyframeTrackValues( times, curves, initialValue ) {
  1615. const prevValue = initialValue;
  1616. const values = [];
  1617. let xIndex = - 1;
  1618. let yIndex = - 1;
  1619. let zIndex = - 1;
  1620. times.forEach( function ( time ) {
  1621. if ( curves.x ) xIndex = curves.x.times.indexOf( time );
  1622. if ( curves.y ) yIndex = curves.y.times.indexOf( time );
  1623. if ( curves.z ) zIndex = curves.z.times.indexOf( time ); // if there is an x value defined for this frame, use that
  1624. if ( xIndex !== - 1 ) {
  1625. const xValue = curves.x.values[ xIndex ];
  1626. values.push( xValue );
  1627. prevValue[ 0 ] = xValue;
  1628. } else {
  1629. // otherwise use the x value from the previous frame
  1630. values.push( prevValue[ 0 ] );
  1631. }
  1632. if ( yIndex !== - 1 ) {
  1633. const yValue = curves.y.values[ yIndex ];
  1634. values.push( yValue );
  1635. prevValue[ 1 ] = yValue;
  1636. } else {
  1637. values.push( prevValue[ 1 ] );
  1638. }
  1639. if ( zIndex !== - 1 ) {
  1640. const zValue = curves.z.values[ zIndex ];
  1641. values.push( zValue );
  1642. prevValue[ 2 ] = zValue;
  1643. } else {
  1644. values.push( prevValue[ 2 ] );
  1645. }
  1646. } );
  1647. return values;
  1648. } // Rotations are defined as THREE.Euler angles which can have values of any size
  1649. // These will be converted to quaternions which don't support values greater than
  1650. // PI, so we'll interpolate large rotations
  1651. interpolateRotations( curve ) {
  1652. for ( let i = 1; i < curve.values.length; i ++ ) {
  1653. const initialValue = curve.values[ i - 1 ];
  1654. const valuesSpan = curve.values[ i ] - initialValue;
  1655. const absoluteSpan = Math.abs( valuesSpan );
  1656. if ( absoluteSpan >= 180 ) {
  1657. const numSubIntervals = absoluteSpan / 180;
  1658. const step = valuesSpan / numSubIntervals;
  1659. let nextValue = initialValue + step;
  1660. const initialTime = curve.times[ i - 1 ];
  1661. const timeSpan = curve.times[ i ] - initialTime;
  1662. const interval = timeSpan / numSubIntervals;
  1663. let nextTime = initialTime + interval;
  1664. const interpolatedTimes = [];
  1665. const interpolatedValues = [];
  1666. while ( nextTime < curve.times[ i ] ) {
  1667. interpolatedTimes.push( nextTime );
  1668. nextTime += interval;
  1669. interpolatedValues.push( nextValue );
  1670. nextValue += step;
  1671. }
  1672. curve.times = inject( curve.times, i, interpolatedTimes );
  1673. curve.values = inject( curve.values, i, interpolatedValues );
  1674. }
  1675. }
  1676. }
  1677. } // parse an FBX file in ASCII format
  1678. class TextParser {
  1679. getPrevNode() {
  1680. return this.nodeStack[ this.currentIndent - 2 ];
  1681. }
  1682. getCurrentNode() {
  1683. return this.nodeStack[ this.currentIndent - 1 ];
  1684. }
  1685. getCurrentProp() {
  1686. return this.currentProp;
  1687. }
  1688. pushStack( node ) {
  1689. this.nodeStack.push( node );
  1690. this.currentIndent += 1;
  1691. }
  1692. popStack() {
  1693. this.nodeStack.pop();
  1694. this.currentIndent -= 1;
  1695. }
  1696. setCurrentProp( val, name ) {
  1697. this.currentProp = val;
  1698. this.currentPropName = name;
  1699. }
  1700. parse( text ) {
  1701. this.currentIndent = 0;
  1702. this.allNodes = new FBXTree();
  1703. this.nodeStack = [];
  1704. this.currentProp = [];
  1705. this.currentPropName = '';
  1706. const scope = this;
  1707. const split = text.split( /[\r\n]+/ );
  1708. split.forEach( function ( line, i ) {
  1709. const matchComment = line.match( /^[\s\t]*;/ );
  1710. const matchEmpty = line.match( /^[\s\t]*$/ );
  1711. if ( matchComment || matchEmpty ) return;
  1712. const matchBeginning = line.match( '^\\t{' + scope.currentIndent + '}(\\w+):(.*){', '' );
  1713. const matchProperty = line.match( '^\\t{' + scope.currentIndent + '}(\\w+):[\\s\\t\\r\\n](.*)' );
  1714. const matchEnd = line.match( '^\\t{' + ( scope.currentIndent - 1 ) + '}}' );
  1715. if ( matchBeginning ) {
  1716. scope.parseNodeBegin( line, matchBeginning );
  1717. } else if ( matchProperty ) {
  1718. scope.parseNodeProperty( line, matchProperty, split[ ++ i ] );
  1719. } else if ( matchEnd ) {
  1720. scope.popStack();
  1721. } else if ( line.match( /^[^\s\t}]/ ) ) {
  1722. // large arrays are split over multiple lines terminated with a ',' character
  1723. // if this is encountered the line needs to be joined to the previous line
  1724. scope.parseNodePropertyContinued( line );
  1725. }
  1726. } );
  1727. return this.allNodes;
  1728. }
  1729. parseNodeBegin( line, property ) {
  1730. const nodeName = property[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  1731. const nodeAttrs = property[ 2 ].split( ',' ).map( function ( attr ) {
  1732. return attr.trim().replace( /^"/, '' ).replace( /"$/, '' );
  1733. } );
  1734. const node = {
  1735. name: nodeName
  1736. };
  1737. const attrs = this.parseNodeAttr( nodeAttrs );
  1738. const currentNode = this.getCurrentNode(); // a top node
  1739. if ( this.currentIndent === 0 ) {
  1740. this.allNodes.add( nodeName, node );
  1741. } else {
  1742. // a subnode
  1743. // if the subnode already exists, append it
  1744. if ( nodeName in currentNode ) {
  1745. // special case Pose needs PoseNodes as an array
  1746. if ( nodeName === 'PoseNode' ) {
  1747. currentNode.PoseNode.push( node );
  1748. } else if ( currentNode[ nodeName ].id !== undefined ) {
  1749. currentNode[ nodeName ] = {};
  1750. currentNode[ nodeName ][ currentNode[ nodeName ].id ] = currentNode[ nodeName ];
  1751. }
  1752. if ( attrs.id !== '' ) currentNode[ nodeName ][ attrs.id ] = node;
  1753. } else if ( typeof attrs.id === 'number' ) {
  1754. currentNode[ nodeName ] = {};
  1755. currentNode[ nodeName ][ attrs.id ] = node;
  1756. } else if ( nodeName !== 'Properties70' ) {
  1757. if ( nodeName === 'PoseNode' ) currentNode[ nodeName ] = [ node ]; else currentNode[ nodeName ] = node;
  1758. }
  1759. }
  1760. if ( typeof attrs.id === 'number' ) node.id = attrs.id;
  1761. if ( attrs.name !== '' ) node.attrName = attrs.name;
  1762. if ( attrs.type !== '' ) node.attrType = attrs.type;
  1763. this.pushStack( node );
  1764. }
  1765. parseNodeAttr( attrs ) {
  1766. let id = attrs[ 0 ];
  1767. if ( attrs[ 0 ] !== '' ) {
  1768. id = parseInt( attrs[ 0 ] );
  1769. if ( isNaN( id ) ) {
  1770. id = attrs[ 0 ];
  1771. }
  1772. }
  1773. let name = '',
  1774. type = '';
  1775. if ( attrs.length > 1 ) {
  1776. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  1777. type = attrs[ 2 ];
  1778. }
  1779. return {
  1780. id: id,
  1781. name: name,
  1782. type: type
  1783. };
  1784. }
  1785. parseNodeProperty( line, property, contentLine ) {
  1786. let propName = property[ 1 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  1787. let propValue = property[ 2 ].replace( /^"/, '' ).replace( /"$/, '' ).trim(); // for special case: base64 image data follows "Content: ," line
  1788. // Content: ,
  1789. // "/9j/4RDaRXhpZgAATU0A..."
  1790. if ( propName === 'Content' && propValue === ',' ) {
  1791. propValue = contentLine.replace( /"/g, '' ).replace( /,$/, '' ).trim();
  1792. }
  1793. const currentNode = this.getCurrentNode();
  1794. const parentName = currentNode.name;
  1795. if ( parentName === 'Properties70' ) {
  1796. this.parseNodeSpecialProperty( line, propName, propValue );
  1797. return;
  1798. } // Connections
  1799. if ( propName === 'C' ) {
  1800. const connProps = propValue.split( ',' ).slice( 1 );
  1801. const from = parseInt( connProps[ 0 ] );
  1802. const to = parseInt( connProps[ 1 ] );
  1803. let rest = propValue.split( ',' ).slice( 3 );
  1804. rest = rest.map( function ( elem ) {
  1805. return elem.trim().replace( /^"/, '' );
  1806. } );
  1807. propName = 'connections';
  1808. propValue = [ from, to ];
  1809. append( propValue, rest );
  1810. if ( currentNode[ propName ] === undefined ) {
  1811. currentNode[ propName ] = [];
  1812. }
  1813. } // Node
  1814. if ( propName === 'Node' ) currentNode.id = propValue; // connections
  1815. if ( propName in currentNode && Array.isArray( currentNode[ propName ] ) ) {
  1816. currentNode[ propName ].push( propValue );
  1817. } else {
  1818. if ( propName !== 'a' ) currentNode[ propName ] = propValue; else currentNode.a = propValue;
  1819. }
  1820. this.setCurrentProp( currentNode, propName ); // convert string to array, unless it ends in ',' in which case more will be added to it
  1821. if ( propName === 'a' && propValue.slice( - 1 ) !== ',' ) {
  1822. currentNode.a = parseNumberArray( propValue );
  1823. }
  1824. }
  1825. parseNodePropertyContinued( line ) {
  1826. const currentNode = this.getCurrentNode();
  1827. currentNode.a += line; // if the line doesn't end in ',' we have reached the end of the property value
  1828. // so convert the string to an array
  1829. if ( line.slice( - 1 ) !== ',' ) {
  1830. currentNode.a = parseNumberArray( currentNode.a );
  1831. }
  1832. } // parse "Property70"
  1833. parseNodeSpecialProperty( line, propName, propValue ) {
  1834. // split this
  1835. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  1836. // into array like below
  1837. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  1838. const props = propValue.split( '",' ).map( function ( prop ) {
  1839. return prop.trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  1840. } );
  1841. const innerPropName = props[ 0 ];
  1842. const innerPropType1 = props[ 1 ];
  1843. const innerPropType2 = props[ 2 ];
  1844. const innerPropFlag = props[ 3 ];
  1845. let innerPropValue = props[ 4 ]; // cast values where needed, otherwise leave as strings
  1846. switch ( innerPropType1 ) {
  1847. case 'int':
  1848. case 'enum':
  1849. case 'bool':
  1850. case 'ULongLong':
  1851. case 'double':
  1852. case 'Number':
  1853. case 'FieldOfView':
  1854. innerPropValue = parseFloat( innerPropValue );
  1855. break;
  1856. case 'Color':
  1857. case 'ColorRGB':
  1858. case 'Vector3D':
  1859. case 'Lcl_Translation':
  1860. case 'Lcl_Rotation':
  1861. case 'Lcl_Scaling':
  1862. innerPropValue = parseNumberArray( innerPropValue );
  1863. break;
  1864. } // CAUTION: these props must append to parent's parent
  1865. this.getPrevNode()[ innerPropName ] = {
  1866. 'type': innerPropType1,
  1867. 'type2': innerPropType2,
  1868. 'flag': innerPropFlag,
  1869. 'value': innerPropValue
  1870. };
  1871. this.setCurrentProp( this.getPrevNode(), innerPropName );
  1872. }
  1873. } // Parse an FBX file in Binary format
  1874. class BinaryParser {
  1875. parse( buffer ) {
  1876. const reader = new BinaryReader( buffer );
  1877. reader.skip( 23 ); // skip magic 23 bytes
  1878. const version = reader.getUint32();
  1879. if ( version < 6400 ) {
  1880. throw new Error( 'THREE.FBXLoader: FBX version not supported, FileVersion: ' + version );
  1881. }
  1882. const allNodes = new FBXTree();
  1883. while ( ! this.endOfContent( reader ) ) {
  1884. const node = this.parseNode( reader, version );
  1885. if ( node !== null ) allNodes.add( node.name, node );
  1886. }
  1887. return allNodes;
  1888. } // Check if reader has reached the end of content.
  1889. endOfContent( reader ) {
  1890. // footer size: 160bytes + 16-byte alignment padding
  1891. // - 16bytes: magic
  1892. // - padding til 16-byte alignment (at least 1byte?)
  1893. // (seems like some exporters embed fixed 15 or 16bytes?)
  1894. // - 4bytes: magic
  1895. // - 4bytes: version
  1896. // - 120bytes: zero
  1897. // - 16bytes: magic
  1898. if ( reader.size() % 16 === 0 ) {
  1899. return ( reader.getOffset() + 160 + 16 & ~ 0xf ) >= reader.size();
  1900. } else {
  1901. return reader.getOffset() + 160 + 16 >= reader.size();
  1902. }
  1903. } // recursively parse nodes until the end of the file is reached
  1904. parseNode( reader, version ) {
  1905. const node = {}; // The first three data sizes depends on version.
  1906. const endOffset = version >= 7500 ? reader.getUint64() : reader.getUint32();
  1907. const numProperties = version >= 7500 ? reader.getUint64() : reader.getUint32();
  1908. version >= 7500 ? reader.getUint64() : reader.getUint32(); // the returned propertyListLen is not used
  1909. const nameLen = reader.getUint8();
  1910. const name = reader.getString( nameLen ); // Regards this node as NULL-record if endOffset is zero
  1911. if ( endOffset === 0 ) return null;
  1912. const propertyList = [];
  1913. for ( let i = 0; i < numProperties; i ++ ) {
  1914. propertyList.push( this.parseProperty( reader ) );
  1915. } // Regards the first three elements in propertyList as id, attrName, and attrType
  1916. const id = propertyList.length > 0 ? propertyList[ 0 ] : '';
  1917. const attrName = propertyList.length > 1 ? propertyList[ 1 ] : '';
  1918. const attrType = propertyList.length > 2 ? propertyList[ 2 ] : ''; // check if this node represents just a single property
  1919. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  1920. node.singleProperty = numProperties === 1 && reader.getOffset() === endOffset ? true : false;
  1921. while ( endOffset > reader.getOffset() ) {
  1922. const subNode = this.parseNode( reader, version );
  1923. if ( subNode !== null ) this.parseSubNode( name, node, subNode );
  1924. }
  1925. node.propertyList = propertyList; // raw property list used by parent
  1926. if ( typeof id === 'number' ) node.id = id;
  1927. if ( attrName !== '' ) node.attrName = attrName;
  1928. if ( attrType !== '' ) node.attrType = attrType;
  1929. if ( name !== '' ) node.name = name;
  1930. return node;
  1931. }
  1932. parseSubNode( name, node, subNode ) {
  1933. // special case: child node is single property
  1934. if ( subNode.singleProperty === true ) {
  1935. const value = subNode.propertyList[ 0 ];
  1936. if ( Array.isArray( value ) ) {
  1937. node[ subNode.name ] = subNode;
  1938. subNode.a = value;
  1939. } else {
  1940. node[ subNode.name ] = value;
  1941. }
  1942. } else if ( name === 'Connections' && subNode.name === 'C' ) {
  1943. const array = [];
  1944. subNode.propertyList.forEach( function ( property, i ) {
  1945. // first Connection is FBX type (OO, OP, etc.). We'll discard these
  1946. if ( i !== 0 ) array.push( property );
  1947. } );
  1948. if ( node.connections === undefined ) {
  1949. node.connections = [];
  1950. }
  1951. node.connections.push( array );
  1952. } else if ( subNode.name === 'Properties70' ) {
  1953. const keys = Object.keys( subNode );
  1954. keys.forEach( function ( key ) {
  1955. node[ key ] = subNode[ key ];
  1956. } );
  1957. } else if ( name === 'Properties70' && subNode.name === 'P' ) {
  1958. let innerPropName = subNode.propertyList[ 0 ];
  1959. let innerPropType1 = subNode.propertyList[ 1 ];
  1960. const innerPropType2 = subNode.propertyList[ 2 ];
  1961. const innerPropFlag = subNode.propertyList[ 3 ];
  1962. let innerPropValue;
  1963. if ( innerPropName.indexOf( 'Lcl ' ) === 0 ) innerPropName = innerPropName.replace( 'Lcl ', 'Lcl_' );
  1964. if ( innerPropType1.indexOf( 'Lcl ' ) === 0 ) innerPropType1 = innerPropType1.replace( 'Lcl ', 'Lcl_' );
  1965. if ( innerPropType1 === 'Color' || innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' || innerPropType1 === 'Vector3D' || innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  1966. innerPropValue = [ subNode.propertyList[ 4 ], subNode.propertyList[ 5 ], subNode.propertyList[ 6 ] ];
  1967. } else {
  1968. innerPropValue = subNode.propertyList[ 4 ];
  1969. } // this will be copied to parent, see above
  1970. node[ innerPropName ] = {
  1971. 'type': innerPropType1,
  1972. 'type2': innerPropType2,
  1973. 'flag': innerPropFlag,
  1974. 'value': innerPropValue
  1975. };
  1976. } else if ( node[ subNode.name ] === undefined ) {
  1977. if ( typeof subNode.id === 'number' ) {
  1978. node[ subNode.name ] = {};
  1979. node[ subNode.name ][ subNode.id ] = subNode;
  1980. } else {
  1981. node[ subNode.name ] = subNode;
  1982. }
  1983. } else {
  1984. if ( subNode.name === 'PoseNode' ) {
  1985. if ( ! Array.isArray( node[ subNode.name ] ) ) {
  1986. node[ subNode.name ] = [ node[ subNode.name ] ];
  1987. }
  1988. node[ subNode.name ].push( subNode );
  1989. } else if ( node[ subNode.name ][ subNode.id ] === undefined ) {
  1990. node[ subNode.name ][ subNode.id ] = subNode;
  1991. }
  1992. }
  1993. }
  1994. parseProperty( reader ) {
  1995. const type = reader.getString( 1 );
  1996. let length;
  1997. switch ( type ) {
  1998. case 'C':
  1999. return reader.getBoolean();
  2000. case 'D':
  2001. return reader.getFloat64();
  2002. case 'F':
  2003. return reader.getFloat32();
  2004. case 'I':
  2005. return reader.getInt32();
  2006. case 'L':
  2007. return reader.getInt64();
  2008. case 'R':
  2009. length = reader.getUint32();
  2010. return reader.getArrayBuffer( length );
  2011. case 'S':
  2012. length = reader.getUint32();
  2013. return reader.getString( length );
  2014. case 'Y':
  2015. return reader.getInt16();
  2016. case 'b':
  2017. case 'c':
  2018. case 'd':
  2019. case 'f':
  2020. case 'i':
  2021. case 'l':
  2022. const arrayLength = reader.getUint32();
  2023. const encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  2024. const compressedLength = reader.getUint32();
  2025. if ( encoding === 0 ) {
  2026. switch ( type ) {
  2027. case 'b':
  2028. case 'c':
  2029. return reader.getBooleanArray( arrayLength );
  2030. case 'd':
  2031. return reader.getFloat64Array( arrayLength );
  2032. case 'f':
  2033. return reader.getFloat32Array( arrayLength );
  2034. case 'i':
  2035. return reader.getInt32Array( arrayLength );
  2036. case 'l':
  2037. return reader.getInt64Array( arrayLength );
  2038. }
  2039. }
  2040. if ( typeof fflate === 'undefined' ) {
  2041. console.error( 'THREE.FBXLoader: External library fflate.min.js required.' );
  2042. }
  2043. const data = fflate.unzlibSync( new Uint8Array( reader.getArrayBuffer( compressedLength ) ) ); // eslint-disable-line no-undef
  2044. const reader2 = new BinaryReader( data.buffer );
  2045. switch ( type ) {
  2046. case 'b':
  2047. case 'c':
  2048. return reader2.getBooleanArray( arrayLength );
  2049. case 'd':
  2050. return reader2.getFloat64Array( arrayLength );
  2051. case 'f':
  2052. return reader2.getFloat32Array( arrayLength );
  2053. case 'i':
  2054. return reader2.getInt32Array( arrayLength );
  2055. case 'l':
  2056. return reader2.getInt64Array( arrayLength );
  2057. }
  2058. default:
  2059. throw new Error( 'THREE.FBXLoader: Unknown property type ' + type );
  2060. }
  2061. }
  2062. }
  2063. class BinaryReader {
  2064. constructor( buffer, littleEndian ) {
  2065. this.dv = new DataView( buffer );
  2066. this.offset = 0;
  2067. this.littleEndian = littleEndian !== undefined ? littleEndian : true;
  2068. }
  2069. getOffset() {
  2070. return this.offset;
  2071. }
  2072. size() {
  2073. return this.dv.buffer.byteLength;
  2074. }
  2075. skip( length ) {
  2076. this.offset += length;
  2077. } // seems like true/false representation depends on exporter.
  2078. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  2079. // then sees LSB.
  2080. getBoolean() {
  2081. return ( this.getUint8() & 1 ) === 1;
  2082. }
  2083. getBooleanArray( size ) {
  2084. const a = [];
  2085. for ( let i = 0; i < size; i ++ ) {
  2086. a.push( this.getBoolean() );
  2087. }
  2088. return a;
  2089. }
  2090. getUint8() {
  2091. const value = this.dv.getUint8( this.offset );
  2092. this.offset += 1;
  2093. return value;
  2094. }
  2095. getInt16() {
  2096. const value = this.dv.getInt16( this.offset, this.littleEndian );
  2097. this.offset += 2;
  2098. return value;
  2099. }
  2100. getInt32() {
  2101. const value = this.dv.getInt32( this.offset, this.littleEndian );
  2102. this.offset += 4;
  2103. return value;
  2104. }
  2105. getInt32Array( size ) {
  2106. const a = [];
  2107. for ( let i = 0; i < size; i ++ ) {
  2108. a.push( this.getInt32() );
  2109. }
  2110. return a;
  2111. }
  2112. getUint32() {
  2113. const value = this.dv.getUint32( this.offset, this.littleEndian );
  2114. this.offset += 4;
  2115. return value;
  2116. } // JavaScript doesn't support 64-bit integer so calculate this here
  2117. // 1 << 32 will return 1 so using multiply operation instead here.
  2118. // There's a possibility that this method returns wrong value if the value
  2119. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  2120. // TODO: safely handle 64-bit integer
  2121. getInt64() {
  2122. let low, high;
  2123. if ( this.littleEndian ) {
  2124. low = this.getUint32();
  2125. high = this.getUint32();
  2126. } else {
  2127. high = this.getUint32();
  2128. low = this.getUint32();
  2129. } // calculate negative value
  2130. if ( high & 0x80000000 ) {
  2131. high = ~ high & 0xFFFFFFFF;
  2132. low = ~ low & 0xFFFFFFFF;
  2133. if ( low === 0xFFFFFFFF ) high = high + 1 & 0xFFFFFFFF;
  2134. low = low + 1 & 0xFFFFFFFF;
  2135. return - ( high * 0x100000000 + low );
  2136. }
  2137. return high * 0x100000000 + low;
  2138. }
  2139. getInt64Array( size ) {
  2140. const a = [];
  2141. for ( let i = 0; i < size; i ++ ) {
  2142. a.push( this.getInt64() );
  2143. }
  2144. return a;
  2145. } // Note: see getInt64() comment
  2146. getUint64() {
  2147. let low, high;
  2148. if ( this.littleEndian ) {
  2149. low = this.getUint32();
  2150. high = this.getUint32();
  2151. } else {
  2152. high = this.getUint32();
  2153. low = this.getUint32();
  2154. }
  2155. return high * 0x100000000 + low;
  2156. }
  2157. getFloat32() {
  2158. const value = this.dv.getFloat32( this.offset, this.littleEndian );
  2159. this.offset += 4;
  2160. return value;
  2161. }
  2162. getFloat32Array( size ) {
  2163. const a = [];
  2164. for ( let i = 0; i < size; i ++ ) {
  2165. a.push( this.getFloat32() );
  2166. }
  2167. return a;
  2168. }
  2169. getFloat64() {
  2170. const value = this.dv.getFloat64( this.offset, this.littleEndian );
  2171. this.offset += 8;
  2172. return value;
  2173. }
  2174. getFloat64Array( size ) {
  2175. const a = [];
  2176. for ( let i = 0; i < size; i ++ ) {
  2177. a.push( this.getFloat64() );
  2178. }
  2179. return a;
  2180. }
  2181. getArrayBuffer( size ) {
  2182. const value = this.dv.buffer.slice( this.offset, this.offset + size );
  2183. this.offset += size;
  2184. return value;
  2185. }
  2186. getString( size ) {
  2187. // note: safari 9 doesn't support Uint8Array.indexOf; create intermediate array instead
  2188. let a = [];
  2189. for ( let i = 0; i < size; i ++ ) {
  2190. a[ i ] = this.getUint8();
  2191. }
  2192. const nullByte = a.indexOf( 0 );
  2193. if ( nullByte >= 0 ) a = a.slice( 0, nullByte );
  2194. return THREE.LoaderUtils.decodeText( new Uint8Array( a ) );
  2195. }
  2196. } // FBXTree holds a representation of the FBX data, returned by the TextParser ( FBX ASCII format)
  2197. // and BinaryParser( FBX Binary format)
  2198. class FBXTree {
  2199. add( key, val ) {
  2200. this[ key ] = val;
  2201. }
  2202. } // ************** UTILITY FUNCTIONS **************
  2203. function isFbxFormatBinary( buffer ) {
  2204. const CORRECT = 'Kaydara\u0020FBX\u0020Binary\u0020\u0020\0';
  2205. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString( buffer, 0, CORRECT.length );
  2206. }
  2207. function isFbxFormatASCII( text ) {
  2208. const CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  2209. let cursor = 0;
  2210. function read( offset ) {
  2211. const result = text[ offset - 1 ];
  2212. text = text.slice( cursor + offset );
  2213. cursor ++;
  2214. return result;
  2215. }
  2216. for ( let i = 0; i < CORRECT.length; ++ i ) {
  2217. const num = read( 1 );
  2218. if ( num === CORRECT[ i ] ) {
  2219. return false;
  2220. }
  2221. }
  2222. return true;
  2223. }
  2224. function getFbxVersion( text ) {
  2225. const versionRegExp = /FBXVersion: (\d+)/;
  2226. const match = text.match( versionRegExp );
  2227. if ( match ) {
  2228. const version = parseInt( match[ 1 ] );
  2229. return version;
  2230. }
  2231. throw new Error( 'THREE.FBXLoader: Cannot find the version number for the file given.' );
  2232. } // Converts FBX ticks into real time seconds.
  2233. function convertFBXTimeToSeconds( time ) {
  2234. return time / 46186158000;
  2235. }
  2236. const dataArray = []; // extracts the data from the correct position in the FBX array based on indexing type
  2237. function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  2238. let index;
  2239. switch ( infoObject.mappingType ) {
  2240. case 'ByPolygonVertex':
  2241. index = polygonVertexIndex;
  2242. break;
  2243. case 'ByPolygon':
  2244. index = polygonIndex;
  2245. break;
  2246. case 'ByVertice':
  2247. index = vertexIndex;
  2248. break;
  2249. case 'AllSame':
  2250. index = infoObject.indices[ 0 ];
  2251. break;
  2252. default:
  2253. console.warn( 'THREE.FBXLoader: unknown attribute mapping type ' + infoObject.mappingType );
  2254. }
  2255. if ( infoObject.referenceType === 'IndexToDirect' ) index = infoObject.indices[ index ];
  2256. const from = index * infoObject.dataSize;
  2257. const to = from + infoObject.dataSize;
  2258. return slice( dataArray, infoObject.buffer, from, to );
  2259. }
  2260. const tempEuler = new THREE.Euler();
  2261. const tempVec = new THREE.Vector3(); // generate transformation from FBX transform data
  2262. // ref: https://help.autodesk.com/view/FBX/2017/ENU/?guid=__files_GUID_10CDD63C_79C1_4F2D_BB28_AD2BE65A02ED_htm
  2263. // ref: http://docs.autodesk.com/FBX/2014/ENU/FBX-SDK-Documentation/index.html?url=cpp_ref/_transformations_2main_8cxx-example.html,topicNumber=cpp_ref__transformations_2main_8cxx_example_htmlfc10a1e1-b18d-4e72-9dc0-70d0f1959f5e
  2264. function generateTransform( transformData ) {
  2265. const lTranslationM = new THREE.Matrix4();
  2266. const lPreRotationM = new THREE.Matrix4();
  2267. const lRotationM = new THREE.Matrix4();
  2268. const lPostRotationM = new THREE.Matrix4();
  2269. const lScalingM = new THREE.Matrix4();
  2270. const lScalingPivotM = new THREE.Matrix4();
  2271. const lScalingOffsetM = new THREE.Matrix4();
  2272. const lRotationOffsetM = new THREE.Matrix4();
  2273. const lRotationPivotM = new THREE.Matrix4();
  2274. const lParentGX = new THREE.Matrix4();
  2275. const lParentLX = new THREE.Matrix4();
  2276. const lGlobalT = new THREE.Matrix4();
  2277. const inheritType = transformData.inheritType ? transformData.inheritType : 0;
  2278. if ( transformData.translation ) lTranslationM.setPosition( tempVec.fromArray( transformData.translation ) );
  2279. if ( transformData.preRotation ) {
  2280. const array = transformData.preRotation.map( THREE.MathUtils.degToRad );
  2281. array.push( transformData.eulerOrder );
  2282. lPreRotationM.makeRotationFromEuler( tempEuler.fromArray( array ) );
  2283. }
  2284. if ( transformData.rotation ) {
  2285. const array = transformData.rotation.map( THREE.MathUtils.degToRad );
  2286. array.push( transformData.eulerOrder );
  2287. lRotationM.makeRotationFromEuler( tempEuler.fromArray( array ) );
  2288. }
  2289. if ( transformData.postRotation ) {
  2290. const array = transformData.postRotation.map( THREE.MathUtils.degToRad );
  2291. array.push( transformData.eulerOrder );
  2292. lPostRotationM.makeRotationFromEuler( tempEuler.fromArray( array ) );
  2293. lPostRotationM.invert();
  2294. }
  2295. if ( transformData.scale ) lScalingM.scale( tempVec.fromArray( transformData.scale ) ); // Pivots and offsets
  2296. if ( transformData.scalingOffset ) lScalingOffsetM.setPosition( tempVec.fromArray( transformData.scalingOffset ) );
  2297. if ( transformData.scalingPivot ) lScalingPivotM.setPosition( tempVec.fromArray( transformData.scalingPivot ) );
  2298. if ( transformData.rotationOffset ) lRotationOffsetM.setPosition( tempVec.fromArray( transformData.rotationOffset ) );
  2299. if ( transformData.rotationPivot ) lRotationPivotM.setPosition( tempVec.fromArray( transformData.rotationPivot ) ); // parent transform
  2300. if ( transformData.parentMatrixWorld ) {
  2301. lParentLX.copy( transformData.parentMatrix );
  2302. lParentGX.copy( transformData.parentMatrixWorld );
  2303. }
  2304. const lLRM = new THREE.Matrix4().copy( lPreRotationM ).multiply( lRotationM ).multiply( lPostRotationM ); // Global Rotation
  2305. const lParentGRM = new THREE.Matrix4();
  2306. lParentGRM.extractRotation( lParentGX ); // Global Shear*Scaling
  2307. const lParentTM = new THREE.Matrix4();
  2308. lParentTM.copyPosition( lParentGX );
  2309. const lParentGSM = new THREE.Matrix4();
  2310. const lParentGRSM = new THREE.Matrix4().copy( lParentTM ).invert().multiply( lParentGX );
  2311. lParentGSM.copy( lParentGRM ).invert().multiply( lParentGRSM );
  2312. const lLSM = lScalingM;
  2313. const lGlobalRS = new THREE.Matrix4();
  2314. if ( inheritType === 0 ) {
  2315. lGlobalRS.copy( lParentGRM ).multiply( lLRM ).multiply( lParentGSM ).multiply( lLSM );
  2316. } else if ( inheritType === 1 ) {
  2317. lGlobalRS.copy( lParentGRM ).multiply( lParentGSM ).multiply( lLRM ).multiply( lLSM );
  2318. } else {
  2319. const lParentLSM = new THREE.Matrix4().scale( new THREE.Vector3().setFromMatrixScale( lParentLX ) );
  2320. const lParentLSM_inv = new THREE.Matrix4().copy( lParentLSM ).invert();
  2321. const lParentGSM_noLocal = new THREE.Matrix4().copy( lParentGSM ).multiply( lParentLSM_inv );
  2322. lGlobalRS.copy( lParentGRM ).multiply( lLRM ).multiply( lParentGSM_noLocal ).multiply( lLSM );
  2323. }
  2324. const lRotationPivotM_inv = new THREE.Matrix4();
  2325. lRotationPivotM_inv.copy( lRotationPivotM ).invert();
  2326. const lScalingPivotM_inv = new THREE.Matrix4();
  2327. lScalingPivotM_inv.copy( lScalingPivotM ).invert(); // Calculate the local transform matrix
  2328. let lTransform = new THREE.Matrix4();
  2329. lTransform.copy( lTranslationM ).multiply( lRotationOffsetM ).multiply( lRotationPivotM ).multiply( lPreRotationM ).multiply( lRotationM ).multiply( lPostRotationM ).multiply( lRotationPivotM_inv ).multiply( lScalingOffsetM ).multiply( lScalingPivotM ).multiply( lScalingM ).multiply( lScalingPivotM_inv );
  2330. const lLocalTWithAllPivotAndOffsetInfo = new THREE.Matrix4().copyPosition( lTransform );
  2331. const lGlobalTranslation = new THREE.Matrix4().copy( lParentGX ).multiply( lLocalTWithAllPivotAndOffsetInfo );
  2332. lGlobalT.copyPosition( lGlobalTranslation );
  2333. lTransform = new THREE.Matrix4().copy( lGlobalT ).multiply( lGlobalRS ); // from global to local
  2334. lTransform.premultiply( lParentGX.invert() );
  2335. return lTransform;
  2336. } // Returns the three.js intrinsic THREE.Euler order corresponding to FBX extrinsic THREE.Euler order
  2337. // ref: http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_euler_html
  2338. function getEulerOrder( order ) {
  2339. order = order || 0;
  2340. const enums = [ 'ZYX', // -> XYZ extrinsic
  2341. 'YZX', // -> XZY extrinsic
  2342. 'XZY', // -> YZX extrinsic
  2343. 'ZXY', // -> YXZ extrinsic
  2344. 'YXZ', // -> ZXY extrinsic
  2345. 'XYZ' // -> ZYX extrinsic
  2346. //'SphericXYZ', // not possible to support
  2347. ];
  2348. if ( order === 6 ) {
  2349. console.warn( 'THREE.FBXLoader: unsupported THREE.Euler Order: Spherical XYZ. Animations and rotations may be incorrect.' );
  2350. return enums[ 0 ];
  2351. }
  2352. return enums[ order ];
  2353. } // Parses comma separated list of numbers and returns them an array.
  2354. // Used internally by the TextParser
  2355. function parseNumberArray( value ) {
  2356. const array = value.split( ',' ).map( function ( val ) {
  2357. return parseFloat( val );
  2358. } );
  2359. return array;
  2360. }
  2361. function convertArrayBufferToString( buffer, from, to ) {
  2362. if ( from === undefined ) from = 0;
  2363. if ( to === undefined ) to = buffer.byteLength;
  2364. return THREE.LoaderUtils.decodeText( new Uint8Array( buffer, from, to ) );
  2365. }
  2366. function append( a, b ) {
  2367. for ( let i = 0, j = a.length, l = b.length; i < l; i ++, j ++ ) {
  2368. a[ j ] = b[ i ];
  2369. }
  2370. }
  2371. function slice( a, b, from, to ) {
  2372. for ( let i = from, j = 0; i < to; i ++, j ++ ) {
  2373. a[ j ] = b[ i ];
  2374. }
  2375. return a;
  2376. } // inject array a2 into array a1 at index
  2377. function inject( a1, index, a2 ) {
  2378. return a1.slice( 0, index ).concat( a2 ).concat( a1.slice( index ) );
  2379. }
  2380. THREE.FBXLoader = FBXLoader;
  2381. } )();