FBXLoader.js 89 KB

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