FBXLoader.js 98 KB

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