FBXLoader.js 99 KB

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