FBXLoader.js 99 KB

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