FBXLoader.js 98 KB

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