FBXLoader.js 99 KB

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