FBXLoader.js 97 KB

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