FBXLoader.js 97 KB

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