FBXLoader.js 97 KB

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