FBXLoader.js 97 KB

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