FBXLoader.js 83 KB

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