FBXLoader.js 99 KB

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