FBXLoader.js 100 KB

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