FBXLoader.js 85 KB

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