FBXLoader.js 99 KB

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