FBXLoader.js 90 KB

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