FBXLoader.js 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348
  1. /**
  2. * @author Kyle-Larson https://github.com/Kyle-Larson
  3. * @author Takahiro https://github.com/takahirox
  4. *
  5. * Loader loads FBX file and generates Group representing FBX scene.
  6. * Requires FBX file to be >= 7.0 and in ASCII or to be any version in Binary format.
  7. *
  8. * Supports:
  9. * Mesh Generation (Positional Data)
  10. * Normal Data (Per Vertex Drawing Instance)
  11. * UV Data (Per Vertex Drawing Instance)
  12. * Skinning
  13. * Animation
  14. * - Separated Animations based on stacks.
  15. * - Skeletal & Non-Skeletal Animations
  16. * NURBS (Open, Closed and Periodic forms)
  17. *
  18. * Needs Support:
  19. * Indexed Buffers
  20. * PreRotation support.
  21. * Euler rotation order
  22. *
  23. * FBX format references:
  24. * https://wiki.blender.org/index.php/User:Mont29/Foundation/FBX_File_Structure
  25. *
  26. * Binary format specification:
  27. * https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  28. * https://wiki.rogiken.org/specifications/file-format/fbx/ (more detail but Japanese)
  29. */
  30. ( function () {
  31. THREE.FBXLoader = function ( manager ) {
  32. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  33. };
  34. Object.assign( THREE.FBXLoader.prototype, {
  35. load: function ( url, onLoad, onProgress, onError ) {
  36. var self = this;
  37. var resourceDirectory = THREE.Loader.prototype.extractUrlBase( url );
  38. var loader = new THREE.FileLoader( this.manager );
  39. loader.setResponseType( 'arraybuffer' );
  40. loader.load( url, function ( buffer ) {
  41. try {
  42. var scene = self.parse( buffer, resourceDirectory );
  43. onLoad( scene );
  44. } catch ( error ) {
  45. window.setTimeout( function () {
  46. if ( onError ) onError( error );
  47. self.manager.itemError( url );
  48. }, 0 );
  49. }
  50. }, onProgress, onError );
  51. },
  52. parse: function ( FBXBuffer, resourceDirectory ) {
  53. var FBXTree;
  54. if ( isFbxFormatBinary( FBXBuffer ) ) {
  55. FBXTree = new BinaryParser().parse( FBXBuffer );
  56. } else {
  57. var FBXText = convertArrayBufferToString( FBXBuffer );
  58. if ( ! isFbxFormatASCII( FBXText ) ) {
  59. throw new Error( 'THREE.FBXLoader: Unknown format.' );
  60. }
  61. if ( getFbxVersion( FBXText ) < 7000 ) {
  62. throw new Error( 'THREE.FBXLoader: FBX version not supported, FileVersion: ' + getFbxVersion( FBXText ) );
  63. }
  64. FBXTree = new TextParser().parse( FBXText );
  65. }
  66. console.log( FBXTree );
  67. var connections = parseConnections( FBXTree );
  68. var images = parseImages( FBXTree );
  69. var textures = parseTextures( FBXTree, new THREE.TextureLoader( this.manager ).setPath( resourceDirectory ), images, connections );
  70. var materials = parseMaterials( FBXTree, textures, connections );
  71. var deformers = parseDeformers( FBXTree, connections );
  72. var geometryMap = parseGeometries( FBXTree, connections, deformers );
  73. var sceneGraph = parseScene( FBXTree, connections, deformers, geometryMap, materials );
  74. return sceneGraph;
  75. }
  76. } );
  77. // Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry )
  78. // and details the connection type
  79. function parseConnections( FBXTree ) {
  80. var connectionMap = new Map();
  81. if ( 'Connections' in FBXTree ) {
  82. var connectionArray = FBXTree.Connections.properties.connections;
  83. for ( var connectionArrayIndex = 0, connectionArrayLength = connectionArray.length; connectionArrayIndex < connectionArrayLength; ++ connectionArrayIndex ) {
  84. var connection = connectionArray[ connectionArrayIndex ];
  85. if ( ! connectionMap.has( connection[ 0 ] ) ) {
  86. connectionMap.set( connection[ 0 ], {
  87. parents: [],
  88. children: []
  89. } );
  90. }
  91. var parentRelationship = { ID: connection[ 1 ], relationship: connection[ 2 ] };
  92. connectionMap.get( connection[ 0 ] ).parents.push( parentRelationship );
  93. if ( ! connectionMap.has( connection[ 1 ] ) ) {
  94. connectionMap.set( connection[ 1 ], {
  95. parents: [],
  96. children: []
  97. } );
  98. }
  99. var childRelationship = { ID: connection[ 0 ], relationship: connection[ 2 ] };
  100. connectionMap.get( connection[ 1 ] ).children.push( childRelationship );
  101. }
  102. }
  103. return connectionMap;
  104. }
  105. // Parses map of images referenced in FBXTree.Objects.subNodes.Video
  106. // Images can either be referenced externally or embedded in the file
  107. // These images are connected to textures in FBXTree.Objects.subNodes.Textures
  108. // via FBXTree.Connections. Note that images can be duplicated here, in which case only one
  109. // will will have a .Content field
  110. function parseImages( FBXTree ) {
  111. var imageMap = new Map();
  112. if ( 'Video' in FBXTree.Objects.subNodes ) {
  113. var videoNodes = FBXTree.Objects.subNodes.Video;
  114. for ( var nodeID in videoNodes ) {
  115. var videoNode = videoNodes[ nodeID ];
  116. // raw image data is in videoNode.properties.Content
  117. if ( 'Content' in videoNode.properties ) {
  118. var image = parseImage( videoNodes[ nodeID ] );
  119. imageMap.set( parseInt( nodeID ), image );
  120. }
  121. }
  122. }
  123. return imageMap;
  124. }
  125. // Parse embedded image data in FBXTree.Video.properties.Content
  126. function parseImage( videoNode ) {
  127. var content = videoNode.properties.Content;
  128. var fileName = videoNode.properties.RelativeFilename || videoNode.properties.Filename;
  129. var extension = fileName.slice( fileName.lastIndexOf( '.' ) + 1 ).toLowerCase();
  130. var type;
  131. switch ( extension ) {
  132. case 'bmp':
  133. type = 'image/bmp';
  134. break;
  135. case 'jpg':
  136. case 'jpeg':
  137. type = 'image/jpeg';
  138. break;
  139. case 'png':
  140. type = 'image/png';
  141. break;
  142. case 'tif':
  143. type = 'image/tiff';
  144. break;
  145. default:
  146. console.warn( 'FBXLoader: Image type "' + extension + '" is not supported.' );
  147. return;
  148. }
  149. if ( typeof content === 'string' ) {
  150. return 'data:' + type + ';base64,' + content;
  151. } else {
  152. var array = new Uint8Array( content );
  153. return window.URL.createObjectURL( new Blob( [ array ], { type: type } ) );
  154. }
  155. }
  156. // Parse nodes in FBXTree.Objects.subNodes.Texture
  157. // These contain details such as UV scaling, cropping, rotation etc and are connected
  158. // to images in FBXTree.Objects.subNodes.Video
  159. function parseTextures( FBXTree, loader, imageMap, connections ) {
  160. var textureMap = new Map();
  161. if ( 'Texture' in FBXTree.Objects.subNodes ) {
  162. var textureNodes = FBXTree.Objects.subNodes.Texture;
  163. for ( var nodeID in textureNodes ) {
  164. var texture = parseTexture( textureNodes[ nodeID ], loader, imageMap, connections );
  165. textureMap.set( parseInt( nodeID ), texture );
  166. }
  167. }
  168. return textureMap;
  169. }
  170. // Parse individual node in FBXTree.Objects.subNodes.Texture
  171. function parseTexture( textureNode, loader, imageMap, connections ) {
  172. var FBX_ID = textureNode.id;
  173. var name = textureNode.attrName;
  174. var fileName;
  175. var filePath = textureNode.properties.FileName;
  176. var relativeFilePath = textureNode.properties.RelativeFilename;
  177. var children = connections.get( FBX_ID ).children;
  178. if ( children !== undefined && children.length > 0 && imageMap.has( children[ 0 ].ID ) ) {
  179. fileName = imageMap.get( children[ 0 ].ID );
  180. } else if ( relativeFilePath !== undefined && relativeFilePath[ 0 ] !== '/' && relativeFilePath.match( /^[a-zA-Z]:/ ) === null ) {
  181. // use textureNode.properties.RelativeFilename
  182. // if it exists and it doesn't seem an absolute path
  183. fileName = relativeFilePath;
  184. } else {
  185. var split = filePath.split( /[\\\/]/ );
  186. if ( split.length > 0 ) {
  187. fileName = split[ split.length - 1 ];
  188. } else {
  189. fileName = filePath;
  190. }
  191. }
  192. var currentPath = loader.path;
  193. if ( fileName.indexOf( 'blob:' ) === 0 || fileName.indexOf( 'data:' ) === 0 ) {
  194. loader.setPath( undefined );
  195. }
  196. var texture = loader.load( fileName );
  197. texture.name = name;
  198. texture.FBX_ID = FBX_ID;
  199. var wrapModeU = textureNode.properties.WrapModeU;
  200. var wrapModeV = textureNode.properties.WrapModeV;
  201. var valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
  202. var valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
  203. // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
  204. // 0: repeat(default), 1: clamp
  205. texture.wrapS = valueU === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  206. texture.wrapT = valueV === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  207. if ( 'Scaling' in textureNode.properties ) {
  208. var values = textureNode.properties.Scaling.value;
  209. texture.repeat.x = values[ 0 ];
  210. texture.repeat.y = values[ 1 ];
  211. }
  212. loader.setPath( currentPath );
  213. return texture;
  214. }
  215. // Parse nodes in FBXTree.Objects.subNodes.Material
  216. function parseMaterials( FBXTree, textureMap, connections ) {
  217. var materialMap = new Map();
  218. if ( 'Material' in FBXTree.Objects.subNodes ) {
  219. var materialNodes = FBXTree.Objects.subNodes.Material;
  220. for ( var nodeID in materialNodes ) {
  221. var material = parseMaterial( materialNodes[ nodeID ], textureMap, connections );
  222. if ( material !== null ) materialMap.set( parseInt( nodeID ), material );
  223. }
  224. }
  225. return materialMap;
  226. }
  227. // Parse single node in FBXTree.Objects.subNodes.Material
  228. // Materials are connected to texture maps in FBXTree.Objects.subNodes.Textures
  229. // FBX format currently only supports Lambert and Phong shading models
  230. function parseMaterial( materialNode, textureMap, connections ) {
  231. var FBX_ID = materialNode.id;
  232. var name = materialNode.attrName;
  233. var type = materialNode.properties.ShadingModel;
  234. //Case where FBX wraps shading model in property object.
  235. if ( typeof type === 'object' ) {
  236. type = type.value;
  237. }
  238. // Ignore unused materials which don't have any connections.
  239. if ( ! connections.has( FBX_ID ) ) return null;
  240. var children = connections.get( FBX_ID ).children;
  241. var parameters = parseParameters( materialNode.properties, textureMap, children );
  242. var material;
  243. switch ( type.toLowerCase() ) {
  244. case 'phong':
  245. material = new THREE.MeshPhongMaterial();
  246. break;
  247. case 'lambert':
  248. material = new THREE.MeshLambertMaterial();
  249. break;
  250. default:
  251. console.warn( 'THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.', type );
  252. material = new THREE.MeshPhongMaterial( { color: 0x3300ff } );
  253. break;
  254. }
  255. material.setValues( parameters );
  256. material.name = name;
  257. return material;
  258. }
  259. // Parse FBX material and return parameters suitable for a three.js material
  260. // Also parse the texture map and return any textures associated with the material
  261. function parseParameters( properties, textureMap, childrenRelationships ) {
  262. var parameters = {};
  263. if ( properties.BumpFactor ) {
  264. parameters.bumpScale = properties.BumpFactor.value;
  265. }
  266. if ( properties.Diffuse ) {
  267. parameters.color = parseColor( properties.Diffuse );
  268. }
  269. if ( properties.DisplacementFactor ) {
  270. parameters.displacementScale = properties.DisplacementFactor.value;
  271. }
  272. if ( properties.ReflectionFactor ) {
  273. parameters.reflectivity = properties.ReflectionFactor.value;
  274. }
  275. if ( properties.Specular ) {
  276. parameters.specular = parseColor( properties.Specular );
  277. }
  278. if ( properties.Shininess ) {
  279. parameters.shininess = properties.Shininess.value;
  280. }
  281. if ( properties.Emissive ) {
  282. parameters.emissive = parseColor( properties.Emissive );
  283. }
  284. if ( properties.EmissiveFactor ) {
  285. parameters.emissiveIntensity = parseFloat( properties.EmissiveFactor.value );
  286. }
  287. if ( properties.Opacity ) {
  288. parameters.opacity = parseFloat( properties.Opacity.value );
  289. }
  290. if ( parameters.opacity < 1.0 ) {
  291. parameters.transparent = true;
  292. }
  293. for ( var childrenRelationshipsIndex = 0, childrenRelationshipsLength = childrenRelationships.length; childrenRelationshipsIndex < childrenRelationshipsLength; ++ childrenRelationshipsIndex ) {
  294. var relationship = childrenRelationships[ childrenRelationshipsIndex ];
  295. var type = relationship.relationship;
  296. switch ( type ) {
  297. case 'Bump':
  298. parameters.bumpMap = textureMap.get( relationship.ID );
  299. break;
  300. case 'DiffuseColor':
  301. parameters.map = textureMap.get( relationship.ID );
  302. break;
  303. case 'DisplacementColor':
  304. parameters.displacementMap = textureMap.get( relationship.ID );
  305. break;
  306. case 'EmissiveColor':
  307. parameters.emissiveMap = textureMap.get( relationship.ID );
  308. break;
  309. case 'NormalMap':
  310. parameters.normalMap = textureMap.get( relationship.ID );
  311. break;
  312. case 'ReflectionColor':
  313. parameters.envMap = textureMap.get( relationship.ID );
  314. parameters.envMap.mapping = THREE.EquirectangularReflectionMapping;
  315. break;
  316. case 'SpecularColor':
  317. parameters.specularMap = textureMap.get( relationship.ID );
  318. break;
  319. case 'TransparentColor':
  320. parameters.alphaMap = textureMap.get( relationship.ID );
  321. parameters.transparent = true;
  322. break;
  323. case 'AmbientColor':
  324. case 'ShininessExponent': // AKA glossiness map
  325. case 'SpecularFactor': // AKA specularLevel
  326. case 'VectorDisplacementColor': // NOTE: Seems to be a copy of DisplacementColor
  327. default:
  328. console.warn( 'THREE.FBXLoader: %s map is not supported in three.js, skipping texture.', type );
  329. break;
  330. }
  331. }
  332. return parameters;
  333. }
  334. // Parse nodes in FBXTree.Objects.subNodes.Deformer
  335. // Deformer node can contain skinning or Vertex Cache animation data, however only skinning is supported here
  336. // Generates map of Skeleton-like objects for use later when generating and binding skeletons.
  337. function parseDeformers( FBXTree, connections ) {
  338. var deformers = {};
  339. if ( 'Deformer' in FBXTree.Objects.subNodes ) {
  340. var DeformerNodes = FBXTree.Objects.subNodes.Deformer;
  341. for ( var nodeID in DeformerNodes ) {
  342. var deformerNode = DeformerNodes[ nodeID ];
  343. if ( deformerNode.attrType === 'Skin' ) {
  344. var conns = connections.get( parseInt( nodeID ) );
  345. var skeleton = parseSkeleton( conns, DeformerNodes );
  346. skeleton.FBX_ID = parseInt( nodeID );
  347. deformers[ nodeID ] = skeleton;
  348. }
  349. }
  350. }
  351. return deformers;
  352. }
  353. // Parse single nodes in FBXTree.Objects.subNodes.Deformer
  354. // Generates a "Skeleton Representation" of FBX nodes based on an FBX Skin Deformer's connections
  355. // and an object containing SubDeformer nodes.
  356. function parseSkeleton( connections, DeformerNodes ) {
  357. var subDeformers = {};
  358. var children = connections.children;
  359. for ( var i = 0, l = children.length; i < l; ++ i ) {
  360. var child = children[ i ];
  361. var subDeformerNode = DeformerNodes[ child.ID ];
  362. var subDeformer = {
  363. FBX_ID: child.ID,
  364. index: i,
  365. indices: [],
  366. weights: [],
  367. transform: new THREE.Matrix4().fromArray( subDeformerNode.subNodes.Transform.properties.a ),
  368. transformLink: new THREE.Matrix4().fromArray( subDeformerNode.subNodes.TransformLink.properties.a ),
  369. linkMode: subDeformerNode.properties.Mode
  370. };
  371. if ( 'Indexes' in subDeformerNode.subNodes ) {
  372. subDeformer.indices = subDeformerNode.subNodes.Indexes.properties.a;
  373. subDeformer.weights = subDeformerNode.subNodes.Weights.properties.a;
  374. }
  375. subDeformers[ child.ID ] = subDeformer;
  376. }
  377. return {
  378. map: subDeformers,
  379. bones: []
  380. };
  381. }
  382. // Parse nodes in FBXTree.Objects.subNodes.Geometry
  383. function parseGeometries( FBXTree, connections, deformers ) {
  384. var geometryMap = new Map();
  385. if ( 'Geometry' in FBXTree.Objects.subNodes ) {
  386. var geometryNodes = FBXTree.Objects.subNodes.Geometry;
  387. for ( var nodeID in geometryNodes ) {
  388. var relationships = connections.get( parseInt( nodeID ) );
  389. var geo = parseGeometry( geometryNodes[ nodeID ], relationships, deformers );
  390. geometryMap.set( parseInt( nodeID ), geo );
  391. }
  392. }
  393. return geometryMap;
  394. }
  395. // Parse single node in FBXTree.Objects.subNodes.Geometry
  396. function parseGeometry( geometryNode, relationships, deformers ) {
  397. switch ( geometryNode.attrType ) {
  398. case 'Mesh':
  399. return parseMeshGeometry( geometryNode, relationships, deformers );
  400. break;
  401. case 'NurbsCurve':
  402. return parseNurbsGeometry( geometryNode );
  403. break;
  404. }
  405. }
  406. // Parse single node mesh geometry in FBXTree.Objects.subNodes.Geometry
  407. function parseMeshGeometry( geometryNode, relationships, deformers ) {
  408. for ( var i = 0; i < relationships.children.length; ++ i ) {
  409. var deformer = deformers[ relationships.children[ i ].ID ];
  410. if ( deformer !== undefined ) break;
  411. }
  412. return genGeometry( geometryNode, deformer );
  413. }
  414. // Generate a THREE.BufferGeometry from a node in FBXTree.Objects.subNodes.Geometry
  415. function genGeometry( geometryNode, deformer ) {
  416. var subNodes = geometryNode.subNodes;
  417. var vertexBuffer = subNodes.Vertices.properties.a;
  418. var indexBuffer = subNodes.PolygonVertexIndex.properties.a;
  419. var vertexB = [];
  420. var normalB = [];
  421. var colorsB = [];
  422. var uvsB = [];
  423. var materialsB = [];
  424. var weightsB = [];
  425. var weightsIndicesB = [];
  426. if ( subNodes.LayerElementNormal ) {
  427. var normalInfo = getNormals( subNodes.LayerElementNormal[ 0 ] );
  428. var normalBuffer = normalInfo.buffer;
  429. // console.log( normalInfo )
  430. }
  431. if ( subNodes.LayerElementUV ) {
  432. var uvInfo = [];
  433. var i = 0;
  434. while ( subNodes.LayerElementUV[ i ] ) {
  435. uvInfo.push( getUVs( subNodes.LayerElementUV[ i ] ) );
  436. i ++;
  437. }
  438. }
  439. if ( subNodes.LayerElementColor ) {
  440. var colorInfo = getColors( subNodes.LayerElementColor[ 0 ] );
  441. var colorBuffer = colorInfo.buffer;
  442. }
  443. if ( subNodes.LayerElementMaterial ) {
  444. var materialInfo = getMaterials( subNodes.LayerElementMaterial[ 0 ] );
  445. }
  446. var weightTable = {};
  447. if ( deformer ) {
  448. var subDeformers = deformer.map;
  449. for ( var key in subDeformers ) {
  450. var subDeformer = subDeformers[ key ];
  451. var indices = subDeformer.indices;
  452. for ( var j = 0; j < indices.length; j ++ ) {
  453. var index = indices[ j ];
  454. var weight = subDeformer.weights[ j ];
  455. if ( weightTable[ index ] === undefined ) weightTable[ index ] = [];
  456. weightTable[ index ].push( {
  457. id: subDeformer.index,
  458. weight: weight
  459. } );
  460. }
  461. }
  462. }
  463. var faceVertexBuffer = [];
  464. var polygonIndex = 0;
  465. var faceLength = 0;
  466. var displayedWeightsWarning = false;
  467. var vertexPositionIndexes = [];
  468. var faceNormals = [];
  469. var faceColors = [];
  470. var faceUVs = [];
  471. var faceMaterials = [];
  472. var faceWeights = [];
  473. var faceWeightIndices = [];
  474. for ( var polygonVertexIndex = 0; polygonVertexIndex < indexBuffer.length; polygonVertexIndex ++ ) {
  475. var vertexIndex = indexBuffer[ polygonVertexIndex ];
  476. var endOfFace = false;
  477. // Face index and vertex index arrays are combined in a single array
  478. // A cube with quad faces looks like this:
  479. // PolygonVertexIndex: *24 {
  480. // 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
  481. // }
  482. // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3
  483. // to find index of last vertex multiply by -1 and subtract 1: -3 * - 1 - 1 = 2
  484. if ( vertexIndex < 0 ) {
  485. vertexIndex = vertexIndex ^ - 1; // equivalent to ( x * -1 ) - 1
  486. indexBuffer[ polygonVertexIndex ] = vertexIndex;
  487. endOfFace = true;
  488. }
  489. var weightIndices = [];
  490. var weights = [];
  491. vertexPositionIndexes.push( vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2 );
  492. if ( deformer ) {
  493. if ( weightTable[ vertexIndex ] !== undefined ) {
  494. var array = weightTable[ vertexIndex ];
  495. for ( var j = 0, jl = array.length; j < jl; j ++ ) {
  496. weights.push( array[ j ].weight );
  497. weightIndices.push( array[ j ].id );
  498. }
  499. }
  500. if ( weights.length > 4 ) {
  501. if ( ! displayedWeightsWarning ) {
  502. console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
  503. displayedWeightsWarning = true;
  504. }
  505. var WIndex = [ 0, 0, 0, 0 ];
  506. var Weight = [ 0, 0, 0, 0 ];
  507. weights.forEach( function ( weight, weightIndex ) {
  508. var currentWeight = weight;
  509. var currentIndex = weightIndices[ weightIndex ];
  510. Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) {
  511. if ( currentWeight > comparedWeight ) {
  512. comparedWeightArray[ comparedWeightIndex ] = currentWeight;
  513. currentWeight = comparedWeight;
  514. var tmp = WIndex[ comparedWeightIndex ];
  515. WIndex[ comparedWeightIndex ] = currentIndex;
  516. currentIndex = tmp;
  517. }
  518. } );
  519. } );
  520. weightIndices = WIndex;
  521. weights = Weight;
  522. }
  523. // if the weight array is shorter than 4 pad with 0s
  524. for ( var i = weights.length; i < 4; ++ i ) {
  525. weights[ i ] = 0;
  526. weightIndices[ i ] = 0;
  527. }
  528. for ( var i = 0; i < 4; ++ i ) {
  529. faceWeights.push( weights[ i ] )
  530. faceWeightIndices.push(weightIndices[ i ] )
  531. }
  532. }
  533. if ( normalInfo ) {
  534. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, normalInfo );
  535. faceNormals.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  536. }
  537. if ( uvInfo ) {
  538. for ( var i = 0; i < uvInfo.length; i ++ ) {
  539. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, uvInfo[ i ] );
  540. if( faceUVs[i] === undefined ) faceUVs[ i ] = [];
  541. faceUVs[ i ].push(
  542. data[ 0 ],
  543. data[ 1 ],
  544. );
  545. }
  546. }
  547. if ( colorInfo ) {
  548. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, colorInfo );
  549. vertex.color.fromArray( data );
  550. faceColors.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  551. }
  552. faceLength ++;
  553. if ( endOfFace ) {
  554. for ( var i = 2; i < faceLength; i ++ ) {
  555. vertexB.push(
  556. vertexBuffer[ vertexPositionIndexes[ 0 ] ],
  557. vertexBuffer[ vertexPositionIndexes[ 1 ] ],
  558. vertexBuffer[ vertexPositionIndexes[ 2 ] ],
  559. vertexBuffer[ vertexPositionIndexes[ ( i - 1 ) * 3 ] ],
  560. vertexBuffer[ vertexPositionIndexes[ ( i - 1 ) * 3 + 1 ] ],
  561. vertexBuffer[ vertexPositionIndexes[ ( i - 1 ) * 3 + 2 ] ],
  562. vertexBuffer[ vertexPositionIndexes[ i * 3 ] ],
  563. vertexBuffer[ vertexPositionIndexes[ i * 3 + 1 ] ],
  564. vertexBuffer[ vertexPositionIndexes[ i * 3 + 2 ] ]
  565. );
  566. }
  567. if ( deformer ) {
  568. for (var i = 2; i < faceLength; i++) {
  569. weightsB.push(
  570. faceWeights[0],
  571. faceWeights[1],
  572. faceWeights[2],
  573. faceWeights[3],
  574. faceWeights[(i - 1) * 4],
  575. faceWeights[(i - 1) * 4 + 1],
  576. faceWeights[(i - 1) * 4 + 2],
  577. faceWeights[(i - 1) * 4 + 3],
  578. faceWeights[i * 4],
  579. faceWeights[i * 4 + 1],
  580. faceWeights[i * 4 + 2],
  581. faceWeights[i * 4 + 3]
  582. );
  583. weightsIndicesB.push(
  584. faceWeightIndices[0],
  585. faceWeightIndices[1],
  586. faceWeightIndices[2],
  587. faceWeightIndices[3],
  588. faceWeightIndices[(i - 1) * 4],
  589. faceWeightIndices[(i - 1) * 4 + 1],
  590. faceWeightIndices[(i - 1) * 4 + 2],
  591. faceWeightIndices[(i - 1) * 4 + 3],
  592. faceWeightIndices[i * 4],
  593. faceWeightIndices[i * 4 + 1],
  594. faceWeightIndices[i * 4 + 2],
  595. faceWeightIndices[i * 4 + 3]
  596. );
  597. }
  598. }
  599. if ( normalInfo ) {
  600. for ( var i = 2; i < faceLength; i ++ ) {
  601. normalB.push(
  602. faceNormals[ 0 ],
  603. faceNormals[ 1 ],
  604. faceNormals[ 2 ],
  605. faceNormals[ ( i - 1 ) * 3 ],
  606. faceNormals[ ( i - 1 ) * 3 + 1 ],
  607. faceNormals[ ( i - 1 ) * 3 + 2 ],
  608. faceNormals[ i * 3 ],
  609. faceNormals[ i * 3 + 1 ],
  610. faceNormals[ i * 3 + 2 ]
  611. );
  612. }
  613. }
  614. if ( uvInfo ) {
  615. for (var j = 0; j < uvInfo.length; j++) {
  616. if ( uvsB[ j ] === undefined) uvsB[ j ] = [];
  617. for ( var i = 2; i < faceLength; i++ ) {
  618. uvsB[j].push(
  619. faceUVs[j][ 0],
  620. faceUVs[j][ 1],
  621. faceUVs[j][ ( i - 1 ) * 2 ],
  622. faceUVs[j][ ( i - 1 ) * 2 + 1 ],
  623. faceUVs[j][ i * 2 ],
  624. faceUVs[j][ i * 2 + 1 ],
  625. );
  626. }
  627. }
  628. }
  629. if ( colorInfo ) {
  630. for ( var i = 2; i < faceLength; i ++ ) {
  631. colorsB.push(
  632. faceColors[ 0 ],
  633. faceColors[ 1 ],
  634. faceColors[ 2 ],
  635. faceColors[ ( i - 1 ) * 3 ],
  636. faceColors[ ( i - 1 ) * 3 + 1 ],
  637. faceColors[ ( i - 1 ) * 3 + 2 ],
  638. faceColors[ i * 3 ],
  639. faceColors[ i * 3 + 1 ],
  640. faceColors[ i * 3 + 2 ]
  641. );
  642. }
  643. }
  644. if( materialInfo && materialInfo.mappingType !== 'AllSame' ) {
  645. var materialIndex = getData(polygonVertexIndex, polygonIndex, vertexIndex, materialInfo)[0];
  646. for (var i = 2; i < faceLength; i++) {
  647. materialsB.push(materialIndex, materialIndex, materialIndex);
  648. }
  649. }
  650. faceVertexBuffer = [];
  651. polygonIndex ++;
  652. endOfFace = false;
  653. vertexPositionIndexes = [];
  654. faceNormals = [];
  655. faceColors = [];
  656. faceUVs = [];
  657. faceMaterials = [];
  658. faceWeights = [];
  659. faceWeightIndices = [];
  660. faceLength = 0;
  661. }
  662. }
  663. var geo = new THREE.BufferGeometry();
  664. geo.name = geometryNode.name;
  665. geo.addAttribute( 'position', new THREE.Float32BufferAttribute( vertexB, 3 ) );
  666. if ( normalB.length > 0 ) {
  667. geo.addAttribute( 'normal', new THREE.Float32BufferAttribute( normalB, 3 ) );
  668. }
  669. if ( uvsB.length > 0 ) {
  670. for ( var i = 0; i < uvsB.length; i ++ ) {
  671. var name = 'uv' + ( i + 1 ).toString();
  672. if ( i == 0 ) {
  673. name = 'uv';
  674. }
  675. geo.addAttribute( name, new THREE.Float32BufferAttribute( uvsB[ i ], 2 ) );
  676. }
  677. }
  678. if ( colorsB.length > 0 ) {
  679. geo.addAttribute( 'color', new THREE.Float32BufferAttribute( colorB, 3 ) );
  680. }
  681. if ( deformer ) {
  682. geo.addAttribute( 'skinIndex', new THREE.Float32BufferAttribute( weightsIndicesB, 4 ) );
  683. geo.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( weightsB, 4 ) );
  684. geo.FBX_Deformer = deformer;
  685. }
  686. if ( materialInfo && materialInfo.mappingType !== 'AllSame' ) {
  687. // Convert the material indices of each vertex into rendering groups on the geometry.
  688. var materialIndexBuffer = materialsB;
  689. var prevMaterialIndex = materialIndexBuffer[ 0 ];
  690. var startIndex = 0;
  691. for ( var i = 0; i < materialIndexBuffer.length; ++ i ) {
  692. if ( materialIndexBuffer[ i ] !== prevMaterialIndex ) {
  693. geo.addGroup( startIndex, i - startIndex, prevMaterialIndex );
  694. prevMaterialIndex = materialIndexBuffer[ i ];
  695. startIndex = i;
  696. }
  697. }
  698. // the loop above doesn't add the last group, do that here.
  699. if ( geo.groups.length > 0 ) {
  700. var lastGroup = geo.groups[ geo.groups.length - 1 ];
  701. var lastIndex = lastGroup.start + lastGroup.count;
  702. if ( lastIndex !== materialIndexBuffer.length ) {
  703. geo.addGroup( lastIndex, materialIndexBuffer.length - lastIndex, prevMaterialIndex );
  704. }
  705. }
  706. // case where there are multiple materials but the whole geometry is only
  707. // using one of them
  708. if ( geo.groups.length === 0 ) {
  709. geo.addGroup( 0, materialIndexBuffer.length, materialIndexBuffer[ 0 ] );
  710. }
  711. }
  712. return geo;
  713. }
  714. // Parse normal from FBXTree.Objects.subNodes.Geometry.subNodes.LayerElementNormal if it exists
  715. function getNormals( NormalNode ) {
  716. var mappingType = NormalNode.properties.MappingInformationType;
  717. var referenceType = NormalNode.properties.ReferenceInformationType;
  718. var buffer = NormalNode.subNodes.Normals.properties.a;
  719. var indexBuffer = [];
  720. if ( referenceType === 'IndexToDirect' ) {
  721. if ( 'NormalIndex' in NormalNode.subNodes ) {
  722. indexBuffer = NormalNode.subNodes.NormalIndex.properties.a;
  723. } else if ( 'NormalsIndex' in NormalNode.subNodes ) {
  724. indexBuffer = NormalNode.subNodes.NormalsIndex.properties.a;
  725. }
  726. }
  727. return {
  728. dataSize: 3,
  729. buffer: buffer,
  730. indices: indexBuffer,
  731. mappingType: mappingType,
  732. referenceType: referenceType
  733. };
  734. }
  735. // Parse UVs from FBXTree.Objects.subNodes.Geometry.subNodes.LayerElementUV if it exists
  736. function getUVs( UVNode ) {
  737. var mappingType = UVNode.properties.MappingInformationType;
  738. var referenceType = UVNode.properties.ReferenceInformationType;
  739. var buffer = UVNode.subNodes.UV.properties.a;
  740. var indexBuffer = [];
  741. if ( referenceType === 'IndexToDirect' ) {
  742. indexBuffer = UVNode.subNodes.UVIndex.properties.a;
  743. }
  744. return {
  745. dataSize: 2,
  746. buffer: buffer,
  747. indices: indexBuffer,
  748. mappingType: mappingType,
  749. referenceType: referenceType
  750. };
  751. }
  752. // Parse Vertex Colors from FBXTree.Objects.subNodes.Geometry.subNodes.LayerElementColor if it exists
  753. function getColors( ColorNode ) {
  754. var mappingType = ColorNode.properties.MappingInformationType;
  755. var referenceType = ColorNode.properties.ReferenceInformationType;
  756. var buffer = ColorNode.subNodes.Colors.properties.a;
  757. var indexBuffer = [];
  758. if ( referenceType === 'IndexToDirect' ) {
  759. indexBuffer = ColorNode.subNodes.ColorIndex.properties.a;
  760. }
  761. return {
  762. dataSize: 4,
  763. buffer: buffer,
  764. indices: indexBuffer,
  765. mappingType: mappingType,
  766. referenceType: referenceType
  767. };
  768. }
  769. // Parse mapping and material data in FBXTree.Objects.subNodes.Geometry.subNodes.LayerElementMaterial if it exists
  770. function getMaterials( MaterialNode ) {
  771. var mappingType = MaterialNode.properties.MappingInformationType;
  772. var referenceType = MaterialNode.properties.ReferenceInformationType;
  773. if ( mappingType === 'NoMappingInformation' ) {
  774. return {
  775. dataSize: 1,
  776. buffer: [ 0 ],
  777. indices: [ 0 ],
  778. mappingType: 'AllSame',
  779. referenceType: referenceType
  780. };
  781. }
  782. var materialIndexBuffer = MaterialNode.subNodes.Materials.properties.a;
  783. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  784. // we expect.So we create an intermediate buffer that points to the index in the buffer,
  785. // for conforming with the other functions we've written for other data.
  786. var materialIndices = [];
  787. for ( var materialIndexBufferIndex = 0, materialIndexBufferLength = materialIndexBuffer.length; materialIndexBufferIndex < materialIndexBufferLength; ++ materialIndexBufferIndex ) {
  788. materialIndices.push( materialIndexBufferIndex );
  789. }
  790. return {
  791. dataSize: 1,
  792. buffer: materialIndexBuffer,
  793. indices: materialIndices,
  794. mappingType: mappingType,
  795. referenceType: referenceType
  796. };
  797. }
  798. // Functions use the infoObject and given indices to return value array of geometry.
  799. // infoObject can be materialInfo, normalInfo, UVInfo or colorInfo
  800. // polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  801. // polygonIndex - Index of polygon in geometry.
  802. // vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  803. var dataArray = [];
  804. var GetData = {
  805. ByPolygonVertex: {
  806. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  807. var from = ( polygonVertexIndex * infoObject.dataSize );
  808. var to = ( polygonVertexIndex * infoObject.dataSize ) + infoObject.dataSize;
  809. // return infoObject.buffer.slice( from, to );
  810. return slice( dataArray, infoObject.buffer, from, to );
  811. },
  812. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  813. var index = infoObject.indices[ polygonVertexIndex ];
  814. var from = ( index * infoObject.dataSize );
  815. var to = ( index * infoObject.dataSize ) + infoObject.dataSize;
  816. // return infoObject.buffer.slice( from, to );
  817. return slice( dataArray, infoObject.buffer, from, to );
  818. }
  819. },
  820. ByPolygon: {
  821. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  822. var from = polygonIndex * infoObject.dataSize;
  823. var to = polygonIndex * infoObject.dataSize + infoObject.dataSize;
  824. // return infoObject.buffer.slice( from, to );
  825. return slice( dataArray, infoObject.buffer, from, to );
  826. },
  827. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  828. var index = infoObject.indices[ polygonIndex ];
  829. var from = index * infoObject.dataSize;
  830. var to = index * infoObject.dataSize + infoObject.dataSize;
  831. // return infoObject.buffer.slice( from, to );
  832. return slice( dataArray, infoObject.buffer, from, to );
  833. }
  834. },
  835. ByVertice: {
  836. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  837. var from = ( vertexIndex * infoObject.dataSize );
  838. var to = ( vertexIndex * infoObject.dataSize ) + infoObject.dataSize;
  839. // return infoObject.buffer.slice( from, to );
  840. return slice( dataArray, infoObject.buffer, from, to );
  841. }
  842. },
  843. AllSame: {
  844. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  845. var from = infoObject.indices[ 0 ] * infoObject.dataSize;
  846. var to = infoObject.indices[ 0 ] * infoObject.dataSize + infoObject.dataSize;
  847. // return infoObject.buffer.slice( from, to );
  848. return slice( dataArray, infoObject.buffer, from, to );
  849. }
  850. }
  851. };
  852. function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  853. return GetData[ infoObject.mappingType ][ infoObject.referenceType ]( polygonVertexIndex, polygonIndex, vertexIndex, infoObject );
  854. }
  855. // Generate a NurbGeometry from a node in FBXTree.Objects.subNodes.Geometry
  856. function parseNurbsGeometry( geometryNode ) {
  857. if ( THREE.NURBSCurve === undefined ) {
  858. console.error( 'THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.' );
  859. return new THREE.BufferGeometry();
  860. }
  861. var order = parseInt( geometryNode.properties.Order );
  862. if ( isNaN( order ) ) {
  863. console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geometryNode.properties.Order, geometryNode.id );
  864. return new THREE.BufferGeometry();
  865. }
  866. var degree = order - 1;
  867. var knots = geometryNode.subNodes.KnotVector.properties.a;
  868. var controlPoints = [];
  869. var pointsValues = geometryNode.subNodes.Points.properties.a;
  870. for ( var i = 0, l = pointsValues.length; i < l; i += 4 ) {
  871. controlPoints.push( new THREE.Vector4().fromArray( pointsValues, i ) );
  872. }
  873. var startKnot, endKnot;
  874. if ( geometryNode.properties.Form === 'Closed' ) {
  875. controlPoints.push( controlPoints[ 0 ] );
  876. } else if ( geometryNode.properties.Form === 'Periodic' ) {
  877. startKnot = degree;
  878. endKnot = knots.length - 1 - startKnot;
  879. for ( var i = 0; i < degree; ++ i ) {
  880. controlPoints.push( controlPoints[ i ] );
  881. }
  882. }
  883. var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
  884. var vertices = curve.getPoints( controlPoints.length * 7 );
  885. var positions = new Float32Array( vertices.length * 3 );
  886. for ( var i = 0, l = vertices.length; i < l; ++ i ) {
  887. vertices[ i ].toArray( positions, i * 3 );
  888. }
  889. var geometry = new THREE.BufferGeometry();
  890. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  891. return geometry;
  892. }
  893. // parse nodes in FBXTree.Objects.subNodes.Model and generate a THREE.Group
  894. function parseScene( FBXTree, connections, deformers, geometryMap, materialMap ) {
  895. var sceneGraph = new THREE.Group();
  896. var ModelNode = FBXTree.Objects.subNodes.Model;
  897. var modelArray = [];
  898. var modelMap = new Map();
  899. for ( var nodeID in ModelNode ) {
  900. var id = parseInt( nodeID );
  901. var node = ModelNode[ nodeID ];
  902. var conns = connections.get( id );
  903. var model = null;
  904. for ( var i = 0; i < conns.parents.length; ++ i ) {
  905. for ( var FBX_ID in deformers ) {
  906. var deformer = deformers[ FBX_ID ];
  907. var subDeformers = deformer.map;
  908. var subDeformer = subDeformers[ conns.parents[ i ].ID ];
  909. if ( subDeformer ) {
  910. var model2 = model;
  911. model = new THREE.Bone();
  912. deformer.bones[ subDeformer.index ] = model;
  913. // seems like we need this not to make non-connected bone, maybe?
  914. // TODO: confirm
  915. if ( model2 !== null ) model.add( model2 );
  916. }
  917. }
  918. }
  919. if ( ! model ) {
  920. switch ( node.attrType ) {
  921. // create a THREE.PerspectiveCamera or THREE.OrthographicCamera
  922. case 'Camera':
  923. var cameraAttribute;
  924. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  925. var childID = conns.children[ childrenIndex ].ID;
  926. var attr = FBXTree.Objects.subNodes.NodeAttribute[ childID ];
  927. if ( attr !== undefined && attr.properties !== undefined ) {
  928. cameraAttribute = attr.properties;
  929. }
  930. }
  931. if ( cameraAttribute === undefined ) {
  932. model = new THREE.Object3D();
  933. } else {
  934. var type = 0;
  935. if ( cameraAttribute.CameraProjectionType !== undefined && cameraAttribute.CameraProjectionType.value === 1 ) {
  936. type = 1;
  937. }
  938. var nearClippingPlane = 1;
  939. if ( cameraAttribute.NearPlane !== undefined ) {
  940. nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
  941. }
  942. var farClippingPlane = 1000;
  943. if ( cameraAttribute.FarPlane !== undefined ) {
  944. farClippingPlane = cameraAttribute.FarPlane.value / 1000;
  945. }
  946. var width = window.innerWidth;
  947. var height = window.innerHeight;
  948. if ( cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined ) {
  949. width = cameraAttribute.AspectWidth.value;
  950. height = cameraAttribute.AspectHeight.value;
  951. }
  952. var aspect = width / height;
  953. var fov = 45;
  954. if ( cameraAttribute.FieldOfView !== undefined ) {
  955. fov = cameraAttribute.FieldOfView.value;
  956. }
  957. switch ( type ) {
  958. case 0: // Perspective
  959. model = new THREE.PerspectiveCamera( fov, aspect, nearClippingPlane, farClippingPlane );
  960. break;
  961. case 1: // Orthographic
  962. model = new THREE.OrthographicCamera( - width / 2, width / 2, height / 2, - height / 2, nearClippingPlane, farClippingPlane );
  963. break;
  964. default:
  965. console.warn( 'THREE.FBXLoader: Unknown camera type ' + type + '.' );
  966. model = new THREE.Object3D();
  967. break;
  968. }
  969. }
  970. break;
  971. // Create a THREE.DirectionalLight, THREE.PointLight or THREE.SpotLight
  972. case 'Light':
  973. var lightAttribute;
  974. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  975. var childID = conns.children[ childrenIndex ].ID;
  976. var attr = FBXTree.Objects.subNodes.NodeAttribute[ childID ];
  977. if ( attr !== undefined && attr.properties !== undefined ) {
  978. lightAttribute = attr.properties;
  979. }
  980. }
  981. if ( lightAttribute === undefined ) {
  982. model = new THREE.Object3D();
  983. } else {
  984. var type;
  985. // LightType can be undefined for Point lights
  986. if ( lightAttribute.LightType === undefined ) {
  987. type = 0;
  988. } else {
  989. type = lightAttribute.LightType.value;
  990. }
  991. var color = 0xffffff;
  992. if ( lightAttribute.Color !== undefined ) {
  993. color = parseColor( lightAttribute.Color.value );
  994. }
  995. var intensity = ( lightAttribute.Intensity === undefined ) ? 1 : lightAttribute.Intensity.value / 100;
  996. // light disabled
  997. if ( lightAttribute.CastLightOnObject !== undefined && lightAttribute.CastLightOnObject.value === 0 ) {
  998. intensity = 0;
  999. }
  1000. var distance = 0;
  1001. if ( lightAttribute.FarAttenuationEnd !== undefined ) {
  1002. if ( lightAttribute.EnableFarAttenuation !== undefined && lightAttribute.EnableFarAttenuation.value === 0 ) {
  1003. distance = 0;
  1004. } else {
  1005. distance = lightAttribute.FarAttenuationEnd.value / 1000;
  1006. }
  1007. }
  1008. // TODO: could this be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
  1009. var decay = 1;
  1010. switch ( type ) {
  1011. case 0: // Point
  1012. model = new THREE.PointLight( color, intensity, distance, decay );
  1013. break;
  1014. case 1: // Directional
  1015. model = new THREE.DirectionalLight( color, intensity );
  1016. break;
  1017. case 2: // Spot
  1018. var angle = Math.PI / 3;
  1019. if ( lightAttribute.InnerAngle !== undefined ) {
  1020. angle = THREE.Math.degToRad( lightAttribute.InnerAngle.value );
  1021. }
  1022. var penumbra = 0;
  1023. if ( lightAttribute.OuterAngle !== undefined ) {
  1024. // TODO: this is not correct - FBX calculates outer and inner angle in degrees
  1025. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  1026. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  1027. penumbra = THREE.Math.degToRad( lightAttribute.OuterAngle.value );
  1028. penumbra = Math.max( penumbra, 1 );
  1029. }
  1030. model = new THREE.SpotLight( color, intensity, distance, angle, penumbra, decay );
  1031. break;
  1032. default:
  1033. console.warn( 'THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a THREE.PointLight.' );
  1034. model = new THREE.PointLight( color, intensity );
  1035. break;
  1036. }
  1037. if ( lightAttribute.CastShadows !== undefined && lightAttribute.CastShadows.value === 1 ) {
  1038. model.castShadow = true;
  1039. }
  1040. }
  1041. break;
  1042. case 'Mesh':
  1043. var geometry = null;
  1044. var material = null;
  1045. var materials = [];
  1046. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1047. var child = conns.children[ childrenIndex ];
  1048. if ( geometryMap.has( child.ID ) ) {
  1049. geometry = geometryMap.get( child.ID );
  1050. }
  1051. if ( materialMap.has( child.ID ) ) {
  1052. materials.push( materialMap.get( child.ID ) );
  1053. }
  1054. }
  1055. if ( materials.length > 1 ) {
  1056. material = materials;
  1057. } else if ( materials.length > 0 ) {
  1058. material = materials[ 0 ];
  1059. } else {
  1060. material = new THREE.MeshPhongMaterial( { color: 0xcccccc } );
  1061. materials.push( material );
  1062. }
  1063. if ( 'color' in geometry.attributes ) {
  1064. for ( var materialIndex = 0, numMaterials = materials.length; materialIndex < numMaterials; ++ materialIndex ) {
  1065. materials[ materialIndex ].vertexColors = THREE.VertexColors;
  1066. }
  1067. }
  1068. if ( geometry.FBX_Deformer ) {
  1069. for ( var materialsIndex = 0, materialsLength = materials.length; materialsIndex < materialsLength; ++ materialsIndex ) {
  1070. materials[ materialsIndex ].skinning = true;
  1071. }
  1072. model = new THREE.SkinnedMesh( geometry, material );
  1073. } else {
  1074. model = new THREE.Mesh( geometry, material );
  1075. }
  1076. break;
  1077. case 'NurbsCurve':
  1078. var geometry = null;
  1079. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1080. var child = conns.children[ childrenIndex ];
  1081. if ( geometryMap.has( child.ID ) ) {
  1082. geometry = geometryMap.get( child.ID );
  1083. }
  1084. }
  1085. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  1086. material = new THREE.LineBasicMaterial( { color: 0x3300ff, linewidth: 5 } );
  1087. model = new THREE.Line( geometry, material );
  1088. break;
  1089. default:
  1090. model = new THREE.Group();
  1091. break;
  1092. }
  1093. }
  1094. model.name = THREE.PropertyBinding.sanitizeNodeName( node.attrName );
  1095. model.FBX_ID = id;
  1096. modelArray.push( model );
  1097. modelMap.set( id, model );
  1098. }
  1099. for ( var modelArrayIndex = 0, modelArrayLength = modelArray.length; modelArrayIndex < modelArrayLength; ++ modelArrayIndex ) {
  1100. var model = modelArray[ modelArrayIndex ];
  1101. var node = ModelNode[ model.FBX_ID ];
  1102. if ( 'Lcl_Translation' in node.properties ) {
  1103. model.position.fromArray( node.properties.Lcl_Translation.value );
  1104. }
  1105. if ( 'Lcl_Rotation' in node.properties ) {
  1106. var rotation = node.properties.Lcl_Rotation.value.map( THREE.Math.degToRad );
  1107. rotation.push( 'ZYX' );
  1108. model.rotation.fromArray( rotation );
  1109. }
  1110. if ( 'Lcl_Scaling' in node.properties ) {
  1111. model.scale.fromArray( node.properties.Lcl_Scaling.value );
  1112. }
  1113. if ( 'PreRotation' in node.properties ) {
  1114. var preRotations = new THREE.Euler().fromArray( node.properties.PreRotation.value.map( THREE.Math.degToRad ), 'ZYX' );
  1115. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1116. var currentRotation = new THREE.Quaternion().setFromEuler( model.rotation );
  1117. preRotations.multiply( currentRotation );
  1118. model.rotation.setFromQuaternion( preRotations, 'ZYX' );
  1119. }
  1120. // allow transformed pivots - see https://github.com/mrdoob/three.js/issues/11895
  1121. if ( 'GeometricTranslation' in node.properties ) {
  1122. var array = node.properties.GeometricTranslation.value;
  1123. model.traverse( function ( child ) {
  1124. if ( child.geometry ) {
  1125. child.geometry.translate( array[ 0 ], array[ 1 ], array[ 2 ] );
  1126. }
  1127. } );
  1128. }
  1129. if ( 'LookAtProperty' in node.properties ) {
  1130. var conns = connections.get( model.FBX_ID );
  1131. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1132. var child = conns.children[ childrenIndex ];
  1133. if ( child.relationship === 'LookAtProperty' ) {
  1134. var lookAtTarget = FBXTree.Objects.subNodes.Model[ child.ID ];
  1135. if ( 'Lcl_Translation' in lookAtTarget.properties ) {
  1136. var pos = lookAtTarget.properties.Lcl_Translation.value;
  1137. // DirectionalLight, SpotLight
  1138. if ( model.target !== undefined ) {
  1139. model.target.position.set( pos[ 0 ], pos[ 1 ], pos[ 2 ] );
  1140. sceneGraph.add( model.target );
  1141. } else { // Cameras and other Object3Ds
  1142. model.lookAt( new THREE.Vector3( pos[ 0 ], pos[ 1 ], pos[ 2 ] ) );
  1143. }
  1144. }
  1145. }
  1146. }
  1147. }
  1148. var conns = connections.get( model.FBX_ID );
  1149. for ( var parentIndex = 0; parentIndex < conns.parents.length; parentIndex ++ ) {
  1150. var pIndex = findIndex( modelArray, function ( mod ) {
  1151. return mod.FBX_ID === conns.parents[ parentIndex ].ID;
  1152. } );
  1153. if ( pIndex > - 1 ) {
  1154. modelArray[ pIndex ].add( model );
  1155. break;
  1156. }
  1157. }
  1158. if ( model.parent === null ) {
  1159. sceneGraph.add( model );
  1160. }
  1161. }
  1162. // Now with the bones created, we can update the skeletons and bind them to the skinned meshes.
  1163. sceneGraph.updateMatrixWorld( true );
  1164. var worldMatrices = new Map();
  1165. // Put skeleton into bind pose.
  1166. if ( 'Pose' in FBXTree.Objects.subNodes ) {
  1167. var BindPoseNode = FBXTree.Objects.subNodes.Pose;
  1168. for ( var nodeID in BindPoseNode ) {
  1169. if ( BindPoseNode[ nodeID ].attrType === 'BindPose' ) {
  1170. BindPoseNode = BindPoseNode[ nodeID ];
  1171. break;
  1172. }
  1173. }
  1174. var PoseNode = BindPoseNode.subNodes.PoseNode;
  1175. for ( var PoseNodeIndex = 0, PoseNodeLength = PoseNode.length; PoseNodeIndex < PoseNodeLength; ++ PoseNodeIndex ) {
  1176. var node = PoseNode[ PoseNodeIndex ];
  1177. var rawMatWrd = new THREE.Matrix4().fromArray( node.subNodes.Matrix.properties.a );
  1178. worldMatrices.set( parseInt( node.id ), rawMatWrd );
  1179. }
  1180. }
  1181. for ( var FBX_ID in deformers ) {
  1182. var deformer = deformers[ FBX_ID ];
  1183. var subDeformers = deformer.map;
  1184. for ( var key in subDeformers ) {
  1185. var subDeformer = subDeformers[ key ];
  1186. var subDeformerIndex = subDeformer.index;
  1187. var bone = deformer.bones[ subDeformerIndex ];
  1188. if ( ! worldMatrices.has( bone.FBX_ID ) ) {
  1189. break;
  1190. }
  1191. var mat = worldMatrices.get( bone.FBX_ID );
  1192. bone.matrixWorld.copy( mat );
  1193. }
  1194. // Now that skeleton is in bind pose, bind to model.
  1195. deformer.skeleton = new THREE.Skeleton( deformer.bones );
  1196. var conns = connections.get( deformer.FBX_ID );
  1197. var parents = conns.parents;
  1198. for ( var parentsIndex = 0, parentsLength = parents.length; parentsIndex < parentsLength; ++ parentsIndex ) {
  1199. var parent = parents[ parentsIndex ];
  1200. if ( geometryMap.has( parent.ID ) ) {
  1201. var geoID = parent.ID;
  1202. var geoConns = connections.get( geoID );
  1203. for ( var i = 0; i < geoConns.parents.length; ++ i ) {
  1204. if ( modelMap.has( geoConns.parents[ i ].ID ) ) {
  1205. var model = modelMap.get( geoConns.parents[ i ].ID );
  1206. model.bind( deformer.skeleton, model.matrixWorld );
  1207. break;
  1208. }
  1209. }
  1210. }
  1211. }
  1212. }
  1213. //Skeleton is now bound, return objects to starting world positions.
  1214. sceneGraph.updateMatrixWorld( true );
  1215. // Silly hack with the animation parsing. We're gonna pretend the scene graph has a skeleton
  1216. // to attach animations to, since FBX treats animations as animations for the entire scene,
  1217. // not just for individual objects.
  1218. sceneGraph.skeleton = {
  1219. bones: modelArray
  1220. };
  1221. var animations = parseAnimations( FBXTree, connections, sceneGraph );
  1222. addAnimations( sceneGraph, animations );
  1223. // Parse ambient color - if it's not set to black (default), create an ambient light
  1224. if ( 'GlobalSettings' in FBXTree && 'AmbientColor' in FBXTree.GlobalSettings.properties ) {
  1225. var ambientColor = FBXTree.GlobalSettings.properties.AmbientColor.value;
  1226. var r = ambientColor[ 0 ];
  1227. var g = ambientColor[ 1 ];
  1228. var b = ambientColor[ 2 ];
  1229. if ( r !== 0 || g !== 0 || b !== 0 ) {
  1230. var color = new THREE.Color( r, g, b );
  1231. sceneGraph.add( new THREE.AmbientLight( color, 1 ) );
  1232. }
  1233. }
  1234. return sceneGraph;
  1235. }
  1236. // Parses animation information from nodes in
  1237. // FBXTree.Objects.subNodes.AnimationCurve ( connected to AnimationCurveNode )
  1238. // FBXTree.Objects.subNodes.AnimationCurveNode ( connected to AnimationLayer and an animated property in some other node )
  1239. // FBXTree.Objects.subNodes.AnimationLayer ( connected to AnimationStack )
  1240. // FBXTree.Objects.subNodes.AnimationStack
  1241. function parseAnimations( FBXTree, connections, sceneGraph ) {
  1242. var rawNodes = FBXTree.Objects.subNodes.AnimationCurveNode;
  1243. var rawCurves = FBXTree.Objects.subNodes.AnimationCurve;
  1244. var rawLayers = FBXTree.Objects.subNodes.AnimationLayer;
  1245. var rawStacks = FBXTree.Objects.subNodes.AnimationStack;
  1246. var fps = 30; // default framerate
  1247. if ( 'GlobalSettings' in FBXTree && 'TimeMode' in FBXTree.GlobalSettings.properties ) {
  1248. /* Autodesk time mode documentation can be found here:
  1249. * http://docs.autodesk.com/FBX/2014/ENU/FBX-SDK-Documentation/index.html?url=cpp_ref/class_fbx_time.html,topicNumber=cpp_ref_class_fbx_time_html
  1250. */
  1251. var timeModeEnum = [
  1252. 30, // 0: eDefaultMode
  1253. 120, // 1: eFrames120
  1254. 100, // 2: eFrames100
  1255. 60, // 3: eFrames60
  1256. 50, // 4: eFrames50
  1257. 48, // 5: eFrames48
  1258. 30, // 6: eFrames30 (black and white NTSC )
  1259. 30, // 7: eFrames30Drop
  1260. 29.97, // 8: eNTSCDropFrame
  1261. 29.97, // 90: eNTSCFullFrame
  1262. 25, // 10: ePal ( PAL/SECAM )
  1263. 24, // 11: eFrames24 (Film/Cinema)
  1264. 1, // 12: eFrames1000 (use for date time))
  1265. 23.976, // 13: eFilmFullFrame
  1266. 30, // 14: eCustom: use GlobalSettings.properties.CustomFrameRate.value
  1267. 96, // 15: eFrames96
  1268. 72, // 16: eFrames72
  1269. 59.94, // 17: eFrames59dot94
  1270. ];
  1271. var eMode = FBXTree.GlobalSettings.properties.TimeMode.value;
  1272. if ( eMode === 14 ) {
  1273. if ( 'CustomFrameRate' in FBXTree.GlobalSettings.properties ) {
  1274. fps = FBXTree.GlobalSettings.properties.CustomFrameRate.value;
  1275. fps = ( fps === - 1 ) ? 30 : fps;
  1276. }
  1277. } else if ( eMode <= 17 ) { // for future proofing - if more eModes get added, they will default to 30fps
  1278. fps = timeModeEnum[ eMode ];
  1279. }
  1280. }
  1281. /**
  1282. * @type {{
  1283. curves: Map<number, {
  1284. T: {
  1285. id: number;
  1286. attr: string;
  1287. internalID: number;
  1288. attrX: boolean;
  1289. attrY: boolean;
  1290. attrZ: boolean;
  1291. containerBoneID: number;
  1292. containerID: number;
  1293. curves: {
  1294. x: {
  1295. version: any;
  1296. id: number;
  1297. internalID: number;
  1298. times: number[];
  1299. values: number[];
  1300. attrFlag: number[];
  1301. attrData: number[];
  1302. };
  1303. y: {
  1304. version: any;
  1305. id: number;
  1306. internalID: number;
  1307. times: number[];
  1308. values: number[];
  1309. attrFlag: number[];
  1310. attrData: number[];
  1311. };
  1312. z: {
  1313. version: any;
  1314. id: number;
  1315. internalID: number;
  1316. times: number[];
  1317. values: number[];
  1318. attrFlag: number[];
  1319. attrData: number[];
  1320. };
  1321. };
  1322. },
  1323. R: {
  1324. id: number;
  1325. attr: string;
  1326. internalID: number;
  1327. attrX: boolean;
  1328. attrY: boolean;
  1329. attrZ: boolean;
  1330. containerBoneID: number;
  1331. containerID: number;
  1332. curves: {
  1333. x: {
  1334. version: any;
  1335. id: number;
  1336. internalID: number;
  1337. times: number[];
  1338. values: number[];
  1339. attrFlag: number[];
  1340. attrData: number[];
  1341. };
  1342. y: {
  1343. version: any;
  1344. id: number;
  1345. internalID: number;
  1346. times: number[];
  1347. values: number[];
  1348. attrFlag: number[];
  1349. attrData: number[];
  1350. };
  1351. z: {
  1352. version: any;
  1353. id: number;
  1354. internalID: number;
  1355. times: number[];
  1356. values: number[];
  1357. attrFlag: number[];
  1358. attrData: number[];
  1359. };
  1360. };
  1361. },
  1362. S: {
  1363. id: number;
  1364. attr: string;
  1365. internalID: number;
  1366. attrX: boolean;
  1367. attrY: boolean;
  1368. attrZ: boolean;
  1369. containerBoneID: number;
  1370. containerID: number;
  1371. curves: {
  1372. x: {
  1373. version: any;
  1374. id: number;
  1375. internalID: number;
  1376. times: number[];
  1377. values: number[];
  1378. attrFlag: number[];
  1379. attrData: number[];
  1380. };
  1381. y: {
  1382. version: any;
  1383. id: number;
  1384. internalID: number;
  1385. times: number[];
  1386. values: number[];
  1387. attrFlag: number[];
  1388. attrData: number[];
  1389. };
  1390. z: {
  1391. version: any;
  1392. id: number;
  1393. internalID: number;
  1394. times: number[];
  1395. values: number[];
  1396. attrFlag: number[];
  1397. attrData: number[];
  1398. };
  1399. };
  1400. }
  1401. }>,
  1402. layers: Map<number, {
  1403. T: {
  1404. id: number;
  1405. attr: string;
  1406. internalID: number;
  1407. attrX: boolean;
  1408. attrY: boolean;
  1409. attrZ: boolean;
  1410. containerBoneID: number;
  1411. containerID: number;
  1412. curves: {
  1413. x: {
  1414. version: any;
  1415. id: number;
  1416. internalID: number;
  1417. times: number[];
  1418. values: number[];
  1419. attrFlag: number[];
  1420. attrData: number[];
  1421. };
  1422. y: {
  1423. version: any;
  1424. id: number;
  1425. internalID: number;
  1426. times: number[];
  1427. values: number[];
  1428. attrFlag: number[];
  1429. attrData: number[];
  1430. };
  1431. z: {
  1432. version: any;
  1433. id: number;
  1434. internalID: number;
  1435. times: number[];
  1436. values: number[];
  1437. attrFlag: number[];
  1438. attrData: number[];
  1439. };
  1440. },
  1441. },
  1442. R: {
  1443. id: number;
  1444. attr: string;
  1445. internalID: number;
  1446. attrX: boolean;
  1447. attrY: boolean;
  1448. attrZ: boolean;
  1449. containerBoneID: number;
  1450. containerID: number;
  1451. curves: {
  1452. x: {
  1453. version: any;
  1454. id: number;
  1455. internalID: number;
  1456. times: number[];
  1457. values: number[];
  1458. attrFlag: number[];
  1459. attrData: number[];
  1460. };
  1461. y: {
  1462. version: any;
  1463. id: number;
  1464. internalID: number;
  1465. times: number[];
  1466. values: number[];
  1467. attrFlag: number[];
  1468. attrData: number[];
  1469. };
  1470. z: {
  1471. version: any;
  1472. id: number;
  1473. internalID: number;
  1474. times: number[];
  1475. values: number[];
  1476. attrFlag: number[];
  1477. attrData: number[];
  1478. };
  1479. },
  1480. },
  1481. S: {
  1482. id: number;
  1483. attr: string;
  1484. internalID: number;
  1485. attrX: boolean;
  1486. attrY: boolean;
  1487. attrZ: boolean;
  1488. containerBoneID: number;
  1489. containerID: number;
  1490. curves: {
  1491. x: {
  1492. version: any;
  1493. id: number;
  1494. internalID: number;
  1495. times: number[];
  1496. values: number[];
  1497. attrFlag: number[];
  1498. attrData: number[];
  1499. };
  1500. y: {
  1501. version: any;
  1502. id: number;
  1503. internalID: number;
  1504. times: number[];
  1505. values: number[];
  1506. attrFlag: number[];
  1507. attrData: number[];
  1508. };
  1509. z: {
  1510. version: any;
  1511. id: number;
  1512. internalID: number;
  1513. times: number[];
  1514. values: number[];
  1515. attrFlag: number[];
  1516. attrData: number[];
  1517. };
  1518. },
  1519. }
  1520. }[]>,
  1521. stacks: Map<number, {
  1522. name: string,
  1523. layers: {
  1524. T: {
  1525. id: number;
  1526. attr: string;
  1527. internalID: number;
  1528. attrX: boolean;
  1529. attrY: boolean;
  1530. attrZ: boolean;
  1531. containerBoneID: number;
  1532. containerID: number;
  1533. curves: {
  1534. x: {
  1535. version: any;
  1536. id: number;
  1537. internalID: number;
  1538. times: number[];
  1539. values: number[];
  1540. attrFlag: number[];
  1541. attrData: number[];
  1542. };
  1543. y: {
  1544. version: any;
  1545. id: number;
  1546. internalID: number;
  1547. times: number[];
  1548. values: number[];
  1549. attrFlag: number[];
  1550. attrData: number[];
  1551. };
  1552. z: {
  1553. version: any;
  1554. id: number;
  1555. internalID: number;
  1556. times: number[];
  1557. values: number[];
  1558. attrFlag: number[];
  1559. attrData: number[];
  1560. };
  1561. };
  1562. };
  1563. R: {
  1564. id: number;
  1565. attr: string;
  1566. internalID: number;
  1567. attrX: boolean;
  1568. attrY: boolean;
  1569. attrZ: boolean;
  1570. containerBoneID: number;
  1571. containerID: number;
  1572. curves: {
  1573. x: {
  1574. version: any;
  1575. id: number;
  1576. internalID: number;
  1577. times: number[];
  1578. values: number[];
  1579. attrFlag: number[];
  1580. attrData: number[];
  1581. };
  1582. y: {
  1583. version: any;
  1584. id: number;
  1585. internalID: number;
  1586. times: number[];
  1587. values: number[];
  1588. attrFlag: number[];
  1589. attrData: number[];
  1590. };
  1591. z: {
  1592. version: any;
  1593. id: number;
  1594. internalID: number;
  1595. times: number[];
  1596. values: number[];
  1597. attrFlag: number[];
  1598. attrData: number[];
  1599. };
  1600. };
  1601. };
  1602. S: {
  1603. id: number;
  1604. attr: string;
  1605. internalID: number;
  1606. attrX: boolean;
  1607. attrY: boolean;
  1608. attrZ: boolean;
  1609. containerBoneID: number;
  1610. containerID: number;
  1611. curves: {
  1612. x: {
  1613. version: any;
  1614. id: number;
  1615. internalID: number;
  1616. times: number[];
  1617. values: number[];
  1618. attrFlag: number[];
  1619. attrData: number[];
  1620. };
  1621. y: {
  1622. version: any;
  1623. id: number;
  1624. internalID: number;
  1625. times: number[];
  1626. values: number[];
  1627. attrFlag: number[];
  1628. attrData: number[];
  1629. };
  1630. z: {
  1631. version: any;
  1632. id: number;
  1633. internalID: number;
  1634. times: number[];
  1635. values: number[];
  1636. attrFlag: number[];
  1637. attrData: number[];
  1638. };
  1639. };
  1640. };
  1641. }[][],
  1642. length: number,
  1643. frames: number }>,
  1644. length: number,
  1645. fps: number,
  1646. frames: number
  1647. }}
  1648. */
  1649. var returnObject = {
  1650. curves: new Map(),
  1651. layers: {},
  1652. stacks: {},
  1653. length: 0,
  1654. fps: fps,
  1655. frames: 0
  1656. };
  1657. var animationCurveNodes = [];
  1658. for ( var nodeID in rawNodes ) {
  1659. if ( nodeID.match( /\d+/ ) ) {
  1660. var animationNode = parseAnimationNode( FBXTree, rawNodes[ nodeID ], connections, sceneGraph );
  1661. animationCurveNodes.push( animationNode );
  1662. }
  1663. }
  1664. var tmpMap = new Map();
  1665. for ( var animationCurveNodeIndex = 0; animationCurveNodeIndex < animationCurveNodes.length; ++ animationCurveNodeIndex ) {
  1666. if ( animationCurveNodes[ animationCurveNodeIndex ] === null ) {
  1667. continue;
  1668. }
  1669. tmpMap.set( animationCurveNodes[ animationCurveNodeIndex ].id, animationCurveNodes[ animationCurveNodeIndex ] );
  1670. }
  1671. var animationCurves = [];
  1672. for ( nodeID in rawCurves ) {
  1673. if ( nodeID.match( /\d+/ ) ) {
  1674. var animationCurve = parseAnimationCurve( rawCurves[ nodeID ] );
  1675. // seems like this check would be necessary?
  1676. if ( ! connections.has( animationCurve.id ) ) continue;
  1677. animationCurves.push( animationCurve );
  1678. var firstParentConn = connections.get( animationCurve.id ).parents[ 0 ];
  1679. var firstParentID = firstParentConn.ID;
  1680. var firstParentRelationship = firstParentConn.relationship;
  1681. var axis = '';
  1682. if ( firstParentRelationship.match( /X/ ) ) {
  1683. axis = 'x';
  1684. } else if ( firstParentRelationship.match( /Y/ ) ) {
  1685. axis = 'y';
  1686. } else if ( firstParentRelationship.match( /Z/ ) ) {
  1687. axis = 'z';
  1688. } else {
  1689. continue;
  1690. }
  1691. tmpMap.get( firstParentID ).curves[ axis ] = animationCurve;
  1692. }
  1693. }
  1694. tmpMap.forEach( function ( curveNode ) {
  1695. var id = curveNode.containerBoneID;
  1696. if ( ! returnObject.curves.has( id ) ) {
  1697. returnObject.curves.set( id, { T: null, R: null, S: null } );
  1698. }
  1699. returnObject.curves.get( id )[ curveNode.attr ] = curveNode;
  1700. if ( curveNode.attr === 'R' ) {
  1701. var curves = curveNode.curves;
  1702. // Some FBX files have an AnimationCurveNode
  1703. // which isn't any connected to any AnimationCurve.
  1704. // Setting animation parameter for them here.
  1705. if ( curves.x === null ) {
  1706. curves.x = {
  1707. version: null,
  1708. times: [ 0.0 ],
  1709. values: [ 0.0 ]
  1710. };
  1711. }
  1712. if ( curves.y === null ) {
  1713. curves.y = {
  1714. version: null,
  1715. times: [ 0.0 ],
  1716. values: [ 0.0 ]
  1717. };
  1718. }
  1719. if ( curves.z === null ) {
  1720. curves.z = {
  1721. version: null,
  1722. times: [ 0.0 ],
  1723. values: [ 0.0 ]
  1724. };
  1725. }
  1726. curves.x.values = curves.x.values.map( THREE.Math.degToRad );
  1727. curves.y.values = curves.y.values.map( THREE.Math.degToRad );
  1728. curves.z.values = curves.z.values.map( THREE.Math.degToRad );
  1729. if ( curveNode.preRotations !== null ) {
  1730. var preRotations = new THREE.Euler().setFromVector3( curveNode.preRotations, 'ZYX' );
  1731. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1732. var frameRotation = new THREE.Euler();
  1733. var frameRotationQuaternion = new THREE.Quaternion();
  1734. for ( var frame = 0; frame < curves.x.times.length; ++ frame ) {
  1735. frameRotation.set( curves.x.values[ frame ], curves.y.values[ frame ], curves.z.values[ frame ], 'ZYX' );
  1736. frameRotationQuaternion.setFromEuler( frameRotation ).premultiply( preRotations );
  1737. frameRotation.setFromQuaternion( frameRotationQuaternion, 'ZYX' );
  1738. curves.x.values[ frame ] = frameRotation.x;
  1739. curves.y.values[ frame ] = frameRotation.y;
  1740. curves.z.values[ frame ] = frameRotation.z;
  1741. }
  1742. }
  1743. }
  1744. } );
  1745. for ( var nodeID in rawLayers ) {
  1746. var layer = [];
  1747. var children = connections.get( parseInt( nodeID ) ).children;
  1748. for ( var childIndex = 0; childIndex < children.length; childIndex ++ ) {
  1749. // Skip lockInfluenceWeights
  1750. if ( tmpMap.has( children[ childIndex ].ID ) ) {
  1751. var curveNode = tmpMap.get( children[ childIndex ].ID );
  1752. var boneID = curveNode.containerBoneID;
  1753. if ( layer[ boneID ] === undefined ) {
  1754. layer[ boneID ] = {
  1755. T: null,
  1756. R: null,
  1757. S: null
  1758. };
  1759. }
  1760. layer[ boneID ][ curveNode.attr ] = curveNode;
  1761. }
  1762. }
  1763. returnObject.layers[ nodeID ] = layer;
  1764. }
  1765. for ( var nodeID in rawStacks ) {
  1766. var layers = [];
  1767. var children = connections.get( parseInt( nodeID ) ).children;
  1768. var timestamps = { max: 0, min: Number.MAX_VALUE };
  1769. for ( var childIndex = 0; childIndex < children.length; ++ childIndex ) {
  1770. var currentLayer = returnObject.layers[ children[ childIndex ].ID ];
  1771. if ( currentLayer !== undefined ) {
  1772. layers.push( currentLayer );
  1773. for ( var currentLayerIndex = 0, currentLayerLength = currentLayer.length; currentLayerIndex < currentLayerLength; ++ currentLayerIndex ) {
  1774. var layer = currentLayer[ currentLayerIndex ];
  1775. if ( layer ) {
  1776. getCurveNodeMaxMinTimeStamps( layer, timestamps );
  1777. }
  1778. }
  1779. }
  1780. }
  1781. // Do we have an animation clip with actual length?
  1782. if ( timestamps.max > timestamps.min ) {
  1783. returnObject.stacks[ nodeID ] = {
  1784. name: rawStacks[ nodeID ].attrName,
  1785. layers: layers,
  1786. length: timestamps.max - timestamps.min,
  1787. frames: ( timestamps.max - timestamps.min ) * returnObject.fps
  1788. };
  1789. }
  1790. }
  1791. return returnObject;
  1792. }
  1793. function parseAnimationNode( FBXTree, animationCurveNode, connections, sceneGraph ) {
  1794. var rawModels = FBXTree.Objects.subNodes.Model;
  1795. var returnObject = {
  1796. id: animationCurveNode.id,
  1797. attr: animationCurveNode.attrName,
  1798. internalID: animationCurveNode.id,
  1799. attrX: false,
  1800. attrY: false,
  1801. attrZ: false,
  1802. containerBoneID: - 1,
  1803. containerID: - 1,
  1804. curves: {
  1805. x: null,
  1806. y: null,
  1807. z: null
  1808. },
  1809. preRotations: null
  1810. };
  1811. if ( returnObject.attr.match( /S|R|T/ ) ) {
  1812. for ( var attributeKey in animationCurveNode.properties ) {
  1813. if ( attributeKey.match( /X/ ) ) {
  1814. returnObject.attrX = true;
  1815. }
  1816. if ( attributeKey.match( /Y/ ) ) {
  1817. returnObject.attrY = true;
  1818. }
  1819. if ( attributeKey.match( /Z/ ) ) {
  1820. returnObject.attrZ = true;
  1821. }
  1822. }
  1823. } else {
  1824. return null;
  1825. }
  1826. var conns = connections.get( returnObject.id );
  1827. var containerIndices = conns.parents;
  1828. for ( var containerIndicesIndex = containerIndices.length - 1; containerIndicesIndex >= 0; -- containerIndicesIndex ) {
  1829. var boneID = findIndex( sceneGraph.skeleton.bones, function ( bone ) {
  1830. return bone.FBX_ID === containerIndices[ containerIndicesIndex ].ID;
  1831. } );
  1832. if ( boneID > - 1 ) {
  1833. returnObject.containerBoneID = boneID;
  1834. returnObject.containerID = containerIndices[ containerIndicesIndex ].ID;
  1835. var model = rawModels[ returnObject.containerID.toString() ];
  1836. if ( 'PreRotation' in model.properties ) {
  1837. returnObject.preRotations = parseVector3( model.properties.PreRotation ).multiplyScalar( Math.PI / 180 );
  1838. }
  1839. break;
  1840. }
  1841. }
  1842. return returnObject;
  1843. }
  1844. function parseAnimationCurve( animationCurve ) {
  1845. return {
  1846. version: null,
  1847. id: animationCurve.id,
  1848. internalID: animationCurve.id,
  1849. times: animationCurve.subNodes.KeyTime.properties.a.map( convertFBXTimeToSeconds ),
  1850. values: animationCurve.subNodes.KeyValueFloat.properties.a,
  1851. attrFlag: animationCurve.subNodes.KeyAttrFlags.properties.a,
  1852. attrData: animationCurve.subNodes.KeyAttrDataFloat.properties.a,
  1853. };
  1854. }
  1855. // Sets the maxTimeStamp and minTimeStamp variables if it has timeStamps that are either larger or smaller
  1856. // than the max or min respectively.
  1857. function getCurveNodeMaxMinTimeStamps( layer, timestamps ) {
  1858. if ( layer.R ) {
  1859. getCurveMaxMinTimeStamp( layer.R.curves, timestamps );
  1860. }
  1861. if ( layer.S ) {
  1862. getCurveMaxMinTimeStamp( layer.S.curves, timestamps );
  1863. }
  1864. if ( layer.T ) {
  1865. getCurveMaxMinTimeStamp( layer.T.curves, timestamps );
  1866. }
  1867. }
  1868. // Sets the maxTimeStamp and minTimeStamp if one of the curve's time stamps
  1869. // exceeds the maximum or minimum.
  1870. function getCurveMaxMinTimeStamp( curve, timestamps ) {
  1871. if ( curve.x ) {
  1872. getCurveAxisMaxMinTimeStamps( curve.x, timestamps );
  1873. }
  1874. if ( curve.y ) {
  1875. getCurveAxisMaxMinTimeStamps( curve.y, timestamps );
  1876. }
  1877. if ( curve.z ) {
  1878. getCurveAxisMaxMinTimeStamps( curve.z, timestamps );
  1879. }
  1880. }
  1881. // Sets the maxTimeStamp and minTimeStamp if one of its timestamps exceeds the maximum or minimum.
  1882. function getCurveAxisMaxMinTimeStamps( axis, timestamps ) {
  1883. timestamps.max = axis.times[ axis.times.length - 1 ] > timestamps.max ? axis.times[ axis.times.length - 1 ] : timestamps.max;
  1884. timestamps.min = axis.times[ 0 ] < timestamps.min ? axis.times[ 0 ] : timestamps.min;
  1885. }
  1886. function addAnimations( group, animations ) {
  1887. if ( group.animations === undefined ) {
  1888. group.animations = [];
  1889. }
  1890. var stacks = animations.stacks;
  1891. for ( var key in stacks ) {
  1892. var stack = stacks[ key ];
  1893. var animationData = {
  1894. name: stack.name,
  1895. fps: animations.fps,
  1896. length: stack.length,
  1897. hierarchy: []
  1898. };
  1899. var bones = group.skeleton.bones;
  1900. for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
  1901. var bone = bones[ bonesIndex ];
  1902. var name = bone.name.replace( /.*:/, '' );
  1903. var parentIndex = findIndex( bones, function ( parentBone ) {
  1904. return bone.parent === parentBone;
  1905. } );
  1906. animationData.hierarchy.push( { parent: parentIndex, name: name, keys: [] } );
  1907. }
  1908. for ( var frame = 0; frame <= stack.frames; frame ++ ) {
  1909. for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
  1910. var bone = bones[ bonesIndex ];
  1911. var boneIndex = bonesIndex;
  1912. var animationNode = stack.layers[ 0 ][ boneIndex ];
  1913. for ( var hierarchyIndex = 0, hierarchyLength = animationData.hierarchy.length; hierarchyIndex < hierarchyLength; ++ hierarchyIndex ) {
  1914. var node = animationData.hierarchy[ hierarchyIndex ];
  1915. if ( node.name === bone.name ) {
  1916. node.keys.push( generateKey( animations, animationNode, bone, frame ) );
  1917. }
  1918. }
  1919. }
  1920. }
  1921. group.animations.push( THREE.AnimationClip.parseAnimation( animationData, bones ) );
  1922. }
  1923. }
  1924. var euler = new THREE.Euler();
  1925. var quaternion = new THREE.Quaternion();
  1926. function generateKey( animations, animationNode, bone, frame ) {
  1927. var key = {
  1928. time: frame / animations.fps,
  1929. pos: bone.position.toArray(),
  1930. rot: bone.quaternion.toArray(),
  1931. scl: bone.scale.toArray()
  1932. };
  1933. if ( animationNode === undefined ) return key;
  1934. euler.setFromQuaternion( bone.quaternion, 'ZYX', false );
  1935. try {
  1936. if ( hasCurve( animationNode, 'T' ) && hasKeyOnFrame( animationNode.T, frame ) ) {
  1937. if ( animationNode.T.curves.x.values[ frame ] ) {
  1938. key.pos[ 0 ] = animationNode.T.curves.x.values[ frame ];
  1939. }
  1940. if ( animationNode.T.curves.y.values[ frame ] ) {
  1941. key.pos[ 1 ] = animationNode.T.curves.y.values[ frame ];
  1942. }
  1943. if ( animationNode.T.curves.z.values[ frame ] ) {
  1944. key.pos[ 2 ] = animationNode.T.curves.z.values[ frame ];
  1945. }
  1946. }
  1947. if ( hasCurve( animationNode, 'R' ) && hasKeyOnFrame( animationNode.R, frame ) ) {
  1948. // Only update the euler's values if rotation is defined for the axis on this frame
  1949. if ( animationNode.R.curves.x.values[ frame ] ) {
  1950. euler.x = animationNode.R.curves.x.values[ frame ];
  1951. }
  1952. if ( animationNode.R.curves.y.values[ frame ] ) {
  1953. euler.y = animationNode.R.curves.y.values[ frame ];
  1954. }
  1955. if ( animationNode.R.curves.z.values[ frame ] ) {
  1956. euler.z = animationNode.R.curves.z.values[ frame ];
  1957. }
  1958. quaternion.setFromEuler( euler );
  1959. key.rot = quaternion.toArray();
  1960. }
  1961. if ( hasCurve( animationNode, 'S' ) && hasKeyOnFrame( animationNode.S, frame ) ) {
  1962. if ( animationNode.T.curves.x.values[ frame ] ) {
  1963. key.scl[ 0 ] = animationNode.S.curves.x.values[ frame ];
  1964. }
  1965. if ( animationNode.T.curves.y.values[ frame ] ) {
  1966. key.scl[ 1 ] = animationNode.S.curves.y.values[ frame ];
  1967. }
  1968. if ( animationNode.T.curves.z.values[ frame ] ) {
  1969. key.scl[ 2 ] = animationNode.S.curves.z.values[ frame ];
  1970. }
  1971. }
  1972. } catch ( error ) {
  1973. // Curve is not fully plotted.
  1974. console.log( 'THREE.FBXLoader: ', bone );
  1975. console.log( 'THREE.FBXLoader: ', error );
  1976. }
  1977. return key;
  1978. }
  1979. var AXES = [ 'x', 'y', 'z' ];
  1980. function hasCurve( animationNode, attribute ) {
  1981. if ( animationNode === undefined ) {
  1982. return false;
  1983. }
  1984. var attributeNode = animationNode[ attribute ];
  1985. if ( ! attributeNode ) {
  1986. return false;
  1987. }
  1988. return AXES.every( function ( key ) {
  1989. return attributeNode.curves[ key ] !== null;
  1990. } );
  1991. }
  1992. function hasKeyOnFrame( attributeNode, frame ) {
  1993. return AXES.every( function ( key ) {
  1994. return isKeyExistOnFrame( attributeNode.curves[ key ], frame );
  1995. } );
  1996. }
  1997. function isKeyExistOnFrame( curve, frame ) {
  1998. return curve.values[ frame ] !== undefined;
  1999. }
  2000. // parse an FBX file in ASCII format
  2001. function TextParser() {}
  2002. Object.assign( TextParser.prototype, {
  2003. getPrevNode: function () {
  2004. return this.nodeStack[ this.currentIndent - 2 ];
  2005. },
  2006. getCurrentNode: function () {
  2007. return this.nodeStack[ this.currentIndent - 1 ];
  2008. },
  2009. getCurrentProp: function () {
  2010. return this.currentProp;
  2011. },
  2012. pushStack: function ( node ) {
  2013. this.nodeStack.push( node );
  2014. this.currentIndent += 1;
  2015. },
  2016. popStack: function () {
  2017. this.nodeStack.pop();
  2018. this.currentIndent -= 1;
  2019. },
  2020. setCurrentProp: function ( val, name ) {
  2021. this.currentProp = val;
  2022. this.currentPropName = name;
  2023. },
  2024. parse: function ( text ) {
  2025. this.currentIndent = 0;
  2026. this.allNodes = new FBXTree();
  2027. this.nodeStack = [];
  2028. this.currentProp = [];
  2029. this.currentPropName = '';
  2030. var split = text.split( '\n' );
  2031. for ( var lineNum = 0, lineLength = split.length; lineNum < lineLength; lineNum ++ ) {
  2032. var l = split[ lineNum ];
  2033. // skip comment line
  2034. if ( l.match( /^[\s\t]*;/ ) ) {
  2035. continue;
  2036. }
  2037. // skip empty line
  2038. if ( l.match( /^[\s\t]*$/ ) ) {
  2039. continue;
  2040. }
  2041. // beginning of node
  2042. var beginningOfNodeExp = new RegExp( '^\\t{' + this.currentIndent + '}(\\w+):(.*){', '' );
  2043. var match = l.match( beginningOfNodeExp );
  2044. if ( match ) {
  2045. var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  2046. var nodeAttrs = match[ 2 ].split( ',' );
  2047. for ( var i = 0, l = nodeAttrs.length; i < l; i ++ ) {
  2048. nodeAttrs[ i ] = nodeAttrs[ i ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  2049. }
  2050. this.parseNodeBegin( l, nodeName, nodeAttrs || null );
  2051. continue;
  2052. }
  2053. // node's property
  2054. var propExp = new RegExp( '^\\t{' + ( this.currentIndent ) + '}(\\w+):[\\s\\t\\r\\n](.*)' );
  2055. var match = l.match( propExp );
  2056. if ( match ) {
  2057. var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  2058. var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  2059. // for special case: base64 image data follows "Content: ," line
  2060. // Content: ,
  2061. // "iVB..."
  2062. if ( propName === 'Content' && propValue === ',' ) {
  2063. propValue = split[ ++ lineNum ].replace( /"/g, '' ).replace( /,$/, '' ).trim();
  2064. }
  2065. this.parseNodeProperty( l, propName, propValue );
  2066. continue;
  2067. }
  2068. // end of node
  2069. var endOfNodeExp = new RegExp( '^\\t{' + ( this.currentIndent - 1 ) + '}}' );
  2070. if ( l.match( endOfNodeExp ) ) {
  2071. this.nodeEnd();
  2072. continue;
  2073. }
  2074. // large arrays are split over multiple lines terminated with a ',' character
  2075. // if this is encountered the line needs to be joined to the previous line
  2076. if ( l.match( /^[^\s\t}]/ ) ) {
  2077. this.parseNodePropertyContinued( l );
  2078. }
  2079. }
  2080. return this.allNodes;
  2081. },
  2082. parseNodeBegin: function ( line, nodeName, nodeAttrs ) {
  2083. var node = { 'name': nodeName, properties: {}, 'subNodes': {} };
  2084. var attrs = this.parseNodeAttr( nodeAttrs );
  2085. var currentNode = this.getCurrentNode();
  2086. // a top node
  2087. if ( this.currentIndent === 0 ) {
  2088. this.allNodes.add( nodeName, node );
  2089. } else { // a subnode
  2090. // if the subnode already exists, append it
  2091. if ( nodeName in currentNode.subNodes ) {
  2092. var tmp = currentNode.subNodes[ nodeName ];
  2093. if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) {
  2094. if ( attrs.id === '' ) {
  2095. currentNode.subNodes[ nodeName ] = [];
  2096. currentNode.subNodes[ nodeName ].push( tmp );
  2097. } else {
  2098. currentNode.subNodes[ nodeName ] = {};
  2099. currentNode.subNodes[ nodeName ][ tmp.id ] = tmp;
  2100. }
  2101. }
  2102. if ( attrs.id === '' ) {
  2103. currentNode.subNodes[ nodeName ].push( node );
  2104. } else {
  2105. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  2106. }
  2107. } else if ( typeof attrs.id === 'number' || attrs.id.match( /^\d+$/ ) ) {
  2108. currentNode.subNodes[ nodeName ] = {};
  2109. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  2110. } else {
  2111. currentNode.subNodes[ nodeName ] = node;
  2112. }
  2113. }
  2114. // for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
  2115. // NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" {
  2116. if ( nodeAttrs ) {
  2117. node.id = attrs.id;
  2118. node.attrName = attrs.name;
  2119. node.attrType = attrs.type;
  2120. }
  2121. this.pushStack( node );
  2122. },
  2123. parseNodeAttr: function ( attrs ) {
  2124. var id = attrs[ 0 ];
  2125. if ( attrs[ 0 ] !== '' ) {
  2126. id = parseInt( attrs[ 0 ] );
  2127. if ( isNaN( id ) ) {
  2128. id = attrs[ 0 ];
  2129. }
  2130. }
  2131. var name = '', type = '';
  2132. if ( attrs.length > 1 ) {
  2133. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  2134. type = attrs[ 2 ];
  2135. }
  2136. return { id: id, name: name, type: type };
  2137. },
  2138. parseNodeProperty: function ( line, propName, propValue ) {
  2139. var currentNode = this.getCurrentNode();
  2140. var parentName = currentNode.name;
  2141. // special case where the parent node is something like "Properties70"
  2142. // these children nodes must treated carefully
  2143. if ( parentName !== undefined ) {
  2144. var propMatch = parentName.match( /Properties(\d)+/ );
  2145. if ( propMatch ) {
  2146. this.parseNodeSpecialProperty( line, propName, propValue );
  2147. return;
  2148. }
  2149. }
  2150. // Connections
  2151. if ( propName === 'C' ) {
  2152. var connProps = propValue.split( ',' ).slice( 1 );
  2153. var from = parseInt( connProps[ 0 ] );
  2154. var to = parseInt( connProps[ 1 ] );
  2155. var rest = propValue.split( ',' ).slice( 3 );
  2156. rest = rest.map( function ( elem ) {
  2157. return elem.trim().replace( /^"/, '' );
  2158. } );
  2159. propName = 'connections';
  2160. propValue = [ from, to ];
  2161. append( propValue, rest );
  2162. if ( currentNode.properties[ propName ] === undefined ) {
  2163. currentNode.properties[ propName ] = [];
  2164. }
  2165. }
  2166. // Node
  2167. if ( propName === 'Node' ) {
  2168. var id = parseInt( propValue );
  2169. currentNode.properties.id = id;
  2170. currentNode.id = id;
  2171. }
  2172. // already exists in properties, then append this
  2173. if ( propName in currentNode.properties ) {
  2174. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  2175. currentNode.properties[ propName ].push( propValue );
  2176. } else {
  2177. currentNode.properties[ propName ] += propValue;
  2178. }
  2179. } else {
  2180. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  2181. currentNode.properties[ propName ].push( propValue );
  2182. } else {
  2183. currentNode.properties[ propName ] = propValue;
  2184. }
  2185. }
  2186. this.setCurrentProp( currentNode.properties, propName );
  2187. // convert string to array, unless it ends in ',' in which case more will be added to it
  2188. if ( propName === 'a' && propValue.slice( - 1 ) !== ',' ) {
  2189. currentNode.properties.a = parseNumberArray( propValue );
  2190. }
  2191. },
  2192. parseNodePropertyContinued: function ( line ) {
  2193. this.currentProp[ this.currentPropName ] += line;
  2194. // if the line doesn't end in ',' we have reached the end of the property value
  2195. // so convert the string to an array
  2196. if ( line.slice( - 1 ) !== ',' ) {
  2197. var currentNode = this.getCurrentNode();
  2198. currentNode.properties.a = parseNumberArray( currentNode.properties.a );
  2199. }
  2200. },
  2201. parseNodeSpecialProperty: function ( line, propName, propValue ) {
  2202. // split this
  2203. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  2204. // into array like below
  2205. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  2206. var props = propValue.split( '",' );
  2207. for ( var i = 0, l = props.length; i < l; i ++ ) {
  2208. props[ i ] = props[ i ].trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  2209. }
  2210. var innerPropName = props[ 0 ];
  2211. var innerPropType1 = props[ 1 ];
  2212. var innerPropType2 = props[ 2 ];
  2213. var innerPropFlag = props[ 3 ];
  2214. var innerPropValue = props[ 4 ];
  2215. /*
  2216. if ( innerPropValue === undefined ) {
  2217. innerPropValue = props[3];
  2218. }
  2219. */
  2220. // cast value to its type
  2221. switch ( innerPropType1 ) {
  2222. case 'int':
  2223. case 'enum':
  2224. case 'bool':
  2225. case 'ULongLong':
  2226. innerPropValue = parseInt( innerPropValue );
  2227. break;
  2228. case 'double':
  2229. case 'Number':
  2230. case 'FieldOfView':
  2231. innerPropValue = parseFloat( innerPropValue );
  2232. break;
  2233. case 'ColorRGB':
  2234. case 'Vector3D':
  2235. case 'Lcl_Translation':
  2236. case 'Lcl_Rotation':
  2237. case 'Lcl_Scaling':
  2238. innerPropValue = parseNumberArray( innerPropValue );
  2239. break;
  2240. }
  2241. // CAUTION: these props must append to parent's parent
  2242. this.getPrevNode().properties[ innerPropName ] = {
  2243. 'type': innerPropType1,
  2244. 'type2': innerPropType2,
  2245. 'flag': innerPropFlag,
  2246. 'value': innerPropValue
  2247. };
  2248. this.setCurrentProp( this.getPrevNode().properties, innerPropName );
  2249. },
  2250. nodeEnd: function () {
  2251. this.popStack();
  2252. },
  2253. isFlattenNode: function ( node ) {
  2254. return ( 'subNodes' in node && 'properties' in node ) ? true : false;
  2255. }
  2256. } );
  2257. // Parse an FBX file in Binary format
  2258. function BinaryParser() {}
  2259. Object.assign( BinaryParser.prototype, {
  2260. parse: function ( buffer ) {
  2261. var reader = new BinaryReader( buffer );
  2262. reader.skip( 23 ); // skip magic 23 bytes
  2263. var version = reader.getUint32();
  2264. console.log( 'THREE.FBXLoader: FBX binary version: ' + version );
  2265. var allNodes = new FBXTree();
  2266. while ( ! this.endOfContent( reader ) ) {
  2267. var node = this.parseNode( reader, version );
  2268. if ( node !== null ) allNodes.add( node.name, node );
  2269. }
  2270. return allNodes;
  2271. },
  2272. // Check if reader has reached the end of content.
  2273. endOfContent: function ( reader ) {
  2274. // footer size: 160bytes + 16-byte alignment padding
  2275. // - 16bytes: magic
  2276. // - padding til 16-byte alignment (at least 1byte?)
  2277. // (seems like some exporters embed fixed 15 or 16bytes?)
  2278. // - 4bytes: magic
  2279. // - 4bytes: version
  2280. // - 120bytes: zero
  2281. // - 16bytes: magic
  2282. if ( reader.size() % 16 === 0 ) {
  2283. return ( ( reader.getOffset() + 160 + 16 ) & ~ 0xf ) >= reader.size();
  2284. } else {
  2285. return reader.getOffset() + 160 + 16 >= reader.size();
  2286. }
  2287. },
  2288. parseNode: function ( reader, version ) {
  2289. // The first three data sizes depends on version.
  2290. var endOffset = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  2291. var numProperties = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  2292. var propertyListLen = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  2293. var nameLen = reader.getUint8();
  2294. var name = reader.getString( nameLen );
  2295. // Regards this node as NULL-record if endOffset is zero
  2296. if ( endOffset === 0 ) return null;
  2297. var propertyList = [];
  2298. for ( var i = 0; i < numProperties; i ++ ) {
  2299. propertyList.push( this.parseProperty( reader ) );
  2300. }
  2301. // Regards the first three elements in propertyList as id, attrName, and attrType
  2302. var id = propertyList.length > 0 ? propertyList[ 0 ] : '';
  2303. var attrName = propertyList.length > 1 ? propertyList[ 1 ] : '';
  2304. var attrType = propertyList.length > 2 ? propertyList[ 2 ] : '';
  2305. var subNodes = {};
  2306. var properties = {};
  2307. var isSingleProperty = false;
  2308. // check if this node represents just a single property
  2309. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  2310. if ( numProperties === 1 && reader.getOffset() === endOffset ) {
  2311. isSingleProperty = true;
  2312. }
  2313. while ( endOffset > reader.getOffset() ) {
  2314. var node = this.parseNode( reader, version );
  2315. if ( node === null ) continue;
  2316. // special case: child node is single property
  2317. if ( node.singleProperty === true ) {
  2318. var value = node.propertyList[ 0 ];
  2319. if ( Array.isArray( value ) ) {
  2320. node.properties[ node.name ] = node.propertyList[ 0 ];
  2321. subNodes[ node.name ] = node;
  2322. node.properties.a = value;
  2323. } else {
  2324. properties[ node.name ] = value;
  2325. }
  2326. continue;
  2327. }
  2328. // parse connections
  2329. if ( name === 'Connections' && node.name === 'C' ) {
  2330. var array = [];
  2331. for ( var i = 1, il = node.propertyList.length; i < il; i ++ ) {
  2332. array[ i - 1 ] = node.propertyList[ i ];
  2333. }
  2334. if ( properties.connections === undefined ) {
  2335. properties.connections = [];
  2336. }
  2337. properties.connections.push( array );
  2338. continue;
  2339. }
  2340. // special case: child node is Properties\d+
  2341. // move child node's properties to this node.
  2342. if ( node.name.match( /^Properties\d+$/ ) ) {
  2343. var keys = Object.keys( node.properties );
  2344. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  2345. var key = keys[ i ];
  2346. properties[ key ] = node.properties[ key ];
  2347. }
  2348. continue;
  2349. }
  2350. // parse 'properties70'
  2351. if ( name.match( /^Properties\d+$/ ) && node.name === 'P' ) {
  2352. var innerPropName = node.propertyList[ 0 ];
  2353. var innerPropType1 = node.propertyList[ 1 ];
  2354. var innerPropType2 = node.propertyList[ 2 ];
  2355. var innerPropFlag = node.propertyList[ 3 ];
  2356. var innerPropValue;
  2357. if ( innerPropName.indexOf( 'Lcl ' ) === 0 ) innerPropName = innerPropName.replace( 'Lcl ', 'Lcl_' );
  2358. if ( innerPropType1.indexOf( 'Lcl ' ) === 0 ) innerPropType1 = innerPropType1.replace( 'Lcl ', 'Lcl_' );
  2359. if ( innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' || innerPropType1 === 'Vector3D' || innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  2360. innerPropValue = [
  2361. node.propertyList[ 4 ],
  2362. node.propertyList[ 5 ],
  2363. node.propertyList[ 6 ]
  2364. ];
  2365. } else {
  2366. innerPropValue = node.propertyList[ 4 ];
  2367. }
  2368. // this will be copied to parent, see above
  2369. properties[ innerPropName ] = {
  2370. 'type': innerPropType1,
  2371. 'type2': innerPropType2,
  2372. 'flag': innerPropFlag,
  2373. 'value': innerPropValue
  2374. };
  2375. continue;
  2376. }
  2377. if ( subNodes[ node.name ] === undefined ) {
  2378. if ( typeof node.id === 'number' ) {
  2379. subNodes[ node.name ] = {};
  2380. subNodes[ node.name ][ node.id ] = node;
  2381. } else {
  2382. subNodes[ node.name ] = node;
  2383. }
  2384. } else {
  2385. if ( node.id === '' ) {
  2386. if ( ! Array.isArray( subNodes[ node.name ] ) ) {
  2387. subNodes[ node.name ] = [ subNodes[ node.name ] ];
  2388. }
  2389. subNodes[ node.name ].push( node );
  2390. } else {
  2391. if ( subNodes[ node.name ][ node.id ] === undefined ) {
  2392. subNodes[ node.name ][ node.id ] = node;
  2393. } else {
  2394. // conflict id. irregular?
  2395. if ( ! Array.isArray( subNodes[ node.name ][ node.id ] ) ) {
  2396. subNodes[ node.name ][ node.id ] = [ subNodes[ node.name ][ node.id ] ];
  2397. }
  2398. subNodes[ node.name ][ node.id ].push( node );
  2399. }
  2400. }
  2401. }
  2402. }
  2403. return {
  2404. singleProperty: isSingleProperty,
  2405. id: id,
  2406. attrName: attrName,
  2407. attrType: attrType,
  2408. name: name,
  2409. properties: properties,
  2410. propertyList: propertyList, // raw property list used by parent
  2411. subNodes: subNodes
  2412. };
  2413. },
  2414. parseProperty: function ( reader ) {
  2415. var type = reader.getChar();
  2416. switch ( type ) {
  2417. case 'C':
  2418. return reader.getBoolean();
  2419. case 'D':
  2420. return reader.getFloat64();
  2421. case 'F':
  2422. return reader.getFloat32();
  2423. case 'I':
  2424. return reader.getInt32();
  2425. case 'L':
  2426. return reader.getInt64();
  2427. case 'R':
  2428. var length = reader.getUint32();
  2429. return reader.getArrayBuffer( length );
  2430. case 'S':
  2431. var length = reader.getUint32();
  2432. return reader.getString( length );
  2433. case 'Y':
  2434. return reader.getInt16();
  2435. case 'b':
  2436. case 'c':
  2437. case 'd':
  2438. case 'f':
  2439. case 'i':
  2440. case 'l':
  2441. var arrayLength = reader.getUint32();
  2442. var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  2443. var compressedLength = reader.getUint32();
  2444. if ( encoding === 0 ) {
  2445. switch ( type ) {
  2446. case 'b':
  2447. case 'c':
  2448. return reader.getBooleanArray( arrayLength );
  2449. case 'd':
  2450. return reader.getFloat64Array( arrayLength );
  2451. case 'f':
  2452. return reader.getFloat32Array( arrayLength );
  2453. case 'i':
  2454. return reader.getInt32Array( arrayLength );
  2455. case 'l':
  2456. return reader.getInt64Array( arrayLength );
  2457. }
  2458. }
  2459. if ( window.Zlib === undefined ) {
  2460. throw new Error( 'THREE.FBXLoader: External library Inflate.min.js required, obtain or import from https://github.com/imaya/zlib.js' );
  2461. }
  2462. var inflate = new Zlib.Inflate( new Uint8Array( reader.getArrayBuffer( compressedLength ) ) ); // eslint-disable-line no-undef
  2463. var reader2 = new BinaryReader( inflate.decompress().buffer );
  2464. switch ( type ) {
  2465. case 'b':
  2466. case 'c':
  2467. return reader2.getBooleanArray( arrayLength );
  2468. case 'd':
  2469. return reader2.getFloat64Array( arrayLength );
  2470. case 'f':
  2471. return reader2.getFloat32Array( arrayLength );
  2472. case 'i':
  2473. return reader2.getInt32Array( arrayLength );
  2474. case 'l':
  2475. return reader2.getInt64Array( arrayLength );
  2476. }
  2477. default:
  2478. throw new Error( 'THREE.FBXLoader: Unknown property type ' + type );
  2479. }
  2480. }
  2481. } );
  2482. function BinaryReader( buffer, littleEndian ) {
  2483. this.dv = new DataView( buffer );
  2484. this.offset = 0;
  2485. this.littleEndian = ( littleEndian !== undefined ) ? littleEndian : true;
  2486. }
  2487. Object.assign( BinaryReader.prototype, {
  2488. getOffset: function () {
  2489. return this.offset;
  2490. },
  2491. size: function () {
  2492. return this.dv.buffer.byteLength;
  2493. },
  2494. skip: function ( length ) {
  2495. this.offset += length;
  2496. },
  2497. // seems like true/false representation depends on exporter.
  2498. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  2499. // then sees LSB.
  2500. getBoolean: function () {
  2501. return ( this.getUint8() & 1 ) === 1;
  2502. },
  2503. getBooleanArray: function ( size ) {
  2504. var a = [];
  2505. for ( var i = 0; i < size; i ++ ) {
  2506. a.push( this.getBoolean() );
  2507. }
  2508. return a;
  2509. },
  2510. getInt8: function () {
  2511. var value = this.dv.getInt8( this.offset );
  2512. this.offset += 1;
  2513. return value;
  2514. },
  2515. getInt8Array: function ( size ) {
  2516. var a = [];
  2517. for ( var i = 0; i < size; i ++ ) {
  2518. a.push( this.getInt8() );
  2519. }
  2520. return a;
  2521. },
  2522. getUint8: function () {
  2523. var value = this.dv.getUint8( this.offset );
  2524. this.offset += 1;
  2525. return value;
  2526. },
  2527. getUint8Array: function ( size ) {
  2528. var a = [];
  2529. for ( var i = 0; i < size; i ++ ) {
  2530. a.push( this.getUint8() );
  2531. }
  2532. return a;
  2533. },
  2534. getInt16: function () {
  2535. var value = this.dv.getInt16( this.offset, this.littleEndian );
  2536. this.offset += 2;
  2537. return value;
  2538. },
  2539. getInt16Array: function ( size ) {
  2540. var a = [];
  2541. for ( var i = 0; i < size; i ++ ) {
  2542. a.push( this.getInt16() );
  2543. }
  2544. return a;
  2545. },
  2546. getUint16: function () {
  2547. var value = this.dv.getUint16( this.offset, this.littleEndian );
  2548. this.offset += 2;
  2549. return value;
  2550. },
  2551. getUint16Array: function ( size ) {
  2552. var a = [];
  2553. for ( var i = 0; i < size; i ++ ) {
  2554. a.push( this.getUint16() );
  2555. }
  2556. return a;
  2557. },
  2558. getInt32: function () {
  2559. var value = this.dv.getInt32( this.offset, this.littleEndian );
  2560. this.offset += 4;
  2561. return value;
  2562. },
  2563. getInt32Array: function ( size ) {
  2564. var a = [];
  2565. for ( var i = 0; i < size; i ++ ) {
  2566. a.push( this.getInt32() );
  2567. }
  2568. return a;
  2569. },
  2570. getUint32: function () {
  2571. var value = this.dv.getUint32( this.offset, this.littleEndian );
  2572. this.offset += 4;
  2573. return value;
  2574. },
  2575. getUint32Array: function ( size ) {
  2576. var a = [];
  2577. for ( var i = 0; i < size; i ++ ) {
  2578. a.push( this.getUint32() );
  2579. }
  2580. return a;
  2581. },
  2582. // JavaScript doesn't support 64-bit integer so calculate this here
  2583. // 1 << 32 will return 1 so using multiply operation instead here.
  2584. // There's a possibility that this method returns wrong value if the value
  2585. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  2586. // TODO: safely handle 64-bit integer
  2587. getInt64: function () {
  2588. var low, high;
  2589. if ( this.littleEndian ) {
  2590. low = this.getUint32();
  2591. high = this.getUint32();
  2592. } else {
  2593. high = this.getUint32();
  2594. low = this.getUint32();
  2595. }
  2596. // calculate negative value
  2597. if ( high & 0x80000000 ) {
  2598. high = ~ high & 0xFFFFFFFF;
  2599. low = ~ low & 0xFFFFFFFF;
  2600. if ( low === 0xFFFFFFFF ) high = ( high + 1 ) & 0xFFFFFFFF;
  2601. low = ( low + 1 ) & 0xFFFFFFFF;
  2602. return - ( high * 0x100000000 + low );
  2603. }
  2604. return high * 0x100000000 + low;
  2605. },
  2606. getInt64Array: function ( size ) {
  2607. var a = [];
  2608. for ( var i = 0; i < size; i ++ ) {
  2609. a.push( this.getInt64() );
  2610. }
  2611. return a;
  2612. },
  2613. // Note: see getInt64() comment
  2614. getUint64: function () {
  2615. var low, high;
  2616. if ( this.littleEndian ) {
  2617. low = this.getUint32();
  2618. high = this.getUint32();
  2619. } else {
  2620. high = this.getUint32();
  2621. low = this.getUint32();
  2622. }
  2623. return high * 0x100000000 + low;
  2624. },
  2625. getUint64Array: function ( size ) {
  2626. var a = [];
  2627. for ( var i = 0; i < size; i ++ ) {
  2628. a.push( this.getUint64() );
  2629. }
  2630. return a;
  2631. },
  2632. getFloat32: function () {
  2633. var value = this.dv.getFloat32( this.offset, this.littleEndian );
  2634. this.offset += 4;
  2635. return value;
  2636. },
  2637. getFloat32Array: function ( size ) {
  2638. var a = [];
  2639. for ( var i = 0; i < size; i ++ ) {
  2640. a.push( this.getFloat32() );
  2641. }
  2642. return a;
  2643. },
  2644. getFloat64: function () {
  2645. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  2646. this.offset += 8;
  2647. return value;
  2648. },
  2649. getFloat64Array: function ( size ) {
  2650. var a = [];
  2651. for ( var i = 0; i < size; i ++ ) {
  2652. a.push( this.getFloat64() );
  2653. }
  2654. return a;
  2655. },
  2656. getArrayBuffer: function ( size ) {
  2657. var value = this.dv.buffer.slice( this.offset, this.offset + size );
  2658. this.offset += size;
  2659. return value;
  2660. },
  2661. getChar: function () {
  2662. return String.fromCharCode( this.getUint8() );
  2663. },
  2664. getString: function ( size ) {
  2665. var s = '';
  2666. while ( size > 0 ) {
  2667. var value = this.getUint8();
  2668. size --;
  2669. if ( value === 0 ) break;
  2670. s += String.fromCharCode( value );
  2671. }
  2672. // Manage UTF8 encoding
  2673. s = decodeURIComponent( escape( s ) );
  2674. this.skip( size );
  2675. return s;
  2676. }
  2677. } );
  2678. // FBXTree holds a representation of the FBX data, returned by the TextParser ( FBX ASCII format)
  2679. // and BinaryParser( FBX Binary format)
  2680. function FBXTree() {}
  2681. Object.assign( FBXTree.prototype, {
  2682. add: function ( key, val ) {
  2683. this[ key ] = val;
  2684. },
  2685. } );
  2686. function isFbxFormatBinary( buffer ) {
  2687. var CORRECT = 'Kaydara FBX Binary \0';
  2688. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString( buffer, 0, CORRECT.length );
  2689. }
  2690. function isFbxFormatASCII( text ) {
  2691. var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  2692. var cursor = 0;
  2693. function read( offset ) {
  2694. var result = text[ offset - 1 ];
  2695. text = text.slice( cursor + offset );
  2696. cursor ++;
  2697. return result;
  2698. }
  2699. for ( var i = 0; i < CORRECT.length; ++ i ) {
  2700. var num = read( 1 );
  2701. if ( num === CORRECT[ i ] ) {
  2702. return false;
  2703. }
  2704. }
  2705. return true;
  2706. }
  2707. function getFbxVersion( text ) {
  2708. var versionRegExp = /FBXVersion: (\d+)/;
  2709. var match = text.match( versionRegExp );
  2710. if ( match ) {
  2711. var version = parseInt( match[ 1 ] );
  2712. return version;
  2713. }
  2714. throw new Error( 'THREE.FBXLoader: Cannot find the version number for the file given.' );
  2715. }
  2716. // Converts FBX ticks into real time seconds.
  2717. function convertFBXTimeToSeconds( time ) {
  2718. return time / 46186158000;
  2719. }
  2720. // Parses comma separated list of numbers and returns them an array.
  2721. // Used internally by the TextParser
  2722. function parseNumberArray( value ) {
  2723. var array = value.split( ',' );
  2724. for ( var i = 0, l = array.length; i < l; i ++ ) {
  2725. array[ i ] = parseFloat( array[ i ] );
  2726. }
  2727. return array;
  2728. }
  2729. function parseVector3( property ) {
  2730. return new THREE.Vector3().fromArray( property.value );
  2731. }
  2732. function parseColor( property ) {
  2733. return new THREE.Color().fromArray( property.value );
  2734. }
  2735. // Converts ArrayBuffer to String.
  2736. function convertArrayBufferToString( buffer, from, to ) {
  2737. if ( from === undefined ) from = 0;
  2738. if ( to === undefined ) to = buffer.byteLength;
  2739. var array = new Uint8Array( buffer, from, to );
  2740. if ( window.TextDecoder !== undefined ) {
  2741. return new TextDecoder().decode( array );
  2742. }
  2743. var s = '';
  2744. for ( var i = 0, il = array.length; i < il; i ++ ) {
  2745. s += String.fromCharCode( array[ i ] );
  2746. }
  2747. return s;
  2748. }
  2749. function findIndex( array, func ) {
  2750. for ( var i = 0, l = array.length; i < l; i ++ ) {
  2751. if ( func( array[ i ] ) ) return i;
  2752. }
  2753. return - 1;
  2754. }
  2755. function append( a, b ) {
  2756. for ( var i = 0, j = a.length, l = b.length; i < l; i ++, j ++ ) {
  2757. a[ j ] = b[ i ];
  2758. }
  2759. }
  2760. function slice( a, b, from, to ) {
  2761. for ( var i = from, j = 0; i < to; i ++, j ++ ) {
  2762. a[ j ] = b[ i ];
  2763. }
  2764. return a;
  2765. }
  2766. } )();