FBXLoader.js 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346
  1. /**
  2. * @author Kyle-Larson https://github.com/Kyle-Larson
  3. * @author Takahiro https://github.com/takahirox
  4. *
  5. * Loader loads FBX file and generates Group representing FBX scene.
  6. * Requires FBX file to be >= 7.0 and in ASCII or to be any version in Binary format.
  7. *
  8. * Supports:
  9. * Mesh Generation (Positional Data)
  10. * Normal Data (Per Vertex Drawing Instance)
  11. * UV Data (Per Vertex Drawing Instance)
  12. * Skinning
  13. * Animation
  14. * - Separated Animations based on stacks.
  15. * - Skeletal & Non-Skeletal Animations
  16. * NURBS (Open, Closed and Periodic forms)
  17. *
  18. * Needs Support:
  19. * Indexed Buffers
  20. * PreRotation support.
  21. * Euler rotation order
  22. *
  23. * FBX format references:
  24. * https://wiki.blender.org/index.php/User:Mont29/Foundation/FBX_File_Structure
  25. *
  26. * Binary format specification:
  27. * https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  28. * https://wiki.rogiken.org/specifications/file-format/fbx/ (more detail but Japanese)
  29. */
  30. ( function () {
  31. THREE.FBXLoader = function ( manager ) {
  32. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  33. };
  34. Object.assign( THREE.FBXLoader.prototype, {
  35. load: function ( url, onLoad, onProgress, onError ) {
  36. var self = this;
  37. var resourceDirectory = THREE.Loader.prototype.extractUrlBase( url );
  38. var loader = new THREE.FileLoader( this.manager );
  39. loader.setResponseType( 'arraybuffer' );
  40. loader.load( url, function ( buffer ) {
  41. try {
  42. var scene = self.parse( buffer, resourceDirectory );
  43. onLoad( scene );
  44. } catch ( error ) {
  45. window.setTimeout( function () {
  46. if ( onError ) onError( error );
  47. self.manager.itemError( url );
  48. }, 0 );
  49. }
  50. }, onProgress, onError );
  51. },
  52. parse: function ( FBXBuffer, resourceDirectory ) {
  53. var FBXTree;
  54. if ( isFbxFormatBinary( FBXBuffer ) ) {
  55. FBXTree = new BinaryParser().parse( FBXBuffer );
  56. } else {
  57. var FBXText = convertArrayBufferToString( FBXBuffer );
  58. if ( ! isFbxFormatASCII( FBXText ) ) {
  59. throw new Error( 'THREE.FBXLoader: Unknown format.' );
  60. }
  61. if ( getFbxVersion( FBXText ) < 7000 ) {
  62. throw new Error( 'THREE.FBXLoader: FBX version not supported, FileVersion: ' + getFbxVersion( FBXText ) );
  63. }
  64. FBXTree = new TextParser().parse( FBXText );
  65. }
  66. // console.log( FBXTree );
  67. var connections = parseConnections( FBXTree );
  68. var images = parseImages( FBXTree );
  69. var textures = parseTextures( FBXTree, new THREE.TextureLoader( this.manager ).setPath( resourceDirectory ), images, connections );
  70. var materials = parseMaterials( FBXTree, textures, connections );
  71. var deformers = parseDeformers( FBXTree, connections );
  72. var geometryMap = parseGeometries( FBXTree, connections, deformers );
  73. var sceneGraph = parseScene( FBXTree, connections, deformers, geometryMap, materials );
  74. return sceneGraph;
  75. }
  76. } );
  77. // Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry )
  78. // and details the connection type
  79. function parseConnections( FBXTree ) {
  80. var connectionMap = new Map();
  81. if ( 'Connections' in FBXTree ) {
  82. var connectionArray = FBXTree.Connections.properties.connections;
  83. for ( var connectionArrayIndex = 0, connectionArrayLength = connectionArray.length; connectionArrayIndex < connectionArrayLength; ++ connectionArrayIndex ) {
  84. var connection = connectionArray[ connectionArrayIndex ];
  85. if ( ! connectionMap.has( connection[ 0 ] ) ) {
  86. connectionMap.set( connection[ 0 ], {
  87. parents: [],
  88. children: []
  89. } );
  90. }
  91. var parentRelationship = { ID: connection[ 1 ], relationship: connection[ 2 ] };
  92. connectionMap.get( connection[ 0 ] ).parents.push( parentRelationship );
  93. if ( ! connectionMap.has( connection[ 1 ] ) ) {
  94. connectionMap.set( connection[ 1 ], {
  95. parents: [],
  96. children: []
  97. } );
  98. }
  99. var childRelationship = { ID: connection[ 0 ], relationship: connection[ 2 ] };
  100. connectionMap.get( connection[ 1 ] ).children.push( childRelationship );
  101. }
  102. }
  103. return connectionMap;
  104. }
  105. // Parses map of images referenced in FBXTree.Objects.subNodes.Video
  106. // Images can either be referenced externally or embedded in the file
  107. // These images are connected to textures in FBXTree.Objects.subNodes.Textures
  108. // via FBXTree.Connections. Note that images can be duplicated here, in which case only one
  109. // will will have a .Content field
  110. function parseImages( FBXTree ) {
  111. var imageMap = new Map();
  112. if ( 'Video' in FBXTree.Objects.subNodes ) {
  113. var videoNodes = FBXTree.Objects.subNodes.Video;
  114. for ( var nodeID in videoNodes ) {
  115. var videoNode = videoNodes[ nodeID ];
  116. // raw image data is in videoNode.properties.Content
  117. if ( 'Content' in videoNode.properties ) {
  118. var image = parseImage( videoNodes[ nodeID ] );
  119. imageMap.set( parseInt( nodeID ), image );
  120. }
  121. }
  122. }
  123. return imageMap;
  124. }
  125. // Parse embedded image data in FBXTree.Video.properties.Content
  126. function parseImage( videoNode ) {
  127. var content = videoNode.properties.Content;
  128. var fileName = videoNode.properties.RelativeFilename || videoNode.properties.Filename;
  129. var extension = fileName.slice( fileName.lastIndexOf( '.' ) + 1 ).toLowerCase();
  130. var type;
  131. switch ( extension ) {
  132. case 'bmp':
  133. type = 'image/bmp';
  134. break;
  135. case 'jpg':
  136. case 'jpeg':
  137. type = 'image/jpeg';
  138. break;
  139. case 'png':
  140. type = 'image/png';
  141. break;
  142. case 'tif':
  143. type = 'image/tiff';
  144. break;
  145. default:
  146. console.warn( 'FBXLoader: Image type "' + extension + '" is not supported.' );
  147. return;
  148. }
  149. if ( typeof content === 'string' ) {
  150. return 'data:' + type + ';base64,' + content;
  151. } else {
  152. var array = new Uint8Array( content );
  153. return window.URL.createObjectURL( new Blob( [ array ], { type: type } ) );
  154. }
  155. }
  156. // Parse nodes in FBXTree.Objects.subNodes.Texture
  157. // These contain details such as UV scaling, cropping, rotation etc and are connected
  158. // to images in FBXTree.Objects.subNodes.Video
  159. function parseTextures( FBXTree, loader, imageMap, connections ) {
  160. var textureMap = new Map();
  161. if ( 'Texture' in FBXTree.Objects.subNodes ) {
  162. var textureNodes = FBXTree.Objects.subNodes.Texture;
  163. for ( var nodeID in textureNodes ) {
  164. var texture = parseTexture( textureNodes[ nodeID ], loader, imageMap, connections );
  165. textureMap.set( parseInt( nodeID ), texture );
  166. }
  167. }
  168. return textureMap;
  169. }
  170. // Parse individual node in FBXTree.Objects.subNodes.Texture
  171. function parseTexture( textureNode, loader, imageMap, connections ) {
  172. var FBX_ID = textureNode.id;
  173. var name = textureNode.attrName;
  174. var fileName;
  175. var filePath = textureNode.properties.FileName;
  176. var relativeFilePath = textureNode.properties.RelativeFilename;
  177. var children = connections.get( FBX_ID ).children;
  178. if ( children !== undefined && children.length > 0 && imageMap.has( children[ 0 ].ID ) ) {
  179. fileName = imageMap.get( children[ 0 ].ID );
  180. } else if ( relativeFilePath !== undefined && relativeFilePath[ 0 ] !== '/' && relativeFilePath.match( /^[a-zA-Z]:/ ) === null ) {
  181. // use textureNode.properties.RelativeFilename
  182. // if it exists and it doesn't seem an absolute path
  183. fileName = relativeFilePath;
  184. } else {
  185. var split = filePath.split( /[\\\/]/ );
  186. if ( split.length > 0 ) {
  187. fileName = split[ split.length - 1 ];
  188. } else {
  189. fileName = filePath;
  190. }
  191. }
  192. var currentPath = loader.path;
  193. if ( fileName.indexOf( 'blob:' ) === 0 || fileName.indexOf( 'data:' ) === 0 ) {
  194. loader.setPath( undefined );
  195. }
  196. var texture = loader.load( fileName );
  197. texture.name = name;
  198. texture.FBX_ID = FBX_ID;
  199. var wrapModeU = textureNode.properties.WrapModeU;
  200. var wrapModeV = textureNode.properties.WrapModeV;
  201. var valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
  202. var valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
  203. // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
  204. // 0: repeat(default), 1: clamp
  205. texture.wrapS = valueU === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  206. texture.wrapT = valueV === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  207. if ( 'Scaling' in textureNode.properties ) {
  208. var values = textureNode.properties.Scaling.value;
  209. texture.repeat.x = values[ 0 ];
  210. texture.repeat.y = values[ 1 ];
  211. }
  212. loader.setPath( currentPath );
  213. return texture;
  214. }
  215. // Parse nodes in FBXTree.Objects.subNodes.Material
  216. function parseMaterials( FBXTree, textureMap, connections ) {
  217. var materialMap = new Map();
  218. if ( 'Material' in FBXTree.Objects.subNodes ) {
  219. var materialNodes = FBXTree.Objects.subNodes.Material;
  220. for ( var nodeID in materialNodes ) {
  221. var material = parseMaterial( materialNodes[ nodeID ], textureMap, connections );
  222. if ( material !== null ) materialMap.set( parseInt( nodeID ), material );
  223. }
  224. }
  225. return materialMap;
  226. }
  227. // Parse single node in FBXTree.Objects.subNodes.Material
  228. // Materials are connected to texture maps in FBXTree.Objects.subNodes.Textures
  229. // FBX format currently only supports Lambert and Phong shading models
  230. function parseMaterial( materialNode, textureMap, connections ) {
  231. var FBX_ID = materialNode.id;
  232. var name = materialNode.attrName;
  233. var type = materialNode.properties.ShadingModel;
  234. //Case where FBX wraps shading model in property object.
  235. if ( typeof type === 'object' ) {
  236. type = type.value;
  237. }
  238. // Ignore unused materials which don't have any connections.
  239. if ( ! connections.has( FBX_ID ) ) return null;
  240. var children = connections.get( FBX_ID ).children;
  241. var parameters = parseParameters( materialNode.properties, textureMap, children );
  242. var material;
  243. switch ( type.toLowerCase() ) {
  244. case 'phong':
  245. material = new THREE.MeshPhongMaterial();
  246. break;
  247. case 'lambert':
  248. material = new THREE.MeshLambertMaterial();
  249. break;
  250. default:
  251. console.warn( 'THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.', type );
  252. material = new THREE.MeshPhongMaterial( { color: 0x3300ff } );
  253. break;
  254. }
  255. material.setValues( parameters );
  256. material.name = name;
  257. return material;
  258. }
  259. // Parse FBX material and return parameters suitable for a three.js material
  260. // Also parse the texture map and return any textures associated with the material
  261. function parseParameters( properties, textureMap, childrenRelationships ) {
  262. var parameters = {};
  263. if ( properties.BumpFactor ) {
  264. parameters.bumpScale = properties.BumpFactor.value;
  265. }
  266. if ( properties.Diffuse ) {
  267. parameters.color = parseColor( properties.Diffuse );
  268. }
  269. if ( properties.DisplacementFactor ) {
  270. parameters.displacementScale = properties.DisplacementFactor.value;
  271. }
  272. if ( properties.ReflectionFactor ) {
  273. parameters.reflectivity = properties.ReflectionFactor.value;
  274. }
  275. if ( properties.Specular ) {
  276. parameters.specular = parseColor( properties.Specular );
  277. }
  278. if ( properties.Shininess ) {
  279. parameters.shininess = properties.Shininess.value;
  280. }
  281. if ( properties.Emissive ) {
  282. parameters.emissive = parseColor( properties.Emissive );
  283. }
  284. if ( properties.EmissiveFactor ) {
  285. parameters.emissiveIntensity = parseFloat( properties.EmissiveFactor.value );
  286. }
  287. if ( properties.Opacity ) {
  288. parameters.opacity = parseFloat( properties.Opacity.value );
  289. }
  290. if ( parameters.opacity < 1.0 ) {
  291. parameters.transparent = true;
  292. }
  293. for ( var childrenRelationshipsIndex = 0, childrenRelationshipsLength = childrenRelationships.length; childrenRelationshipsIndex < childrenRelationshipsLength; ++ childrenRelationshipsIndex ) {
  294. var relationship = childrenRelationships[ childrenRelationshipsIndex ];
  295. var type = relationship.relationship;
  296. switch ( type ) {
  297. case 'Bump':
  298. parameters.bumpMap = textureMap.get( relationship.ID );
  299. break;
  300. case 'DiffuseColor':
  301. parameters.map = textureMap.get( relationship.ID );
  302. break;
  303. case 'DisplacementColor':
  304. parameters.displacementMap = textureMap.get( relationship.ID );
  305. break;
  306. case 'EmissiveColor':
  307. parameters.emissiveMap = textureMap.get( relationship.ID );
  308. break;
  309. case 'NormalMap':
  310. parameters.normalMap = textureMap.get( relationship.ID );
  311. break;
  312. case 'ReflectionColor':
  313. parameters.envMap = textureMap.get( relationship.ID );
  314. parameters.envMap.mapping = THREE.EquirectangularReflectionMapping;
  315. break;
  316. case 'SpecularColor':
  317. parameters.specularMap = textureMap.get( relationship.ID );
  318. break;
  319. case 'TransparentColor':
  320. parameters.alphaMap = textureMap.get( relationship.ID );
  321. parameters.transparent = true;
  322. break;
  323. case 'AmbientColor':
  324. case 'ShininessExponent': // AKA glossiness map
  325. case 'SpecularFactor': // AKA specularLevel
  326. case 'VectorDisplacementColor': // NOTE: Seems to be a copy of DisplacementColor
  327. default:
  328. console.warn( 'THREE.FBXLoader: %s map is not supported in three.js, skipping texture.', type );
  329. break;
  330. }
  331. }
  332. return parameters;
  333. }
  334. // Parse nodes in FBXTree.Objects.subNodes.Deformer
  335. // Deformer node can contain skinning or Vertex Cache animation data, however only skinning is supported here
  336. // Generates map of Skeleton-like objects for use later when generating and binding skeletons.
  337. function parseDeformers( FBXTree, connections ) {
  338. var deformers = {};
  339. if ( 'Deformer' in FBXTree.Objects.subNodes ) {
  340. var DeformerNodes = FBXTree.Objects.subNodes.Deformer;
  341. for ( var nodeID in DeformerNodes ) {
  342. var deformerNode = DeformerNodes[ nodeID ];
  343. if ( deformerNode.attrType === 'Skin' ) {
  344. var conns = connections.get( parseInt( nodeID ) );
  345. var skeleton = parseSkeleton( conns, DeformerNodes );
  346. skeleton.FBX_ID = parseInt( nodeID );
  347. deformers[ nodeID ] = skeleton;
  348. }
  349. }
  350. }
  351. return deformers;
  352. }
  353. // Parse single nodes in FBXTree.Objects.subNodes.Deformer
  354. // Generates a "Skeleton Representation" of FBX nodes based on an FBX Skin Deformer's connections
  355. // and an object containing SubDeformer nodes.
  356. function parseSkeleton( connections, DeformerNodes ) {
  357. var subDeformers = {};
  358. var children = connections.children;
  359. for ( var i = 0, l = children.length; i < l; ++ i ) {
  360. var child = children[ i ];
  361. var subDeformerNode = DeformerNodes[ child.ID ];
  362. var subDeformer = {
  363. FBX_ID: child.ID,
  364. index: i,
  365. indices: [],
  366. weights: [],
  367. transform: new THREE.Matrix4().fromArray( subDeformerNode.subNodes.Transform.properties.a ),
  368. transformLink: new THREE.Matrix4().fromArray( subDeformerNode.subNodes.TransformLink.properties.a ),
  369. linkMode: subDeformerNode.properties.Mode
  370. };
  371. if ( 'Indexes' in subDeformerNode.subNodes ) {
  372. subDeformer.indices = subDeformerNode.subNodes.Indexes.properties.a;
  373. subDeformer.weights = subDeformerNode.subNodes.Weights.properties.a;
  374. }
  375. subDeformers[ child.ID ] = subDeformer;
  376. }
  377. return {
  378. map: subDeformers,
  379. bones: []
  380. };
  381. }
  382. // Parse nodes in FBXTree.Objects.subNodes.Geometry
  383. function parseGeometries( FBXTree, connections, deformers ) {
  384. var geometryMap = new Map();
  385. if ( 'Geometry' in FBXTree.Objects.subNodes ) {
  386. var geometryNodes = FBXTree.Objects.subNodes.Geometry;
  387. for ( var nodeID in geometryNodes ) {
  388. var relationships = connections.get( parseInt( nodeID ) );
  389. var geo = parseGeometry( geometryNodes[ nodeID ], relationships, deformers );
  390. geometryMap.set( parseInt( nodeID ), geo );
  391. }
  392. }
  393. return geometryMap;
  394. }
  395. // Parse single node in FBXTree.Objects.subNodes.Geometry
  396. function parseGeometry( geometryNode, relationships, deformers ) {
  397. switch ( geometryNode.attrType ) {
  398. case 'Mesh':
  399. return parseMeshGeometry( geometryNode, relationships, deformers );
  400. break;
  401. case 'NurbsCurve':
  402. return parseNurbsGeometry( geometryNode );
  403. break;
  404. default:
  405. console.error( 'FBXLoader: Unsupported geometry type %s', geometryNode.attrType );
  406. return THREE.BufferGeometry();
  407. }
  408. }
  409. // Parse single node mesh geometry in FBXTree.Objects.subNodes.Geometry
  410. function parseMeshGeometry( geometryNode, relationships, deformers ) {
  411. for ( var i = 0; i < relationships.children.length; ++ i ) {
  412. var deformer = deformers[ relationships.children[ i ].ID ];
  413. if ( deformer !== undefined ) break;
  414. }
  415. return genGeometry( geometryNode, deformer );
  416. }
  417. // Generate a THREE.BufferGeometry from a node in FBXTree.Objects.subNodes.Geometry
  418. function genGeometry( geometryNode, deformer ) {
  419. var subNodes = geometryNode.subNodes;
  420. var vertexPositions = subNodes.Vertices.properties.a;
  421. var vertexIndices = subNodes.PolygonVertexIndex.properties.a;
  422. // create arrays to hold the final data used to build the buffergeometry
  423. var vertexBuffer = [];
  424. var normalBuffer = [];
  425. var colorsBuffer = [];
  426. var uvsBuffer = [];
  427. var materialIndexBuffer = [];
  428. var vertexWeightsBuffer = [];
  429. var weightsIndicesBuffer = [];
  430. if ( subNodes.LayerElementColor ) {
  431. var colorInfo = getColors( subNodes.LayerElementColor[ 0 ] );
  432. }
  433. if ( subNodes.LayerElementMaterial ) {
  434. var materialInfo = getMaterials( subNodes.LayerElementMaterial[ 0 ] );
  435. }
  436. if ( subNodes.LayerElementNormal ) {
  437. var normalInfo = getNormals( subNodes.LayerElementNormal[ 0 ] );
  438. }
  439. if ( subNodes.LayerElementUV ) {
  440. var uvInfo = [];
  441. var i = 0;
  442. while ( subNodes.LayerElementUV[ i ] ) {
  443. uvInfo.push( getUVs( subNodes.LayerElementUV[ i ] ) );
  444. i ++;
  445. }
  446. }
  447. var weightTable = {};
  448. if ( deformer ) {
  449. var subDeformers = deformer.map;
  450. for ( var key in subDeformers ) {
  451. var subDeformer = subDeformers[ key ];
  452. var indices = subDeformer.indices;
  453. for ( var j = 0; j < indices.length; j ++ ) {
  454. var index = indices[ j ];
  455. var weight = subDeformer.weights[ j ];
  456. if ( weightTable[ index ] === undefined ) weightTable[ index ] = [];
  457. weightTable[ index ].push( {
  458. id: subDeformer.index,
  459. weight: weight
  460. } );
  461. }
  462. }
  463. }
  464. var polygonIndex = 0;
  465. var faceLength = 0;
  466. var displayedWeightsWarning = false;
  467. // these will hold data for a single face
  468. var vertexPositionIndexes = [];
  469. var faceNormals = [];
  470. var faceColors = [];
  471. var faceUVs = [];
  472. var faceWeights = [];
  473. var faceWeightIndices = [];
  474. for ( var polygonVertexIndex = 0; polygonVertexIndex < vertexIndices.length; polygonVertexIndex ++ ) {
  475. var vertexIndex = vertexIndices[ polygonVertexIndex ];
  476. var endOfFace = false;
  477. // Face index and vertex index arrays are combined in a single array
  478. // A cube with quad faces looks like this:
  479. // PolygonVertexIndex: *24 {
  480. // 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
  481. // }
  482. // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3
  483. // to find index of last vertex multiply by -1 and subtract 1: -3 * - 1 - 1 = 2
  484. if ( vertexIndex < 0 ) {
  485. vertexIndex = vertexIndex ^ - 1; // equivalent to ( x * -1 ) - 1
  486. vertexIndices[ polygonVertexIndex ] = vertexIndex;
  487. endOfFace = true;
  488. }
  489. var weightIndices = [];
  490. var weights = [];
  491. vertexPositionIndexes.push( vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2 );
  492. if ( colorInfo ) {
  493. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, colorInfo );
  494. faceColors.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  495. }
  496. if ( deformer ) {
  497. if ( weightTable[ vertexIndex ] !== undefined ) {
  498. var array = weightTable[ vertexIndex ];
  499. for ( var j = 0, jl = array.length; j < jl; j ++ ) {
  500. weights.push( array[ j ].weight );
  501. weightIndices.push( array[ j ].id );
  502. }
  503. }
  504. if ( weights.length > 4 ) {
  505. if ( ! displayedWeightsWarning ) {
  506. console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
  507. displayedWeightsWarning = true;
  508. }
  509. var WIndex = [ 0, 0, 0, 0 ];
  510. var Weight = [ 0, 0, 0, 0 ];
  511. weights.forEach( function ( weight, weightIndex ) {
  512. var currentWeight = weight;
  513. var currentIndex = weightIndices[ weightIndex ];
  514. Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) {
  515. if ( currentWeight > comparedWeight ) {
  516. comparedWeightArray[ comparedWeightIndex ] = currentWeight;
  517. currentWeight = comparedWeight;
  518. var tmp = WIndex[ comparedWeightIndex ];
  519. WIndex[ comparedWeightIndex ] = currentIndex;
  520. currentIndex = tmp;
  521. }
  522. } );
  523. } );
  524. weightIndices = WIndex;
  525. weights = Weight;
  526. }
  527. // if the weight array is shorter than 4 pad with 0s
  528. for ( var i = weights.length; i < 4; ++ i ) {
  529. weights[ i ] = 0;
  530. weightIndices[ i ] = 0;
  531. }
  532. for ( var i = 0; i < 4; ++ i ) {
  533. faceWeights.push( weights[ i ] );
  534. faceWeightIndices.push( weightIndices[ i ] );
  535. }
  536. }
  537. if ( normalInfo ) {
  538. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, normalInfo );
  539. faceNormals.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  540. }
  541. if ( uvInfo ) {
  542. for ( var i = 0; i < uvInfo.length; i ++ ) {
  543. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, uvInfo[ i ] );
  544. if ( faceUVs[ i ] === undefined ) {
  545. faceUVs[ i ] = [];
  546. }
  547. faceUVs[ i ].push(
  548. data[ 0 ],
  549. data[ 1 ]
  550. );
  551. }
  552. }
  553. faceLength ++;
  554. // we have reached the end of a face - it may have 4 sides though
  555. // in which case the data is split into to represent 3 sides faces
  556. if ( endOfFace ) {
  557. for ( var i = 2; i < faceLength; i ++ ) {
  558. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ 0 ] ] );
  559. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ 1 ] ] );
  560. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ 2 ] ] );
  561. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ ( i - 1 ) * 3 ] ] );
  562. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ ( i - 1 ) * 3 + 1 ] ] );
  563. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ ( i - 1 ) * 3 + 2 ] ] );
  564. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ i * 3 ] ] );
  565. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ i * 3 + 1 ] ] );
  566. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ i * 3 + 2 ] ] );
  567. }
  568. if ( deformer ) {
  569. for ( var i = 2; i < faceLength; i ++ ) {
  570. vertexWeightsBuffer.push( faceWeights[ 0 ] );
  571. vertexWeightsBuffer.push( faceWeights[ 1 ] );
  572. vertexWeightsBuffer.push( faceWeights[ 2 ] );
  573. vertexWeightsBuffer.push( faceWeights[ 3 ] );
  574. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 ] );
  575. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 + 1 ] );
  576. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 + 2 ] );
  577. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 + 3 ] );
  578. vertexWeightsBuffer.push( faceWeights[ i * 4 ] );
  579. vertexWeightsBuffer.push( faceWeights[ i * 4 + 1 ] );
  580. vertexWeightsBuffer.push( faceWeights[ i * 4 + 2 ] );
  581. vertexWeightsBuffer.push( faceWeights[ i * 4 + 3 ] );
  582. weightsIndicesBuffer.push( faceWeightIndices[ 0 ] );
  583. weightsIndicesBuffer.push( faceWeightIndices[ 1 ] );
  584. weightsIndicesBuffer.push( faceWeightIndices[ 2 ] );
  585. weightsIndicesBuffer.push( faceWeightIndices[ 3 ] );
  586. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 ] );
  587. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 + 1 ] );
  588. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 + 2 ] );
  589. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 + 3 ] );
  590. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 ] );
  591. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 + 1 ] );
  592. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 + 2 ] );
  593. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 + 3 ] );
  594. }
  595. }
  596. if ( normalInfo ) {
  597. for ( var i = 2; i < faceLength; i ++ ) {
  598. normalBuffer.push( faceNormals[ 0 ] );
  599. normalBuffer.push( faceNormals[ 1 ] );
  600. normalBuffer.push( faceNormals[ 2 ] );
  601. normalBuffer.push( faceNormals[ ( i - 1 ) * 3 ] );
  602. normalBuffer.push( faceNormals[ ( i - 1 ) * 3 + 1 ] );
  603. normalBuffer.push( faceNormals[ ( i - 1 ) * 3 + 2 ] );
  604. normalBuffer.push( faceNormals[ i * 3 ] );
  605. normalBuffer.push( faceNormals[ i * 3 + 1 ] );
  606. normalBuffer.push( faceNormals[ i * 3 + 2 ] );
  607. }
  608. }
  609. if ( uvInfo ) {
  610. for ( var j = 0; j < uvInfo.length; j ++ ) {
  611. if ( uvsBuffer[ j ] === undefined ) uvsBuffer[ j ] = [];
  612. for ( var i = 2; i < faceLength; i ++ ) {
  613. uvsBuffer[ j ].push( faceUVs[ j ][ 0 ] );
  614. uvsBuffer[ j ].push( faceUVs[ j ][ 1 ] );
  615. uvsBuffer[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 ] );
  616. uvsBuffer[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 + 1 ] );
  617. uvsBuffer[ j ].push( faceUVs[ j ][ i * 2 ] );
  618. uvsBuffer[ j ].push( faceUVs[ j ][ i * 2 + 1 ] );
  619. }
  620. }
  621. }
  622. if ( colorInfo ) {
  623. for ( var i = 2; i < faceLength; i ++ ) {
  624. colorsBuffer.push( faceColors[ 0 ] );
  625. colorsBuffer.push( faceColors[ 1 ] );
  626. colorsBuffer.push( faceColors[ 2 ] );
  627. colorsBuffer.push( faceColors[ ( i - 1 ) * 3 ] );
  628. colorsBuffer.push( faceColors[ ( i - 1 ) * 3 + 1 ] );
  629. colorsBuffer.push( faceColors[ ( i - 1 ) * 3 + 2 ] );
  630. colorsBuffer.push( faceColors[ i * 3 ] );
  631. colorsBuffer.push( faceColors[ i * 3 + 1 ] );
  632. colorsBuffer.push( faceColors[ i * 3 + 2 ] );
  633. }
  634. }
  635. if ( materialInfo && materialInfo.mappingType !== 'AllSame' ) {
  636. var materialIndex = getData( polygonVertexIndex, polygonIndex, vertexIndex, materialInfo )[ 0 ];
  637. for ( var i = 2; i < faceLength; i ++ ) {
  638. materialIndexBuffer.push( materialIndex );
  639. materialIndexBuffer.push( materialIndex );
  640. materialIndexBuffer.push( materialIndex );
  641. }
  642. }
  643. polygonIndex ++;
  644. endOfFace = false;
  645. faceLength = 0;
  646. // reset arrays for the next face
  647. vertexPositionIndexes = [];
  648. faceNormals = [];
  649. faceColors = [];
  650. faceUVs = [];
  651. faceWeights = [];
  652. faceWeightIndices = [];
  653. }
  654. }
  655. var geo = new THREE.BufferGeometry();
  656. geo.name = geometryNode.name;
  657. geo.addAttribute( 'position', new THREE.Float32BufferAttribute( vertexBuffer, 3 ) );
  658. if ( colorsBuffer.length > 0 ) {
  659. geo.addAttribute( 'color', new THREE.Float32BufferAttribute( colorsBuffer, 3 ) );
  660. }
  661. if ( deformer ) {
  662. geo.addAttribute( 'skinIndex', new THREE.Float32BufferAttribute( weightsIndicesBuffer, 4 ) );
  663. geo.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( vertexWeightsBuffer, 4 ) );
  664. // used later to bind the skeleton to the model
  665. geo.FBX_Deformer = deformer;
  666. }
  667. if ( normalBuffer.length > 0 ) {
  668. geo.addAttribute( 'normal', new THREE.Float32BufferAttribute( normalBuffer, 3 ) );
  669. }
  670. if ( uvsBuffer.length > 0 ) {
  671. for ( var i = 0; i < uvsBuffer.length; i ++ ) {
  672. var name = 'uv' + ( i + 1 ).toString();
  673. if ( i == 0 ) {
  674. name = 'uv';
  675. }
  676. geo.addAttribute( name, new THREE.Float32BufferAttribute( uvsBuffer[ i ], 2 ) );
  677. }
  678. }
  679. if ( materialInfo && materialInfo.mappingType !== 'AllSame' ) {
  680. // Convert the material indices of each vertex into rendering groups on the geometry.
  681. var prevMaterialIndex = materialIndexBuffer[ 0 ];
  682. var startIndex = 0;
  683. for ( var i = 0; i < materialIndexBuffer.length; ++ i ) {
  684. if ( materialIndexBuffer[ i ] !== prevMaterialIndex ) {
  685. geo.addGroup( startIndex, i - startIndex, prevMaterialIndex );
  686. prevMaterialIndex = materialIndexBuffer[ i ];
  687. startIndex = i;
  688. }
  689. }
  690. // the loop above doesn't add the last group, do that here.
  691. if ( geo.groups.length > 0 ) {
  692. var lastGroup = geo.groups[ geo.groups.length - 1 ];
  693. var lastIndex = lastGroup.start + lastGroup.count;
  694. if ( lastIndex !== materialIndexBuffer.length ) {
  695. geo.addGroup( lastIndex, materialIndexBuffer.length - lastIndex, prevMaterialIndex );
  696. }
  697. }
  698. // case where there are multiple materials but the whole geometry is only
  699. // using one of them
  700. if ( geo.groups.length === 0 ) {
  701. geo.addGroup( 0, materialIndexBuffer.length, materialIndexBuffer[ 0 ] );
  702. }
  703. }
  704. return geo;
  705. }
  706. // Parse normal from FBXTree.Objects.subNodes.Geometry.subNodes.LayerElementNormal if it exists
  707. function getNormals( NormalNode ) {
  708. var mappingType = NormalNode.properties.MappingInformationType;
  709. var referenceType = NormalNode.properties.ReferenceInformationType;
  710. var buffer = NormalNode.subNodes.Normals.properties.a;
  711. var indexBuffer = [];
  712. if ( referenceType === 'IndexToDirect' ) {
  713. if ( 'NormalIndex' in NormalNode.subNodes ) {
  714. indexBuffer = NormalNode.subNodes.NormalIndex.properties.a;
  715. } else if ( 'NormalsIndex' in NormalNode.subNodes ) {
  716. indexBuffer = NormalNode.subNodes.NormalsIndex.properties.a;
  717. }
  718. }
  719. return {
  720. dataSize: 3,
  721. buffer: buffer,
  722. indices: indexBuffer,
  723. mappingType: mappingType,
  724. referenceType: referenceType
  725. };
  726. }
  727. // Parse UVs from FBXTree.Objects.subNodes.Geometry.subNodes.LayerElementUV if it exists
  728. function getUVs( UVNode ) {
  729. var mappingType = UVNode.properties.MappingInformationType;
  730. var referenceType = UVNode.properties.ReferenceInformationType;
  731. var buffer = UVNode.subNodes.UV.properties.a;
  732. var indexBuffer = [];
  733. if ( referenceType === 'IndexToDirect' ) {
  734. indexBuffer = UVNode.subNodes.UVIndex.properties.a;
  735. }
  736. return {
  737. dataSize: 2,
  738. buffer: buffer,
  739. indices: indexBuffer,
  740. mappingType: mappingType,
  741. referenceType: referenceType
  742. };
  743. }
  744. // Parse Vertex Colors from FBXTree.Objects.subNodes.Geometry.subNodes.LayerElementColor if it exists
  745. function getColors( ColorNode ) {
  746. var mappingType = ColorNode.properties.MappingInformationType;
  747. var referenceType = ColorNode.properties.ReferenceInformationType;
  748. var buffer = ColorNode.subNodes.Colors.properties.a;
  749. var indexBuffer = [];
  750. if ( referenceType === 'IndexToDirect' ) {
  751. indexBuffer = ColorNode.subNodes.ColorIndex.properties.a;
  752. }
  753. return {
  754. dataSize: 4,
  755. buffer: buffer,
  756. indices: indexBuffer,
  757. mappingType: mappingType,
  758. referenceType: referenceType
  759. };
  760. }
  761. // Parse mapping and material data in FBXTree.Objects.subNodes.Geometry.subNodes.LayerElementMaterial if it exists
  762. function getMaterials( MaterialNode ) {
  763. var mappingType = MaterialNode.properties.MappingInformationType;
  764. var referenceType = MaterialNode.properties.ReferenceInformationType;
  765. if ( mappingType === 'NoMappingInformation' ) {
  766. return {
  767. dataSize: 1,
  768. buffer: [ 0 ],
  769. indices: [ 0 ],
  770. mappingType: 'AllSame',
  771. referenceType: referenceType
  772. };
  773. }
  774. var materialIndexBuffer = MaterialNode.subNodes.Materials.properties.a;
  775. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  776. // we expect.So we create an intermediate buffer that points to the index in the buffer,
  777. // for conforming with the other functions we've written for other data.
  778. var materialIndices = [];
  779. for ( var materialIndexBufferIndex = 0, materialIndexBufferLength = materialIndexBuffer.length; materialIndexBufferIndex < materialIndexBufferLength; ++ materialIndexBufferIndex ) {
  780. materialIndices.push( materialIndexBufferIndex );
  781. }
  782. return {
  783. dataSize: 1,
  784. buffer: materialIndexBuffer,
  785. indices: materialIndices,
  786. mappingType: mappingType,
  787. referenceType: referenceType
  788. };
  789. }
  790. // Functions use the infoObject and given indices to return value array of geometry.
  791. // infoObject can be materialInfo, normalInfo, UVInfo or colorInfo
  792. // polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  793. // polygonIndex - Index of polygon in geometry.
  794. // vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  795. var dataArray = [];
  796. var GetData = {
  797. ByPolygonVertex: {
  798. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  799. var from = ( polygonVertexIndex * infoObject.dataSize );
  800. var to = ( polygonVertexIndex * infoObject.dataSize ) + infoObject.dataSize;
  801. // return infoObject.buffer.slice( from, to );
  802. return slice( dataArray, infoObject.buffer, from, to );
  803. },
  804. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  805. var index = infoObject.indices[ polygonVertexIndex ];
  806. var from = ( index * infoObject.dataSize );
  807. var to = ( index * infoObject.dataSize ) + infoObject.dataSize;
  808. // return infoObject.buffer.slice( from, to );
  809. return slice( dataArray, infoObject.buffer, from, to );
  810. }
  811. },
  812. ByPolygon: {
  813. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  814. var from = polygonIndex * infoObject.dataSize;
  815. var to = polygonIndex * infoObject.dataSize + infoObject.dataSize;
  816. // return infoObject.buffer.slice( from, to );
  817. return slice( dataArray, infoObject.buffer, from, to );
  818. },
  819. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  820. var index = infoObject.indices[ polygonIndex ];
  821. var from = index * infoObject.dataSize;
  822. var to = index * infoObject.dataSize + infoObject.dataSize;
  823. // return infoObject.buffer.slice( from, to );
  824. return slice( dataArray, infoObject.buffer, from, to );
  825. }
  826. },
  827. ByVertice: {
  828. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  829. var from = ( vertexIndex * infoObject.dataSize );
  830. var to = ( vertexIndex * infoObject.dataSize ) + infoObject.dataSize;
  831. // return infoObject.buffer.slice( from, to );
  832. return slice( dataArray, infoObject.buffer, from, to );
  833. }
  834. },
  835. AllSame: {
  836. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  837. var from = infoObject.indices[ 0 ] * infoObject.dataSize;
  838. var to = infoObject.indices[ 0 ] * infoObject.dataSize + infoObject.dataSize;
  839. // return infoObject.buffer.slice( from, to );
  840. return slice( dataArray, infoObject.buffer, from, to );
  841. }
  842. }
  843. };
  844. function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  845. return GetData[ infoObject.mappingType ][ infoObject.referenceType ]( polygonVertexIndex, polygonIndex, vertexIndex, infoObject );
  846. }
  847. // Generate a NurbGeometry from a node in FBXTree.Objects.subNodes.Geometry
  848. function parseNurbsGeometry( geometryNode ) {
  849. if ( THREE.NURBSCurve === undefined ) {
  850. console.error( 'THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.' );
  851. return new THREE.BufferGeometry();
  852. }
  853. var order = parseInt( geometryNode.properties.Order );
  854. if ( isNaN( order ) ) {
  855. console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geometryNode.properties.Order, geometryNode.id );
  856. return new THREE.BufferGeometry();
  857. }
  858. var degree = order - 1;
  859. var knots = geometryNode.subNodes.KnotVector.properties.a;
  860. var controlPoints = [];
  861. var pointsValues = geometryNode.subNodes.Points.properties.a;
  862. for ( var i = 0, l = pointsValues.length; i < l; i += 4 ) {
  863. controlPoints.push( new THREE.Vector4().fromArray( pointsValues, i ) );
  864. }
  865. var startKnot, endKnot;
  866. if ( geometryNode.properties.Form === 'Closed' ) {
  867. controlPoints.push( controlPoints[ 0 ] );
  868. } else if ( geometryNode.properties.Form === 'Periodic' ) {
  869. startKnot = degree;
  870. endKnot = knots.length - 1 - startKnot;
  871. for ( var i = 0; i < degree; ++ i ) {
  872. controlPoints.push( controlPoints[ i ] );
  873. }
  874. }
  875. var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
  876. var vertices = curve.getPoints( controlPoints.length * 7 );
  877. var positions = new Float32Array( vertices.length * 3 );
  878. for ( var i = 0, l = vertices.length; i < l; ++ i ) {
  879. vertices[ i ].toArray( positions, i * 3 );
  880. }
  881. var geometry = new THREE.BufferGeometry();
  882. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  883. return geometry;
  884. }
  885. // parse nodes in FBXTree.Objects.subNodes.Model and generate a THREE.Group
  886. function parseScene( FBXTree, connections, deformers, geometryMap, materialMap ) {
  887. var sceneGraph = new THREE.Group();
  888. var ModelNode = FBXTree.Objects.subNodes.Model;
  889. var modelArray = [];
  890. var modelMap = new Map();
  891. for ( var nodeID in ModelNode ) {
  892. var id = parseInt( nodeID );
  893. var node = ModelNode[ nodeID ];
  894. var conns = connections.get( id );
  895. var model = null;
  896. for ( var i = 0; i < conns.parents.length; ++ i ) {
  897. for ( var FBX_ID in deformers ) {
  898. var deformer = deformers[ FBX_ID ];
  899. var subDeformers = deformer.map;
  900. var subDeformer = subDeformers[ conns.parents[ i ].ID ];
  901. if ( subDeformer ) {
  902. var model2 = model;
  903. model = new THREE.Bone();
  904. deformer.bones[ subDeformer.index ] = model;
  905. // seems like we need this not to make non-connected bone, maybe?
  906. // TODO: confirm
  907. if ( model2 !== null ) model.add( model2 );
  908. }
  909. }
  910. }
  911. if ( ! model ) {
  912. switch ( node.attrType ) {
  913. // create a THREE.PerspectiveCamera or THREE.OrthographicCamera
  914. case 'Camera':
  915. var cameraAttribute;
  916. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  917. var childID = conns.children[ childrenIndex ].ID;
  918. var attr = FBXTree.Objects.subNodes.NodeAttribute[ childID ];
  919. if ( attr !== undefined && attr.properties !== undefined ) {
  920. cameraAttribute = attr.properties;
  921. }
  922. }
  923. if ( cameraAttribute === undefined ) {
  924. model = new THREE.Object3D();
  925. } else {
  926. var type = 0;
  927. if ( cameraAttribute.CameraProjectionType !== undefined && cameraAttribute.CameraProjectionType.value === 1 ) {
  928. type = 1;
  929. }
  930. var nearClippingPlane = 1;
  931. if ( cameraAttribute.NearPlane !== undefined ) {
  932. nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
  933. }
  934. var farClippingPlane = 1000;
  935. if ( cameraAttribute.FarPlane !== undefined ) {
  936. farClippingPlane = cameraAttribute.FarPlane.value / 1000;
  937. }
  938. var width = window.innerWidth;
  939. var height = window.innerHeight;
  940. if ( cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined ) {
  941. width = cameraAttribute.AspectWidth.value;
  942. height = cameraAttribute.AspectHeight.value;
  943. }
  944. var aspect = width / height;
  945. var fov = 45;
  946. if ( cameraAttribute.FieldOfView !== undefined ) {
  947. fov = cameraAttribute.FieldOfView.value;
  948. }
  949. switch ( type ) {
  950. case 0: // Perspective
  951. model = new THREE.PerspectiveCamera( fov, aspect, nearClippingPlane, farClippingPlane );
  952. break;
  953. case 1: // Orthographic
  954. model = new THREE.OrthographicCamera( - width / 2, width / 2, height / 2, - height / 2, nearClippingPlane, farClippingPlane );
  955. break;
  956. default:
  957. console.warn( 'THREE.FBXLoader: Unknown camera type ' + type + '.' );
  958. model = new THREE.Object3D();
  959. break;
  960. }
  961. }
  962. break;
  963. // Create a THREE.DirectionalLight, THREE.PointLight or THREE.SpotLight
  964. case 'Light':
  965. var lightAttribute;
  966. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  967. var childID = conns.children[ childrenIndex ].ID;
  968. var attr = FBXTree.Objects.subNodes.NodeAttribute[ childID ];
  969. if ( attr !== undefined && attr.properties !== undefined ) {
  970. lightAttribute = attr.properties;
  971. }
  972. }
  973. if ( lightAttribute === undefined ) {
  974. model = new THREE.Object3D();
  975. } else {
  976. var type;
  977. // LightType can be undefined for Point lights
  978. if ( lightAttribute.LightType === undefined ) {
  979. type = 0;
  980. } else {
  981. type = lightAttribute.LightType.value;
  982. }
  983. var color = 0xffffff;
  984. if ( lightAttribute.Color !== undefined ) {
  985. color = parseColor( lightAttribute.Color.value );
  986. }
  987. var intensity = ( lightAttribute.Intensity === undefined ) ? 1 : lightAttribute.Intensity.value / 100;
  988. // light disabled
  989. if ( lightAttribute.CastLightOnObject !== undefined && lightAttribute.CastLightOnObject.value === 0 ) {
  990. intensity = 0;
  991. }
  992. var distance = 0;
  993. if ( lightAttribute.FarAttenuationEnd !== undefined ) {
  994. if ( lightAttribute.EnableFarAttenuation !== undefined && lightAttribute.EnableFarAttenuation.value === 0 ) {
  995. distance = 0;
  996. } else {
  997. distance = lightAttribute.FarAttenuationEnd.value / 1000;
  998. }
  999. }
  1000. // TODO: could this be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
  1001. var decay = 1;
  1002. switch ( type ) {
  1003. case 0: // Point
  1004. model = new THREE.PointLight( color, intensity, distance, decay );
  1005. break;
  1006. case 1: // Directional
  1007. model = new THREE.DirectionalLight( color, intensity );
  1008. break;
  1009. case 2: // Spot
  1010. var angle = Math.PI / 3;
  1011. if ( lightAttribute.InnerAngle !== undefined ) {
  1012. angle = THREE.Math.degToRad( lightAttribute.InnerAngle.value );
  1013. }
  1014. var penumbra = 0;
  1015. if ( lightAttribute.OuterAngle !== undefined ) {
  1016. // TODO: this is not correct - FBX calculates outer and inner angle in degrees
  1017. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  1018. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  1019. penumbra = THREE.Math.degToRad( lightAttribute.OuterAngle.value );
  1020. penumbra = Math.max( penumbra, 1 );
  1021. }
  1022. model = new THREE.SpotLight( color, intensity, distance, angle, penumbra, decay );
  1023. break;
  1024. default:
  1025. console.warn( 'THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a THREE.PointLight.' );
  1026. model = new THREE.PointLight( color, intensity );
  1027. break;
  1028. }
  1029. if ( lightAttribute.CastShadows !== undefined && lightAttribute.CastShadows.value === 1 ) {
  1030. model.castShadow = true;
  1031. }
  1032. }
  1033. break;
  1034. case 'Mesh':
  1035. var geometry = null;
  1036. var material = null;
  1037. var materials = [];
  1038. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1039. var child = conns.children[ childrenIndex ];
  1040. if ( geometryMap.has( child.ID ) ) {
  1041. geometry = geometryMap.get( child.ID );
  1042. }
  1043. if ( materialMap.has( child.ID ) ) {
  1044. materials.push( materialMap.get( child.ID ) );
  1045. }
  1046. }
  1047. if ( materials.length > 1 ) {
  1048. material = materials;
  1049. } else if ( materials.length > 0 ) {
  1050. material = materials[ 0 ];
  1051. } else {
  1052. material = new THREE.MeshPhongMaterial( { color: 0xcccccc } );
  1053. materials.push( material );
  1054. }
  1055. if ( 'color' in geometry.attributes ) {
  1056. for ( var materialIndex = 0, numMaterials = materials.length; materialIndex < numMaterials; ++ materialIndex ) {
  1057. materials[ materialIndex ].vertexColors = THREE.VertexColors;
  1058. }
  1059. }
  1060. if ( geometry.FBX_Deformer ) {
  1061. for ( var materialsIndex = 0, materialsLength = materials.length; materialsIndex < materialsLength; ++ materialsIndex ) {
  1062. materials[ materialsIndex ].skinning = true;
  1063. }
  1064. model = new THREE.SkinnedMesh( geometry, material );
  1065. } else {
  1066. model = new THREE.Mesh( geometry, material );
  1067. }
  1068. break;
  1069. case 'NurbsCurve':
  1070. var geometry = null;
  1071. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1072. var child = conns.children[ childrenIndex ];
  1073. if ( geometryMap.has( child.ID ) ) {
  1074. geometry = geometryMap.get( child.ID );
  1075. }
  1076. }
  1077. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  1078. material = new THREE.LineBasicMaterial( { color: 0x3300ff, linewidth: 5 } );
  1079. model = new THREE.Line( geometry, material );
  1080. break;
  1081. default:
  1082. model = new THREE.Group();
  1083. break;
  1084. }
  1085. }
  1086. model.name = THREE.PropertyBinding.sanitizeNodeName( node.attrName );
  1087. model.FBX_ID = id;
  1088. modelArray.push( model );
  1089. modelMap.set( id, model );
  1090. }
  1091. for ( var modelArrayIndex = 0, modelArrayLength = modelArray.length; modelArrayIndex < modelArrayLength; ++ modelArrayIndex ) {
  1092. var model = modelArray[ modelArrayIndex ];
  1093. var node = ModelNode[ model.FBX_ID ];
  1094. if ( 'Lcl_Translation' in node.properties ) {
  1095. model.position.fromArray( node.properties.Lcl_Translation.value );
  1096. }
  1097. if ( 'Lcl_Rotation' in node.properties ) {
  1098. var rotation = node.properties.Lcl_Rotation.value.map( THREE.Math.degToRad );
  1099. rotation.push( 'ZYX' );
  1100. model.rotation.fromArray( rotation );
  1101. }
  1102. if ( 'Lcl_Scaling' in node.properties ) {
  1103. model.scale.fromArray( node.properties.Lcl_Scaling.value );
  1104. }
  1105. if ( 'PreRotation' in node.properties ) {
  1106. var preRotations = new THREE.Euler().fromArray( node.properties.PreRotation.value.map( THREE.Math.degToRad ), 'ZYX' );
  1107. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1108. var currentRotation = new THREE.Quaternion().setFromEuler( model.rotation );
  1109. preRotations.multiply( currentRotation );
  1110. model.rotation.setFromQuaternion( preRotations, 'ZYX' );
  1111. }
  1112. // allow transformed pivots - see https://github.com/mrdoob/three.js/issues/11895
  1113. if ( 'GeometricTranslation' in node.properties ) {
  1114. var array = node.properties.GeometricTranslation.value;
  1115. model.traverse( function ( child ) {
  1116. if ( child.geometry ) {
  1117. child.geometry.translate( array[ 0 ], array[ 1 ], array[ 2 ] );
  1118. }
  1119. } );
  1120. }
  1121. if ( 'LookAtProperty' in node.properties ) {
  1122. var conns = connections.get( model.FBX_ID );
  1123. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1124. var child = conns.children[ childrenIndex ];
  1125. if ( child.relationship === 'LookAtProperty' ) {
  1126. var lookAtTarget = FBXTree.Objects.subNodes.Model[ child.ID ];
  1127. if ( 'Lcl_Translation' in lookAtTarget.properties ) {
  1128. var pos = lookAtTarget.properties.Lcl_Translation.value;
  1129. // DirectionalLight, SpotLight
  1130. if ( model.target !== undefined ) {
  1131. model.target.position.set( pos[ 0 ], pos[ 1 ], pos[ 2 ] );
  1132. sceneGraph.add( model.target );
  1133. } else { // Cameras and other Object3Ds
  1134. model.lookAt( new THREE.Vector3( pos[ 0 ], pos[ 1 ], pos[ 2 ] ) );
  1135. }
  1136. }
  1137. }
  1138. }
  1139. }
  1140. var conns = connections.get( model.FBX_ID );
  1141. for ( var parentIndex = 0; parentIndex < conns.parents.length; parentIndex ++ ) {
  1142. var pIndex = findIndex( modelArray, function ( mod ) {
  1143. return mod.FBX_ID === conns.parents[ parentIndex ].ID;
  1144. } );
  1145. if ( pIndex > - 1 ) {
  1146. modelArray[ pIndex ].add( model );
  1147. break;
  1148. }
  1149. }
  1150. if ( model.parent === null ) {
  1151. sceneGraph.add( model );
  1152. }
  1153. }
  1154. // Now with the bones created, we can update the skeletons and bind them to the skinned meshes.
  1155. sceneGraph.updateMatrixWorld( true );
  1156. var worldMatrices = new Map();
  1157. // Put skeleton into bind pose.
  1158. if ( 'Pose' in FBXTree.Objects.subNodes ) {
  1159. var BindPoseNode = FBXTree.Objects.subNodes.Pose;
  1160. for ( var nodeID in BindPoseNode ) {
  1161. if ( BindPoseNode[ nodeID ].attrType === 'BindPose' ) {
  1162. BindPoseNode = BindPoseNode[ nodeID ];
  1163. break;
  1164. }
  1165. }
  1166. var PoseNode = BindPoseNode.subNodes.PoseNode;
  1167. for ( var PoseNodeIndex = 0, PoseNodeLength = PoseNode.length; PoseNodeIndex < PoseNodeLength; ++ PoseNodeIndex ) {
  1168. var node = PoseNode[ PoseNodeIndex ];
  1169. var rawMatWrd = new THREE.Matrix4().fromArray( node.subNodes.Matrix.properties.a );
  1170. worldMatrices.set( parseInt( node.id ), rawMatWrd );
  1171. }
  1172. }
  1173. for ( var FBX_ID in deformers ) {
  1174. var deformer = deformers[ FBX_ID ];
  1175. var subDeformers = deformer.map;
  1176. for ( var key in subDeformers ) {
  1177. var subDeformer = subDeformers[ key ];
  1178. var subDeformerIndex = subDeformer.index;
  1179. var bone = deformer.bones[ subDeformerIndex ];
  1180. if ( ! worldMatrices.has( bone.FBX_ID ) ) {
  1181. break;
  1182. }
  1183. var mat = worldMatrices.get( bone.FBX_ID );
  1184. bone.matrixWorld.copy( mat );
  1185. }
  1186. // Now that skeleton is in bind pose, bind to model.
  1187. deformer.skeleton = new THREE.Skeleton( deformer.bones );
  1188. var conns = connections.get( deformer.FBX_ID );
  1189. var parents = conns.parents;
  1190. for ( var parentsIndex = 0, parentsLength = parents.length; parentsIndex < parentsLength; ++ parentsIndex ) {
  1191. var parent = parents[ parentsIndex ];
  1192. if ( geometryMap.has( parent.ID ) ) {
  1193. var geoID = parent.ID;
  1194. var geoConns = connections.get( geoID );
  1195. for ( var i = 0; i < geoConns.parents.length; ++ i ) {
  1196. if ( modelMap.has( geoConns.parents[ i ].ID ) ) {
  1197. var model = modelMap.get( geoConns.parents[ i ].ID );
  1198. model.bind( deformer.skeleton, model.matrixWorld );
  1199. break;
  1200. }
  1201. }
  1202. }
  1203. }
  1204. }
  1205. //Skeleton is now bound, return objects to starting world positions.
  1206. sceneGraph.updateMatrixWorld( true );
  1207. // Silly hack with the animation parsing. We're gonna pretend the scene graph has a skeleton
  1208. // to attach animations to, since FBX treats animations as animations for the entire scene,
  1209. // not just for individual objects.
  1210. sceneGraph.skeleton = {
  1211. bones: modelArray
  1212. };
  1213. var animations = parseAnimations( FBXTree, connections, sceneGraph );
  1214. addAnimations( sceneGraph, animations );
  1215. // Parse ambient color - if it's not set to black (default), create an ambient light
  1216. if ( 'GlobalSettings' in FBXTree && 'AmbientColor' in FBXTree.GlobalSettings.properties ) {
  1217. var ambientColor = FBXTree.GlobalSettings.properties.AmbientColor.value;
  1218. var r = ambientColor[ 0 ];
  1219. var g = ambientColor[ 1 ];
  1220. var b = ambientColor[ 2 ];
  1221. if ( r !== 0 || g !== 0 || b !== 0 ) {
  1222. var color = new THREE.Color( r, g, b );
  1223. sceneGraph.add( new THREE.AmbientLight( color, 1 ) );
  1224. }
  1225. }
  1226. return sceneGraph;
  1227. }
  1228. // Parses animation information from nodes in
  1229. // FBXTree.Objects.subNodes.AnimationCurve ( connected to AnimationCurveNode )
  1230. // FBXTree.Objects.subNodes.AnimationCurveNode ( connected to AnimationLayer and an animated property in some other node )
  1231. // FBXTree.Objects.subNodes.AnimationLayer ( connected to AnimationStack )
  1232. // FBXTree.Objects.subNodes.AnimationStack
  1233. function parseAnimations( FBXTree, connections, sceneGraph ) {
  1234. var rawNodes = FBXTree.Objects.subNodes.AnimationCurveNode;
  1235. var rawCurves = FBXTree.Objects.subNodes.AnimationCurve;
  1236. var rawLayers = FBXTree.Objects.subNodes.AnimationLayer;
  1237. var rawStacks = FBXTree.Objects.subNodes.AnimationStack;
  1238. var fps = 30; // default framerate
  1239. if ( 'GlobalSettings' in FBXTree && 'TimeMode' in FBXTree.GlobalSettings.properties ) {
  1240. /* Autodesk time mode documentation can be found here:
  1241. * http://docs.autodesk.com/FBX/2014/ENU/FBX-SDK-Documentation/index.html?url=cpp_ref/class_fbx_time.html,topicNumber=cpp_ref_class_fbx_time_html
  1242. */
  1243. var timeModeEnum = [
  1244. 30, // 0: eDefaultMode
  1245. 120, // 1: eFrames120
  1246. 100, // 2: eFrames100
  1247. 60, // 3: eFrames60
  1248. 50, // 4: eFrames50
  1249. 48, // 5: eFrames48
  1250. 30, // 6: eFrames30 (black and white NTSC )
  1251. 30, // 7: eFrames30Drop
  1252. 29.97, // 8: eNTSCDropFrame
  1253. 29.97, // 90: eNTSCFullFrame
  1254. 25, // 10: ePal ( PAL/SECAM )
  1255. 24, // 11: eFrames24 (Film/Cinema)
  1256. 1, // 12: eFrames1000 (use for date time))
  1257. 23.976, // 13: eFilmFullFrame
  1258. 30, // 14: eCustom: use GlobalSettings.properties.CustomFrameRate.value
  1259. 96, // 15: eFrames96
  1260. 72, // 16: eFrames72
  1261. 59.94, // 17: eFrames59dot94
  1262. ];
  1263. var eMode = FBXTree.GlobalSettings.properties.TimeMode.value;
  1264. if ( eMode === 14 ) {
  1265. if ( 'CustomFrameRate' in FBXTree.GlobalSettings.properties ) {
  1266. fps = FBXTree.GlobalSettings.properties.CustomFrameRate.value;
  1267. fps = ( fps === - 1 ) ? 30 : fps;
  1268. }
  1269. } else if ( eMode <= 17 ) { // for future proofing - if more eModes get added, they will default to 30fps
  1270. fps = timeModeEnum[ eMode ];
  1271. }
  1272. }
  1273. /**
  1274. * @type {{
  1275. curves: Map<number, {
  1276. T: {
  1277. id: number;
  1278. attr: string;
  1279. internalID: number;
  1280. attrX: boolean;
  1281. attrY: boolean;
  1282. attrZ: boolean;
  1283. containerBoneID: number;
  1284. containerID: number;
  1285. curves: {
  1286. x: {
  1287. version: any;
  1288. id: number;
  1289. internalID: number;
  1290. times: number[];
  1291. values: number[];
  1292. attrFlag: number[];
  1293. attrData: number[];
  1294. };
  1295. y: {
  1296. version: any;
  1297. id: number;
  1298. internalID: number;
  1299. times: number[];
  1300. values: number[];
  1301. attrFlag: number[];
  1302. attrData: number[];
  1303. };
  1304. z: {
  1305. version: any;
  1306. id: number;
  1307. internalID: number;
  1308. times: number[];
  1309. values: number[];
  1310. attrFlag: number[];
  1311. attrData: number[];
  1312. };
  1313. };
  1314. },
  1315. R: {
  1316. id: number;
  1317. attr: string;
  1318. internalID: number;
  1319. attrX: boolean;
  1320. attrY: boolean;
  1321. attrZ: boolean;
  1322. containerBoneID: number;
  1323. containerID: number;
  1324. curves: {
  1325. x: {
  1326. version: any;
  1327. id: number;
  1328. internalID: number;
  1329. times: number[];
  1330. values: number[];
  1331. attrFlag: number[];
  1332. attrData: number[];
  1333. };
  1334. y: {
  1335. version: any;
  1336. id: number;
  1337. internalID: number;
  1338. times: number[];
  1339. values: number[];
  1340. attrFlag: number[];
  1341. attrData: number[];
  1342. };
  1343. z: {
  1344. version: any;
  1345. id: number;
  1346. internalID: number;
  1347. times: number[];
  1348. values: number[];
  1349. attrFlag: number[];
  1350. attrData: number[];
  1351. };
  1352. };
  1353. },
  1354. S: {
  1355. id: number;
  1356. attr: string;
  1357. internalID: number;
  1358. attrX: boolean;
  1359. attrY: boolean;
  1360. attrZ: boolean;
  1361. containerBoneID: number;
  1362. containerID: number;
  1363. curves: {
  1364. x: {
  1365. version: any;
  1366. id: number;
  1367. internalID: number;
  1368. times: number[];
  1369. values: number[];
  1370. attrFlag: number[];
  1371. attrData: number[];
  1372. };
  1373. y: {
  1374. version: any;
  1375. id: number;
  1376. internalID: number;
  1377. times: number[];
  1378. values: number[];
  1379. attrFlag: number[];
  1380. attrData: number[];
  1381. };
  1382. z: {
  1383. version: any;
  1384. id: number;
  1385. internalID: number;
  1386. times: number[];
  1387. values: number[];
  1388. attrFlag: number[];
  1389. attrData: number[];
  1390. };
  1391. };
  1392. }
  1393. }>,
  1394. layers: Map<number, {
  1395. T: {
  1396. id: number;
  1397. attr: string;
  1398. internalID: number;
  1399. attrX: boolean;
  1400. attrY: boolean;
  1401. attrZ: boolean;
  1402. containerBoneID: number;
  1403. containerID: number;
  1404. curves: {
  1405. x: {
  1406. version: any;
  1407. id: number;
  1408. internalID: number;
  1409. times: number[];
  1410. values: number[];
  1411. attrFlag: number[];
  1412. attrData: number[];
  1413. };
  1414. y: {
  1415. version: any;
  1416. id: number;
  1417. internalID: number;
  1418. times: number[];
  1419. values: number[];
  1420. attrFlag: number[];
  1421. attrData: number[];
  1422. };
  1423. z: {
  1424. version: any;
  1425. id: number;
  1426. internalID: number;
  1427. times: number[];
  1428. values: number[];
  1429. attrFlag: number[];
  1430. attrData: number[];
  1431. };
  1432. },
  1433. },
  1434. R: {
  1435. id: number;
  1436. attr: string;
  1437. internalID: number;
  1438. attrX: boolean;
  1439. attrY: boolean;
  1440. attrZ: boolean;
  1441. containerBoneID: number;
  1442. containerID: number;
  1443. curves: {
  1444. x: {
  1445. version: any;
  1446. id: number;
  1447. internalID: number;
  1448. times: number[];
  1449. values: number[];
  1450. attrFlag: number[];
  1451. attrData: number[];
  1452. };
  1453. y: {
  1454. version: any;
  1455. id: number;
  1456. internalID: number;
  1457. times: number[];
  1458. values: number[];
  1459. attrFlag: number[];
  1460. attrData: number[];
  1461. };
  1462. z: {
  1463. version: any;
  1464. id: number;
  1465. internalID: number;
  1466. times: number[];
  1467. values: number[];
  1468. attrFlag: number[];
  1469. attrData: number[];
  1470. };
  1471. },
  1472. },
  1473. S: {
  1474. id: number;
  1475. attr: string;
  1476. internalID: number;
  1477. attrX: boolean;
  1478. attrY: boolean;
  1479. attrZ: boolean;
  1480. containerBoneID: number;
  1481. containerID: number;
  1482. curves: {
  1483. x: {
  1484. version: any;
  1485. id: number;
  1486. internalID: number;
  1487. times: number[];
  1488. values: number[];
  1489. attrFlag: number[];
  1490. attrData: number[];
  1491. };
  1492. y: {
  1493. version: any;
  1494. id: number;
  1495. internalID: number;
  1496. times: number[];
  1497. values: number[];
  1498. attrFlag: number[];
  1499. attrData: number[];
  1500. };
  1501. z: {
  1502. version: any;
  1503. id: number;
  1504. internalID: number;
  1505. times: number[];
  1506. values: number[];
  1507. attrFlag: number[];
  1508. attrData: number[];
  1509. };
  1510. },
  1511. }
  1512. }[]>,
  1513. stacks: Map<number, {
  1514. name: string,
  1515. layers: {
  1516. T: {
  1517. id: number;
  1518. attr: string;
  1519. internalID: number;
  1520. attrX: boolean;
  1521. attrY: boolean;
  1522. attrZ: boolean;
  1523. containerBoneID: number;
  1524. containerID: number;
  1525. curves: {
  1526. x: {
  1527. version: any;
  1528. id: number;
  1529. internalID: number;
  1530. times: number[];
  1531. values: number[];
  1532. attrFlag: number[];
  1533. attrData: number[];
  1534. };
  1535. y: {
  1536. version: any;
  1537. id: number;
  1538. internalID: number;
  1539. times: number[];
  1540. values: number[];
  1541. attrFlag: number[];
  1542. attrData: number[];
  1543. };
  1544. z: {
  1545. version: any;
  1546. id: number;
  1547. internalID: number;
  1548. times: number[];
  1549. values: number[];
  1550. attrFlag: number[];
  1551. attrData: number[];
  1552. };
  1553. };
  1554. };
  1555. R: {
  1556. id: number;
  1557. attr: string;
  1558. internalID: number;
  1559. attrX: boolean;
  1560. attrY: boolean;
  1561. attrZ: boolean;
  1562. containerBoneID: number;
  1563. containerID: number;
  1564. curves: {
  1565. x: {
  1566. version: any;
  1567. id: number;
  1568. internalID: number;
  1569. times: number[];
  1570. values: number[];
  1571. attrFlag: number[];
  1572. attrData: number[];
  1573. };
  1574. y: {
  1575. version: any;
  1576. id: number;
  1577. internalID: number;
  1578. times: number[];
  1579. values: number[];
  1580. attrFlag: number[];
  1581. attrData: number[];
  1582. };
  1583. z: {
  1584. version: any;
  1585. id: number;
  1586. internalID: number;
  1587. times: number[];
  1588. values: number[];
  1589. attrFlag: number[];
  1590. attrData: number[];
  1591. };
  1592. };
  1593. };
  1594. S: {
  1595. id: number;
  1596. attr: string;
  1597. internalID: number;
  1598. attrX: boolean;
  1599. attrY: boolean;
  1600. attrZ: boolean;
  1601. containerBoneID: number;
  1602. containerID: number;
  1603. curves: {
  1604. x: {
  1605. version: any;
  1606. id: number;
  1607. internalID: number;
  1608. times: number[];
  1609. values: number[];
  1610. attrFlag: number[];
  1611. attrData: number[];
  1612. };
  1613. y: {
  1614. version: any;
  1615. id: number;
  1616. internalID: number;
  1617. times: number[];
  1618. values: number[];
  1619. attrFlag: number[];
  1620. attrData: number[];
  1621. };
  1622. z: {
  1623. version: any;
  1624. id: number;
  1625. internalID: number;
  1626. times: number[];
  1627. values: number[];
  1628. attrFlag: number[];
  1629. attrData: number[];
  1630. };
  1631. };
  1632. };
  1633. }[][],
  1634. length: number,
  1635. frames: number }>,
  1636. length: number,
  1637. fps: number,
  1638. frames: number
  1639. }}
  1640. */
  1641. var returnObject = {
  1642. curves: new Map(),
  1643. layers: {},
  1644. stacks: {},
  1645. length: 0,
  1646. fps: fps,
  1647. frames: 0
  1648. };
  1649. var animationCurveNodes = [];
  1650. for ( var nodeID in rawNodes ) {
  1651. if ( nodeID.match( /\d+/ ) ) {
  1652. var animationNode = parseAnimationNode( FBXTree, rawNodes[ nodeID ], connections, sceneGraph );
  1653. animationCurveNodes.push( animationNode );
  1654. }
  1655. }
  1656. var tmpMap = new Map();
  1657. for ( var animationCurveNodeIndex = 0; animationCurveNodeIndex < animationCurveNodes.length; ++ animationCurveNodeIndex ) {
  1658. if ( animationCurveNodes[ animationCurveNodeIndex ] === null ) {
  1659. continue;
  1660. }
  1661. tmpMap.set( animationCurveNodes[ animationCurveNodeIndex ].id, animationCurveNodes[ animationCurveNodeIndex ] );
  1662. }
  1663. var animationCurves = [];
  1664. for ( nodeID in rawCurves ) {
  1665. if ( nodeID.match( /\d+/ ) ) {
  1666. var animationCurve = parseAnimationCurve( rawCurves[ nodeID ] );
  1667. // seems like this check would be necessary?
  1668. if ( ! connections.has( animationCurve.id ) ) continue;
  1669. animationCurves.push( animationCurve );
  1670. var firstParentConn = connections.get( animationCurve.id ).parents[ 0 ];
  1671. var firstParentID = firstParentConn.ID;
  1672. var firstParentRelationship = firstParentConn.relationship;
  1673. var axis = '';
  1674. if ( firstParentRelationship.match( /X/ ) ) {
  1675. axis = 'x';
  1676. } else if ( firstParentRelationship.match( /Y/ ) ) {
  1677. axis = 'y';
  1678. } else if ( firstParentRelationship.match( /Z/ ) ) {
  1679. axis = 'z';
  1680. } else {
  1681. continue;
  1682. }
  1683. tmpMap.get( firstParentID ).curves[ axis ] = animationCurve;
  1684. }
  1685. }
  1686. tmpMap.forEach( function ( curveNode ) {
  1687. var id = curveNode.containerBoneID;
  1688. if ( ! returnObject.curves.has( id ) ) {
  1689. returnObject.curves.set( id, { T: null, R: null, S: null } );
  1690. }
  1691. returnObject.curves.get( id )[ curveNode.attr ] = curveNode;
  1692. if ( curveNode.attr === 'R' ) {
  1693. var curves = curveNode.curves;
  1694. // Some FBX files have an AnimationCurveNode
  1695. // which isn't any connected to any AnimationCurve.
  1696. // Setting animation parameter for them here.
  1697. if ( curves.x === null ) {
  1698. curves.x = {
  1699. version: null,
  1700. times: [ 0.0 ],
  1701. values: [ 0.0 ]
  1702. };
  1703. }
  1704. if ( curves.y === null ) {
  1705. curves.y = {
  1706. version: null,
  1707. times: [ 0.0 ],
  1708. values: [ 0.0 ]
  1709. };
  1710. }
  1711. if ( curves.z === null ) {
  1712. curves.z = {
  1713. version: null,
  1714. times: [ 0.0 ],
  1715. values: [ 0.0 ]
  1716. };
  1717. }
  1718. curves.x.values = curves.x.values.map( THREE.Math.degToRad );
  1719. curves.y.values = curves.y.values.map( THREE.Math.degToRad );
  1720. curves.z.values = curves.z.values.map( THREE.Math.degToRad );
  1721. if ( curveNode.preRotations !== null ) {
  1722. var preRotations = new THREE.Euler().setFromVector3( curveNode.preRotations, 'ZYX' );
  1723. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1724. var frameRotation = new THREE.Euler();
  1725. var frameRotationQuaternion = new THREE.Quaternion();
  1726. for ( var frame = 0; frame < curves.x.times.length; ++ frame ) {
  1727. frameRotation.set( curves.x.values[ frame ], curves.y.values[ frame ], curves.z.values[ frame ], 'ZYX' );
  1728. frameRotationQuaternion.setFromEuler( frameRotation ).premultiply( preRotations );
  1729. frameRotation.setFromQuaternion( frameRotationQuaternion, 'ZYX' );
  1730. curves.x.values[ frame ] = frameRotation.x;
  1731. curves.y.values[ frame ] = frameRotation.y;
  1732. curves.z.values[ frame ] = frameRotation.z;
  1733. }
  1734. }
  1735. }
  1736. } );
  1737. for ( var nodeID in rawLayers ) {
  1738. var layer = [];
  1739. var children = connections.get( parseInt( nodeID ) ).children;
  1740. for ( var childIndex = 0; childIndex < children.length; childIndex ++ ) {
  1741. // Skip lockInfluenceWeights
  1742. if ( tmpMap.has( children[ childIndex ].ID ) ) {
  1743. var curveNode = tmpMap.get( children[ childIndex ].ID );
  1744. var boneID = curveNode.containerBoneID;
  1745. if ( layer[ boneID ] === undefined ) {
  1746. layer[ boneID ] = {
  1747. T: null,
  1748. R: null,
  1749. S: null
  1750. };
  1751. }
  1752. layer[ boneID ][ curveNode.attr ] = curveNode;
  1753. }
  1754. }
  1755. returnObject.layers[ nodeID ] = layer;
  1756. }
  1757. for ( var nodeID in rawStacks ) {
  1758. var layers = [];
  1759. var children = connections.get( parseInt( nodeID ) ).children;
  1760. var timestamps = { max: 0, min: Number.MAX_VALUE };
  1761. for ( var childIndex = 0; childIndex < children.length; ++ childIndex ) {
  1762. var currentLayer = returnObject.layers[ children[ childIndex ].ID ];
  1763. if ( currentLayer !== undefined ) {
  1764. layers.push( currentLayer );
  1765. for ( var currentLayerIndex = 0, currentLayerLength = currentLayer.length; currentLayerIndex < currentLayerLength; ++ currentLayerIndex ) {
  1766. var layer = currentLayer[ currentLayerIndex ];
  1767. if ( layer ) {
  1768. getCurveNodeMaxMinTimeStamps( layer, timestamps );
  1769. }
  1770. }
  1771. }
  1772. }
  1773. // Do we have an animation clip with actual length?
  1774. if ( timestamps.max > timestamps.min ) {
  1775. returnObject.stacks[ nodeID ] = {
  1776. name: rawStacks[ nodeID ].attrName,
  1777. layers: layers,
  1778. length: timestamps.max - timestamps.min,
  1779. frames: ( timestamps.max - timestamps.min ) * returnObject.fps
  1780. };
  1781. }
  1782. }
  1783. return returnObject;
  1784. }
  1785. function parseAnimationNode( FBXTree, animationCurveNode, connections, sceneGraph ) {
  1786. var rawModels = FBXTree.Objects.subNodes.Model;
  1787. var returnObject = {
  1788. id: animationCurveNode.id,
  1789. attr: animationCurveNode.attrName,
  1790. internalID: animationCurveNode.id,
  1791. attrX: false,
  1792. attrY: false,
  1793. attrZ: false,
  1794. containerBoneID: - 1,
  1795. containerID: - 1,
  1796. curves: {
  1797. x: null,
  1798. y: null,
  1799. z: null
  1800. },
  1801. preRotations: null
  1802. };
  1803. if ( returnObject.attr.match( /S|R|T/ ) ) {
  1804. for ( var attributeKey in animationCurveNode.properties ) {
  1805. if ( attributeKey.match( /X/ ) ) {
  1806. returnObject.attrX = true;
  1807. }
  1808. if ( attributeKey.match( /Y/ ) ) {
  1809. returnObject.attrY = true;
  1810. }
  1811. if ( attributeKey.match( /Z/ ) ) {
  1812. returnObject.attrZ = true;
  1813. }
  1814. }
  1815. } else {
  1816. return null;
  1817. }
  1818. var conns = connections.get( returnObject.id );
  1819. var containerIndices = conns.parents;
  1820. for ( var containerIndicesIndex = containerIndices.length - 1; containerIndicesIndex >= 0; -- containerIndicesIndex ) {
  1821. var boneID = findIndex( sceneGraph.skeleton.bones, function ( bone ) {
  1822. return bone.FBX_ID === containerIndices[ containerIndicesIndex ].ID;
  1823. } );
  1824. if ( boneID > - 1 ) {
  1825. returnObject.containerBoneID = boneID;
  1826. returnObject.containerID = containerIndices[ containerIndicesIndex ].ID;
  1827. var model = rawModels[ returnObject.containerID.toString() ];
  1828. if ( 'PreRotation' in model.properties ) {
  1829. returnObject.preRotations = parseVector3( model.properties.PreRotation ).multiplyScalar( Math.PI / 180 );
  1830. }
  1831. break;
  1832. }
  1833. }
  1834. return returnObject;
  1835. }
  1836. function parseAnimationCurve( animationCurve ) {
  1837. return {
  1838. version: null,
  1839. id: animationCurve.id,
  1840. internalID: animationCurve.id,
  1841. times: animationCurve.subNodes.KeyTime.properties.a.map( convertFBXTimeToSeconds ),
  1842. values: animationCurve.subNodes.KeyValueFloat.properties.a,
  1843. attrFlag: animationCurve.subNodes.KeyAttrFlags.properties.a,
  1844. attrData: animationCurve.subNodes.KeyAttrDataFloat.properties.a,
  1845. };
  1846. }
  1847. // Sets the maxTimeStamp and minTimeStamp variables if it has timeStamps that are either larger or smaller
  1848. // than the max or min respectively.
  1849. function getCurveNodeMaxMinTimeStamps( layer, timestamps ) {
  1850. if ( layer.R ) {
  1851. getCurveMaxMinTimeStamp( layer.R.curves, timestamps );
  1852. }
  1853. if ( layer.S ) {
  1854. getCurveMaxMinTimeStamp( layer.S.curves, timestamps );
  1855. }
  1856. if ( layer.T ) {
  1857. getCurveMaxMinTimeStamp( layer.T.curves, timestamps );
  1858. }
  1859. }
  1860. // Sets the maxTimeStamp and minTimeStamp if one of the curve's time stamps
  1861. // exceeds the maximum or minimum.
  1862. function getCurveMaxMinTimeStamp( curve, timestamps ) {
  1863. if ( curve.x ) {
  1864. getCurveAxisMaxMinTimeStamps( curve.x, timestamps );
  1865. }
  1866. if ( curve.y ) {
  1867. getCurveAxisMaxMinTimeStamps( curve.y, timestamps );
  1868. }
  1869. if ( curve.z ) {
  1870. getCurveAxisMaxMinTimeStamps( curve.z, timestamps );
  1871. }
  1872. }
  1873. // Sets the maxTimeStamp and minTimeStamp if one of its timestamps exceeds the maximum or minimum.
  1874. function getCurveAxisMaxMinTimeStamps( axis, timestamps ) {
  1875. timestamps.max = axis.times[ axis.times.length - 1 ] > timestamps.max ? axis.times[ axis.times.length - 1 ] : timestamps.max;
  1876. timestamps.min = axis.times[ 0 ] < timestamps.min ? axis.times[ 0 ] : timestamps.min;
  1877. }
  1878. function addAnimations( group, animations ) {
  1879. if ( group.animations === undefined ) {
  1880. group.animations = [];
  1881. }
  1882. var stacks = animations.stacks;
  1883. for ( var key in stacks ) {
  1884. var stack = stacks[ key ];
  1885. var animationData = {
  1886. name: stack.name,
  1887. fps: animations.fps,
  1888. length: stack.length,
  1889. hierarchy: []
  1890. };
  1891. var bones = group.skeleton.bones;
  1892. for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
  1893. var bone = bones[ bonesIndex ];
  1894. var name = bone.name.replace( /.*:/, '' );
  1895. var parentIndex = findIndex( bones, function ( parentBone ) {
  1896. return bone.parent === parentBone;
  1897. } );
  1898. animationData.hierarchy.push( { parent: parentIndex, name: name, keys: [] } );
  1899. }
  1900. for ( var frame = 0; frame <= stack.frames; frame ++ ) {
  1901. for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
  1902. var bone = bones[ bonesIndex ];
  1903. var boneIndex = bonesIndex;
  1904. var animationNode = stack.layers[ 0 ][ boneIndex ];
  1905. for ( var hierarchyIndex = 0, hierarchyLength = animationData.hierarchy.length; hierarchyIndex < hierarchyLength; ++ hierarchyIndex ) {
  1906. var node = animationData.hierarchy[ hierarchyIndex ];
  1907. if ( node.name === bone.name ) {
  1908. node.keys.push( generateKey( animations, animationNode, bone, frame ) );
  1909. }
  1910. }
  1911. }
  1912. }
  1913. group.animations.push( THREE.AnimationClip.parseAnimation( animationData, bones ) );
  1914. }
  1915. }
  1916. var euler = new THREE.Euler();
  1917. var quaternion = new THREE.Quaternion();
  1918. function generateKey( animations, animationNode, bone, frame ) {
  1919. var key = {
  1920. time: frame / animations.fps,
  1921. pos: bone.position.toArray(),
  1922. rot: bone.quaternion.toArray(),
  1923. scl: bone.scale.toArray()
  1924. };
  1925. if ( animationNode === undefined ) return key;
  1926. euler.setFromQuaternion( bone.quaternion, 'ZYX', false );
  1927. try {
  1928. if ( hasCurve( animationNode, 'T' ) && hasKeyOnFrame( animationNode.T, frame ) ) {
  1929. if ( animationNode.T.curves.x.values[ frame ] ) {
  1930. key.pos[ 0 ] = animationNode.T.curves.x.values[ frame ];
  1931. }
  1932. if ( animationNode.T.curves.y.values[ frame ] ) {
  1933. key.pos[ 1 ] = animationNode.T.curves.y.values[ frame ];
  1934. }
  1935. if ( animationNode.T.curves.z.values[ frame ] ) {
  1936. key.pos[ 2 ] = animationNode.T.curves.z.values[ frame ];
  1937. }
  1938. }
  1939. if ( hasCurve( animationNode, 'R' ) && hasKeyOnFrame( animationNode.R, frame ) ) {
  1940. // Only update the euler's values if rotation is defined for the axis on this frame
  1941. if ( animationNode.R.curves.x.values[ frame ] ) {
  1942. euler.x = animationNode.R.curves.x.values[ frame ];
  1943. }
  1944. if ( animationNode.R.curves.y.values[ frame ] ) {
  1945. euler.y = animationNode.R.curves.y.values[ frame ];
  1946. }
  1947. if ( animationNode.R.curves.z.values[ frame ] ) {
  1948. euler.z = animationNode.R.curves.z.values[ frame ];
  1949. }
  1950. quaternion.setFromEuler( euler );
  1951. key.rot = quaternion.toArray();
  1952. }
  1953. if ( hasCurve( animationNode, 'S' ) && hasKeyOnFrame( animationNode.S, frame ) ) {
  1954. if ( animationNode.T.curves.x.values[ frame ] ) {
  1955. key.scl[ 0 ] = animationNode.S.curves.x.values[ frame ];
  1956. }
  1957. if ( animationNode.T.curves.y.values[ frame ] ) {
  1958. key.scl[ 1 ] = animationNode.S.curves.y.values[ frame ];
  1959. }
  1960. if ( animationNode.T.curves.z.values[ frame ] ) {
  1961. key.scl[ 2 ] = animationNode.S.curves.z.values[ frame ];
  1962. }
  1963. }
  1964. } catch ( error ) {
  1965. // Curve is not fully plotted.
  1966. console.log( 'THREE.FBXLoader: ', bone );
  1967. console.log( 'THREE.FBXLoader: ', error );
  1968. }
  1969. return key;
  1970. }
  1971. var AXES = [ 'x', 'y', 'z' ];
  1972. function hasCurve( animationNode, attribute ) {
  1973. if ( animationNode === undefined ) {
  1974. return false;
  1975. }
  1976. var attributeNode = animationNode[ attribute ];
  1977. if ( ! attributeNode ) {
  1978. return false;
  1979. }
  1980. return AXES.every( function ( key ) {
  1981. return attributeNode.curves[ key ] !== null;
  1982. } );
  1983. }
  1984. function hasKeyOnFrame( attributeNode, frame ) {
  1985. return AXES.every( function ( key ) {
  1986. return isKeyExistOnFrame( attributeNode.curves[ key ], frame );
  1987. } );
  1988. }
  1989. function isKeyExistOnFrame( curve, frame ) {
  1990. return curve.values[ frame ] !== undefined;
  1991. }
  1992. // parse an FBX file in ASCII format
  1993. function TextParser() {}
  1994. Object.assign( TextParser.prototype, {
  1995. getPrevNode: function () {
  1996. return this.nodeStack[ this.currentIndent - 2 ];
  1997. },
  1998. getCurrentNode: function () {
  1999. return this.nodeStack[ this.currentIndent - 1 ];
  2000. },
  2001. getCurrentProp: function () {
  2002. return this.currentProp;
  2003. },
  2004. pushStack: function ( node ) {
  2005. this.nodeStack.push( node );
  2006. this.currentIndent += 1;
  2007. },
  2008. popStack: function () {
  2009. this.nodeStack.pop();
  2010. this.currentIndent -= 1;
  2011. },
  2012. setCurrentProp: function ( val, name ) {
  2013. this.currentProp = val;
  2014. this.currentPropName = name;
  2015. },
  2016. parse: function ( text ) {
  2017. this.currentIndent = 0;
  2018. this.allNodes = new FBXTree();
  2019. this.nodeStack = [];
  2020. this.currentProp = [];
  2021. this.currentPropName = '';
  2022. var split = text.split( '\n' );
  2023. for ( var lineNum = 0, lineLength = split.length; lineNum < lineLength; lineNum ++ ) {
  2024. var l = split[ lineNum ];
  2025. // skip comment line
  2026. if ( l.match( /^[\s\t]*;/ ) ) {
  2027. continue;
  2028. }
  2029. // skip empty line
  2030. if ( l.match( /^[\s\t]*$/ ) ) {
  2031. continue;
  2032. }
  2033. // beginning of node
  2034. var beginningOfNodeExp = new RegExp( '^\\t{' + this.currentIndent + '}(\\w+):(.*){', '' );
  2035. var match = l.match( beginningOfNodeExp );
  2036. if ( match ) {
  2037. var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  2038. var nodeAttrs = match[ 2 ].split( ',' );
  2039. for ( var i = 0, l = nodeAttrs.length; i < l; i ++ ) {
  2040. nodeAttrs[ i ] = nodeAttrs[ i ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  2041. }
  2042. this.parseNodeBegin( l, nodeName, nodeAttrs || null );
  2043. continue;
  2044. }
  2045. // node's property
  2046. var propExp = new RegExp( '^\\t{' + ( this.currentIndent ) + '}(\\w+):[\\s\\t\\r\\n](.*)' );
  2047. var match = l.match( propExp );
  2048. if ( match ) {
  2049. var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  2050. var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  2051. // for special case: base64 image data follows "Content: ," line
  2052. // Content: ,
  2053. // "iVB..."
  2054. if ( propName === 'Content' && propValue === ',' ) {
  2055. propValue = split[ ++ lineNum ].replace( /"/g, '' ).replace( /,$/, '' ).trim();
  2056. }
  2057. this.parseNodeProperty( l, propName, propValue );
  2058. continue;
  2059. }
  2060. // end of node
  2061. var endOfNodeExp = new RegExp( '^\\t{' + ( this.currentIndent - 1 ) + '}}' );
  2062. if ( l.match( endOfNodeExp ) ) {
  2063. this.nodeEnd();
  2064. continue;
  2065. }
  2066. // large arrays are split over multiple lines terminated with a ',' character
  2067. // if this is encountered the line needs to be joined to the previous line
  2068. if ( l.match( /^[^\s\t}]/ ) ) {
  2069. this.parseNodePropertyContinued( l );
  2070. }
  2071. }
  2072. return this.allNodes;
  2073. },
  2074. parseNodeBegin: function ( line, nodeName, nodeAttrs ) {
  2075. var node = { 'name': nodeName, properties: {}, 'subNodes': {} };
  2076. var attrs = this.parseNodeAttr( nodeAttrs );
  2077. var currentNode = this.getCurrentNode();
  2078. // a top node
  2079. if ( this.currentIndent === 0 ) {
  2080. this.allNodes.add( nodeName, node );
  2081. } else { // a subnode
  2082. // if the subnode already exists, append it
  2083. if ( nodeName in currentNode.subNodes ) {
  2084. var tmp = currentNode.subNodes[ nodeName ];
  2085. if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) {
  2086. if ( attrs.id === '' ) {
  2087. currentNode.subNodes[ nodeName ] = [];
  2088. currentNode.subNodes[ nodeName ].push( tmp );
  2089. } else {
  2090. currentNode.subNodes[ nodeName ] = {};
  2091. currentNode.subNodes[ nodeName ][ tmp.id ] = tmp;
  2092. }
  2093. }
  2094. if ( attrs.id === '' ) {
  2095. currentNode.subNodes[ nodeName ].push( node );
  2096. } else {
  2097. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  2098. }
  2099. } else if ( typeof attrs.id === 'number' || attrs.id.match( /^\d+$/ ) ) {
  2100. currentNode.subNodes[ nodeName ] = {};
  2101. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  2102. } else {
  2103. currentNode.subNodes[ nodeName ] = node;
  2104. }
  2105. }
  2106. // for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
  2107. // NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" {
  2108. if ( nodeAttrs ) {
  2109. node.id = attrs.id;
  2110. node.attrName = attrs.name;
  2111. node.attrType = attrs.type;
  2112. }
  2113. this.pushStack( node );
  2114. },
  2115. parseNodeAttr: function ( attrs ) {
  2116. var id = attrs[ 0 ];
  2117. if ( attrs[ 0 ] !== '' ) {
  2118. id = parseInt( attrs[ 0 ] );
  2119. if ( isNaN( id ) ) {
  2120. id = attrs[ 0 ];
  2121. }
  2122. }
  2123. var name = '', type = '';
  2124. if ( attrs.length > 1 ) {
  2125. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  2126. type = attrs[ 2 ];
  2127. }
  2128. return { id: id, name: name, type: type };
  2129. },
  2130. parseNodeProperty: function ( line, propName, propValue ) {
  2131. var currentNode = this.getCurrentNode();
  2132. var parentName = currentNode.name;
  2133. // special case where the parent node is something like "Properties70"
  2134. // these children nodes must treated carefully
  2135. if ( parentName !== undefined ) {
  2136. var propMatch = parentName.match( /Properties(\d)+/ );
  2137. if ( propMatch ) {
  2138. this.parseNodeSpecialProperty( line, propName, propValue );
  2139. return;
  2140. }
  2141. }
  2142. // Connections
  2143. if ( propName === 'C' ) {
  2144. var connProps = propValue.split( ',' ).slice( 1 );
  2145. var from = parseInt( connProps[ 0 ] );
  2146. var to = parseInt( connProps[ 1 ] );
  2147. var rest = propValue.split( ',' ).slice( 3 );
  2148. rest = rest.map( function ( elem ) {
  2149. return elem.trim().replace( /^"/, '' );
  2150. } );
  2151. propName = 'connections';
  2152. propValue = [ from, to ];
  2153. append( propValue, rest );
  2154. if ( currentNode.properties[ propName ] === undefined ) {
  2155. currentNode.properties[ propName ] = [];
  2156. }
  2157. }
  2158. // Node
  2159. if ( propName === 'Node' ) {
  2160. var id = parseInt( propValue );
  2161. currentNode.properties.id = id;
  2162. currentNode.id = id;
  2163. }
  2164. // already exists in properties, then append this
  2165. if ( propName in currentNode.properties ) {
  2166. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  2167. currentNode.properties[ propName ].push( propValue );
  2168. } else {
  2169. currentNode.properties[ propName ] += propValue;
  2170. }
  2171. } else {
  2172. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  2173. currentNode.properties[ propName ].push( propValue );
  2174. } else {
  2175. currentNode.properties[ propName ] = propValue;
  2176. }
  2177. }
  2178. this.setCurrentProp( currentNode.properties, propName );
  2179. // convert string to array, unless it ends in ',' in which case more will be added to it
  2180. if ( propName === 'a' && propValue.slice( - 1 ) !== ',' ) {
  2181. currentNode.properties.a = parseNumberArray( propValue );
  2182. }
  2183. },
  2184. parseNodePropertyContinued: function ( line ) {
  2185. this.currentProp[ this.currentPropName ] += line;
  2186. // if the line doesn't end in ',' we have reached the end of the property value
  2187. // so convert the string to an array
  2188. if ( line.slice( - 1 ) !== ',' ) {
  2189. var currentNode = this.getCurrentNode();
  2190. currentNode.properties.a = parseNumberArray( currentNode.properties.a );
  2191. }
  2192. },
  2193. parseNodeSpecialProperty: function ( line, propName, propValue ) {
  2194. // split this
  2195. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  2196. // into array like below
  2197. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  2198. var props = propValue.split( '",' );
  2199. for ( var i = 0, l = props.length; i < l; i ++ ) {
  2200. props[ i ] = props[ i ].trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  2201. }
  2202. var innerPropName = props[ 0 ];
  2203. var innerPropType1 = props[ 1 ];
  2204. var innerPropType2 = props[ 2 ];
  2205. var innerPropFlag = props[ 3 ];
  2206. var innerPropValue = props[ 4 ];
  2207. /*
  2208. if ( innerPropValue === undefined ) {
  2209. innerPropValue = props[3];
  2210. }
  2211. */
  2212. // cast value to its type
  2213. switch ( innerPropType1 ) {
  2214. case 'int':
  2215. case 'enum':
  2216. case 'bool':
  2217. case 'ULongLong':
  2218. innerPropValue = parseInt( innerPropValue );
  2219. break;
  2220. case 'double':
  2221. case 'Number':
  2222. case 'FieldOfView':
  2223. innerPropValue = parseFloat( innerPropValue );
  2224. break;
  2225. case 'ColorRGB':
  2226. case 'Vector3D':
  2227. case 'Lcl_Translation':
  2228. case 'Lcl_Rotation':
  2229. case 'Lcl_Scaling':
  2230. innerPropValue = parseNumberArray( innerPropValue );
  2231. break;
  2232. }
  2233. // CAUTION: these props must append to parent's parent
  2234. this.getPrevNode().properties[ innerPropName ] = {
  2235. 'type': innerPropType1,
  2236. 'type2': innerPropType2,
  2237. 'flag': innerPropFlag,
  2238. 'value': innerPropValue
  2239. };
  2240. this.setCurrentProp( this.getPrevNode().properties, innerPropName );
  2241. },
  2242. nodeEnd: function () {
  2243. this.popStack();
  2244. },
  2245. isFlattenNode: function ( node ) {
  2246. return ( 'subNodes' in node && 'properties' in node ) ? true : false;
  2247. }
  2248. } );
  2249. // Parse an FBX file in Binary format
  2250. function BinaryParser() {}
  2251. Object.assign( BinaryParser.prototype, {
  2252. parse: function ( buffer ) {
  2253. var reader = new BinaryReader( buffer );
  2254. reader.skip( 23 ); // skip magic 23 bytes
  2255. var version = reader.getUint32();
  2256. console.log( 'THREE.FBXLoader: FBX binary version: ' + version );
  2257. var allNodes = new FBXTree();
  2258. while ( ! this.endOfContent( reader ) ) {
  2259. var node = this.parseNode( reader, version );
  2260. if ( node !== null ) allNodes.add( node.name, node );
  2261. }
  2262. return allNodes;
  2263. },
  2264. // Check if reader has reached the end of content.
  2265. endOfContent: function ( reader ) {
  2266. // footer size: 160bytes + 16-byte alignment padding
  2267. // - 16bytes: magic
  2268. // - padding til 16-byte alignment (at least 1byte?)
  2269. // (seems like some exporters embed fixed 15 or 16bytes?)
  2270. // - 4bytes: magic
  2271. // - 4bytes: version
  2272. // - 120bytes: zero
  2273. // - 16bytes: magic
  2274. if ( reader.size() % 16 === 0 ) {
  2275. return ( ( reader.getOffset() + 160 + 16 ) & ~ 0xf ) >= reader.size();
  2276. } else {
  2277. return reader.getOffset() + 160 + 16 >= reader.size();
  2278. }
  2279. },
  2280. parseNode: function ( reader, version ) {
  2281. // The first three data sizes depends on version.
  2282. var endOffset = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  2283. var numProperties = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  2284. // note: do not remove this even if you get a linter warning as it moves the buffer forward
  2285. var propertyListLen = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  2286. var nameLen = reader.getUint8();
  2287. var name = reader.getString( nameLen );
  2288. // Regards this node as NULL-record if endOffset is zero
  2289. if ( endOffset === 0 ) return null;
  2290. var propertyList = [];
  2291. for ( var i = 0; i < numProperties; i ++ ) {
  2292. propertyList.push( this.parseProperty( reader ) );
  2293. }
  2294. // Regards the first three elements in propertyList as id, attrName, and attrType
  2295. var id = propertyList.length > 0 ? propertyList[ 0 ] : '';
  2296. var attrName = propertyList.length > 1 ? propertyList[ 1 ] : '';
  2297. var attrType = propertyList.length > 2 ? propertyList[ 2 ] : '';
  2298. var subNodes = {};
  2299. var properties = {};
  2300. var isSingleProperty = false;
  2301. // check if this node represents just a single property
  2302. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  2303. if ( numProperties === 1 && reader.getOffset() === endOffset ) {
  2304. isSingleProperty = true;
  2305. }
  2306. while ( endOffset > reader.getOffset() ) {
  2307. var node = this.parseNode( reader, version );
  2308. if ( node === null ) continue;
  2309. // special case: child node is single property
  2310. if ( node.singleProperty === true ) {
  2311. var value = node.propertyList[ 0 ];
  2312. if ( Array.isArray( value ) ) {
  2313. node.properties[ node.name ] = node.propertyList[ 0 ];
  2314. subNodes[ node.name ] = node;
  2315. node.properties.a = value;
  2316. } else {
  2317. properties[ node.name ] = value;
  2318. }
  2319. continue;
  2320. }
  2321. // parse connections
  2322. if ( name === 'Connections' && node.name === 'C' ) {
  2323. var array = [];
  2324. for ( var i = 1, il = node.propertyList.length; i < il; i ++ ) {
  2325. array[ i - 1 ] = node.propertyList[ i ];
  2326. }
  2327. if ( properties.connections === undefined ) {
  2328. properties.connections = [];
  2329. }
  2330. properties.connections.push( array );
  2331. continue;
  2332. }
  2333. // special case: child node is Properties\d+
  2334. // move child node's properties to this node.
  2335. if ( node.name.match( /^Properties\d+$/ ) ) {
  2336. var keys = Object.keys( node.properties );
  2337. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  2338. var key = keys[ i ];
  2339. properties[ key ] = node.properties[ key ];
  2340. }
  2341. continue;
  2342. }
  2343. // parse 'properties70'
  2344. if ( name.match( /^Properties\d+$/ ) && node.name === 'P' ) {
  2345. var innerPropName = node.propertyList[ 0 ];
  2346. var innerPropType1 = node.propertyList[ 1 ];
  2347. var innerPropType2 = node.propertyList[ 2 ];
  2348. var innerPropFlag = node.propertyList[ 3 ];
  2349. var innerPropValue;
  2350. if ( innerPropName.indexOf( 'Lcl ' ) === 0 ) innerPropName = innerPropName.replace( 'Lcl ', 'Lcl_' );
  2351. if ( innerPropType1.indexOf( 'Lcl ' ) === 0 ) innerPropType1 = innerPropType1.replace( 'Lcl ', 'Lcl_' );
  2352. if ( innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' || innerPropType1 === 'Vector3D' || innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  2353. innerPropValue = [
  2354. node.propertyList[ 4 ],
  2355. node.propertyList[ 5 ],
  2356. node.propertyList[ 6 ]
  2357. ];
  2358. } else {
  2359. innerPropValue = node.propertyList[ 4 ];
  2360. }
  2361. // this will be copied to parent, see above
  2362. properties[ innerPropName ] = {
  2363. 'type': innerPropType1,
  2364. 'type2': innerPropType2,
  2365. 'flag': innerPropFlag,
  2366. 'value': innerPropValue
  2367. };
  2368. continue;
  2369. }
  2370. if ( subNodes[ node.name ] === undefined ) {
  2371. if ( typeof node.id === 'number' ) {
  2372. subNodes[ node.name ] = {};
  2373. subNodes[ node.name ][ node.id ] = node;
  2374. } else {
  2375. subNodes[ node.name ] = node;
  2376. }
  2377. } else {
  2378. if ( node.id === '' ) {
  2379. if ( ! Array.isArray( subNodes[ node.name ] ) ) {
  2380. subNodes[ node.name ] = [ subNodes[ node.name ] ];
  2381. }
  2382. subNodes[ node.name ].push( node );
  2383. } else {
  2384. if ( subNodes[ node.name ][ node.id ] === undefined ) {
  2385. subNodes[ node.name ][ node.id ] = node;
  2386. } else {
  2387. // conflict id. irregular?
  2388. if ( ! Array.isArray( subNodes[ node.name ][ node.id ] ) ) {
  2389. subNodes[ node.name ][ node.id ] = [ subNodes[ node.name ][ node.id ] ];
  2390. }
  2391. subNodes[ node.name ][ node.id ].push( node );
  2392. }
  2393. }
  2394. }
  2395. }
  2396. return {
  2397. singleProperty: isSingleProperty,
  2398. id: id,
  2399. attrName: attrName,
  2400. attrType: attrType,
  2401. name: name,
  2402. properties: properties,
  2403. propertyList: propertyList, // raw property list used by parent
  2404. subNodes: subNodes
  2405. };
  2406. },
  2407. parseProperty: function ( reader ) {
  2408. var type = reader.getChar();
  2409. switch ( type ) {
  2410. case 'C':
  2411. return reader.getBoolean();
  2412. case 'D':
  2413. return reader.getFloat64();
  2414. case 'F':
  2415. return reader.getFloat32();
  2416. case 'I':
  2417. return reader.getInt32();
  2418. case 'L':
  2419. return reader.getInt64();
  2420. case 'R':
  2421. var length = reader.getUint32();
  2422. return reader.getArrayBuffer( length );
  2423. case 'S':
  2424. var length = reader.getUint32();
  2425. return reader.getString( length );
  2426. case 'Y':
  2427. return reader.getInt16();
  2428. case 'b':
  2429. case 'c':
  2430. case 'd':
  2431. case 'f':
  2432. case 'i':
  2433. case 'l':
  2434. var arrayLength = reader.getUint32();
  2435. var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  2436. var compressedLength = reader.getUint32();
  2437. if ( encoding === 0 ) {
  2438. switch ( type ) {
  2439. case 'b':
  2440. case 'c':
  2441. return reader.getBooleanArray( arrayLength );
  2442. case 'd':
  2443. return reader.getFloat64Array( arrayLength );
  2444. case 'f':
  2445. return reader.getFloat32Array( arrayLength );
  2446. case 'i':
  2447. return reader.getInt32Array( arrayLength );
  2448. case 'l':
  2449. return reader.getInt64Array( arrayLength );
  2450. }
  2451. }
  2452. if ( window.Zlib === undefined ) {
  2453. throw new Error( 'THREE.FBXLoader: External library Inflate.min.js required, obtain or import from https://github.com/imaya/zlib.js' );
  2454. }
  2455. var inflate = new Zlib.Inflate( new Uint8Array( reader.getArrayBuffer( compressedLength ) ) ); // eslint-disable-line no-undef
  2456. var reader2 = new BinaryReader( inflate.decompress().buffer );
  2457. switch ( type ) {
  2458. case 'b':
  2459. case 'c':
  2460. return reader2.getBooleanArray( arrayLength );
  2461. case 'd':
  2462. return reader2.getFloat64Array( arrayLength );
  2463. case 'f':
  2464. return reader2.getFloat32Array( arrayLength );
  2465. case 'i':
  2466. return reader2.getInt32Array( arrayLength );
  2467. case 'l':
  2468. return reader2.getInt64Array( arrayLength );
  2469. }
  2470. default:
  2471. throw new Error( 'THREE.FBXLoader: Unknown property type ' + type );
  2472. }
  2473. }
  2474. } );
  2475. function BinaryReader( buffer, littleEndian ) {
  2476. this.dv = new DataView( buffer );
  2477. this.offset = 0;
  2478. this.littleEndian = ( littleEndian !== undefined ) ? littleEndian : true;
  2479. }
  2480. Object.assign( BinaryReader.prototype, {
  2481. getOffset: function () {
  2482. return this.offset;
  2483. },
  2484. size: function () {
  2485. return this.dv.buffer.byteLength;
  2486. },
  2487. skip: function ( length ) {
  2488. this.offset += length;
  2489. },
  2490. // seems like true/false representation depends on exporter.
  2491. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  2492. // then sees LSB.
  2493. getBoolean: function () {
  2494. return ( this.getUint8() & 1 ) === 1;
  2495. },
  2496. getBooleanArray: function ( size ) {
  2497. var a = [];
  2498. for ( var i = 0; i < size; i ++ ) {
  2499. a.push( this.getBoolean() );
  2500. }
  2501. return a;
  2502. },
  2503. getInt8: function () {
  2504. var value = this.dv.getInt8( this.offset );
  2505. this.offset += 1;
  2506. return value;
  2507. },
  2508. getInt8Array: function ( size ) {
  2509. var a = [];
  2510. for ( var i = 0; i < size; i ++ ) {
  2511. a.push( this.getInt8() );
  2512. }
  2513. return a;
  2514. },
  2515. getUint8: function () {
  2516. var value = this.dv.getUint8( this.offset );
  2517. this.offset += 1;
  2518. return value;
  2519. },
  2520. getUint8Array: function ( size ) {
  2521. var a = [];
  2522. for ( var i = 0; i < size; i ++ ) {
  2523. a.push( this.getUint8() );
  2524. }
  2525. return a;
  2526. },
  2527. getInt16: function () {
  2528. var value = this.dv.getInt16( this.offset, this.littleEndian );
  2529. this.offset += 2;
  2530. return value;
  2531. },
  2532. getInt16Array: function ( size ) {
  2533. var a = [];
  2534. for ( var i = 0; i < size; i ++ ) {
  2535. a.push( this.getInt16() );
  2536. }
  2537. return a;
  2538. },
  2539. getUint16: function () {
  2540. var value = this.dv.getUint16( this.offset, this.littleEndian );
  2541. this.offset += 2;
  2542. return value;
  2543. },
  2544. getUint16Array: function ( size ) {
  2545. var a = [];
  2546. for ( var i = 0; i < size; i ++ ) {
  2547. a.push( this.getUint16() );
  2548. }
  2549. return a;
  2550. },
  2551. getInt32: function () {
  2552. var value = this.dv.getInt32( this.offset, this.littleEndian );
  2553. this.offset += 4;
  2554. return value;
  2555. },
  2556. getInt32Array: function ( size ) {
  2557. var a = [];
  2558. for ( var i = 0; i < size; i ++ ) {
  2559. a.push( this.getInt32() );
  2560. }
  2561. return a;
  2562. },
  2563. getUint32: function () {
  2564. var value = this.dv.getUint32( this.offset, this.littleEndian );
  2565. this.offset += 4;
  2566. return value;
  2567. },
  2568. getUint32Array: function ( size ) {
  2569. var a = [];
  2570. for ( var i = 0; i < size; i ++ ) {
  2571. a.push( this.getUint32() );
  2572. }
  2573. return a;
  2574. },
  2575. // JavaScript doesn't support 64-bit integer so calculate this here
  2576. // 1 << 32 will return 1 so using multiply operation instead here.
  2577. // There's a possibility that this method returns wrong value if the value
  2578. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  2579. // TODO: safely handle 64-bit integer
  2580. getInt64: function () {
  2581. var low, high;
  2582. if ( this.littleEndian ) {
  2583. low = this.getUint32();
  2584. high = this.getUint32();
  2585. } else {
  2586. high = this.getUint32();
  2587. low = this.getUint32();
  2588. }
  2589. // calculate negative value
  2590. if ( high & 0x80000000 ) {
  2591. high = ~ high & 0xFFFFFFFF;
  2592. low = ~ low & 0xFFFFFFFF;
  2593. if ( low === 0xFFFFFFFF ) high = ( high + 1 ) & 0xFFFFFFFF;
  2594. low = ( low + 1 ) & 0xFFFFFFFF;
  2595. return - ( high * 0x100000000 + low );
  2596. }
  2597. return high * 0x100000000 + low;
  2598. },
  2599. getInt64Array: function ( size ) {
  2600. var a = [];
  2601. for ( var i = 0; i < size; i ++ ) {
  2602. a.push( this.getInt64() );
  2603. }
  2604. return a;
  2605. },
  2606. // Note: see getInt64() comment
  2607. getUint64: function () {
  2608. var low, high;
  2609. if ( this.littleEndian ) {
  2610. low = this.getUint32();
  2611. high = this.getUint32();
  2612. } else {
  2613. high = this.getUint32();
  2614. low = this.getUint32();
  2615. }
  2616. return high * 0x100000000 + low;
  2617. },
  2618. getUint64Array: function ( size ) {
  2619. var a = [];
  2620. for ( var i = 0; i < size; i ++ ) {
  2621. a.push( this.getUint64() );
  2622. }
  2623. return a;
  2624. },
  2625. getFloat32: function () {
  2626. var value = this.dv.getFloat32( this.offset, this.littleEndian );
  2627. this.offset += 4;
  2628. return value;
  2629. },
  2630. getFloat32Array: function ( size ) {
  2631. var a = [];
  2632. for ( var i = 0; i < size; i ++ ) {
  2633. a.push( this.getFloat32() );
  2634. }
  2635. return a;
  2636. },
  2637. getFloat64: function () {
  2638. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  2639. this.offset += 8;
  2640. return value;
  2641. },
  2642. getFloat64Array: function ( size ) {
  2643. var a = [];
  2644. for ( var i = 0; i < size; i ++ ) {
  2645. a.push( this.getFloat64() );
  2646. }
  2647. return a;
  2648. },
  2649. getArrayBuffer: function ( size ) {
  2650. var value = this.dv.buffer.slice( this.offset, this.offset + size );
  2651. this.offset += size;
  2652. return value;
  2653. },
  2654. getChar: function () {
  2655. return String.fromCharCode( this.getUint8() );
  2656. },
  2657. getString: function ( size ) {
  2658. var s = '';
  2659. while ( size > 0 ) {
  2660. var value = this.getUint8();
  2661. size --;
  2662. if ( value === 0 ) break;
  2663. s += String.fromCharCode( value );
  2664. }
  2665. // Manage UTF8 encoding
  2666. s = decodeURIComponent( escape( s ) );
  2667. this.skip( size );
  2668. return s;
  2669. }
  2670. } );
  2671. // FBXTree holds a representation of the FBX data, returned by the TextParser ( FBX ASCII format)
  2672. // and BinaryParser( FBX Binary format)
  2673. function FBXTree() {}
  2674. Object.assign( FBXTree.prototype, {
  2675. add: function ( key, val ) {
  2676. this[ key ] = val;
  2677. },
  2678. } );
  2679. function isFbxFormatBinary( buffer ) {
  2680. var CORRECT = 'Kaydara FBX Binary \0';
  2681. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString( buffer, 0, CORRECT.length );
  2682. }
  2683. function isFbxFormatASCII( text ) {
  2684. var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  2685. var cursor = 0;
  2686. function read( offset ) {
  2687. var result = text[ offset - 1 ];
  2688. text = text.slice( cursor + offset );
  2689. cursor ++;
  2690. return result;
  2691. }
  2692. for ( var i = 0; i < CORRECT.length; ++ i ) {
  2693. var num = read( 1 );
  2694. if ( num === CORRECT[ i ] ) {
  2695. return false;
  2696. }
  2697. }
  2698. return true;
  2699. }
  2700. function getFbxVersion( text ) {
  2701. var versionRegExp = /FBXVersion: (\d+)/;
  2702. var match = text.match( versionRegExp );
  2703. if ( match ) {
  2704. var version = parseInt( match[ 1 ] );
  2705. return version;
  2706. }
  2707. throw new Error( 'THREE.FBXLoader: Cannot find the version number for the file given.' );
  2708. }
  2709. // Converts FBX ticks into real time seconds.
  2710. function convertFBXTimeToSeconds( time ) {
  2711. return time / 46186158000;
  2712. }
  2713. // Parses comma separated list of numbers and returns them an array.
  2714. // Used internally by the TextParser
  2715. function parseNumberArray( value ) {
  2716. var array = value.split( ',' );
  2717. for ( var i = 0, l = array.length; i < l; i ++ ) {
  2718. array[ i ] = parseFloat( array[ i ] );
  2719. }
  2720. return array;
  2721. }
  2722. function parseVector3( property ) {
  2723. return new THREE.Vector3().fromArray( property.value );
  2724. }
  2725. function parseColor( property ) {
  2726. return new THREE.Color().fromArray( property.value );
  2727. }
  2728. // Converts ArrayBuffer to String.
  2729. function convertArrayBufferToString( buffer, from, to ) {
  2730. if ( from === undefined ) from = 0;
  2731. if ( to === undefined ) to = buffer.byteLength;
  2732. var array = new Uint8Array( buffer, from, to );
  2733. if ( window.TextDecoder !== undefined ) {
  2734. return new TextDecoder().decode( array );
  2735. }
  2736. var s = '';
  2737. for ( var i = 0, il = array.length; i < il; i ++ ) {
  2738. s += String.fromCharCode( array[ i ] );
  2739. }
  2740. return s;
  2741. }
  2742. function findIndex( array, func ) {
  2743. for ( var i = 0, l = array.length; i < l; i ++ ) {
  2744. if ( func( array[ i ] ) ) return i;
  2745. }
  2746. return - 1;
  2747. }
  2748. function append( a, b ) {
  2749. for ( var i = 0, j = a.length, l = b.length; i < l; i ++, j ++ ) {
  2750. a[ j ] = b[ i ];
  2751. }
  2752. }
  2753. function slice( a, b, from, to ) {
  2754. for ( var i = from, j = 0; i < to; i ++, j ++ ) {
  2755. a[ j ] = b[ i ];
  2756. }
  2757. return a;
  2758. }
  2759. } )();