FBXLoader.js 99 KB

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