FBXLoader.js 99 KB

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