FBXLoader.js 80 KB

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