FBXLoader.js 100 KB

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