aframe-extras.loaders.js 105 KB

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