FBXLoader.js 109 KB

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