FBXLoader.js 88 KB

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