FBXLoader.js 98 KB

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