FBXLoader.js 97 KB

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