FBXLoader.js 89 KB

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