FBXLoader.js 99 KB

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