FBXLoader.js 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163
  1. /**
  2. * @author Kyle-Larson https://github.com/Kyle-Larson
  3. * @author Takahiro https://github.com/takahirox
  4. * @author Lewy Blue https://github.com/looeee
  5. *
  6. * Loader loads FBX file and generates Group representing FBX scene.
  7. * Requires FBX file to be >= 7.0 and in ASCII or >= 6400 in Binary format
  8. * Versions lower than this may load but will probably have errors
  9. *
  10. * Needs Support:
  11. * Morph normals / blend shape normals
  12. *
  13. * FBX format references:
  14. * https://wiki.blender.org/index.php/User:Mont29/Foundation/FBX_File_Structure
  15. * http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_index_html (C++ SDK reference)
  16. *
  17. * Binary format specification:
  18. * https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  19. */
  20. import {
  21. AmbientLight,
  22. AnimationClip,
  23. Bone,
  24. BufferAttribute,
  25. BufferGeometry,
  26. ClampToEdgeWrapping,
  27. Color,
  28. DirectionalLight,
  29. EquirectangularReflectionMapping,
  30. Euler,
  31. FileLoader,
  32. Float32BufferAttribute,
  33. Group,
  34. Line,
  35. LineBasicMaterial,
  36. Loader,
  37. LoaderUtils,
  38. MathUtils,
  39. Matrix3,
  40. Matrix4,
  41. Mesh,
  42. MeshLambertMaterial,
  43. MeshPhongMaterial,
  44. NumberKeyframeTrack,
  45. Object3D,
  46. OrthographicCamera,
  47. PerspectiveCamera,
  48. PointLight,
  49. PropertyBinding,
  50. Quaternion,
  51. QuaternionKeyframeTrack,
  52. RepeatWrapping,
  53. Skeleton,
  54. SkinnedMesh,
  55. SpotLight,
  56. Texture,
  57. TextureLoader,
  58. Uint16BufferAttribute,
  59. Vector3,
  60. Vector4,
  61. VectorKeyframeTrack,
  62. VertexColors,
  63. sRGBEncoding
  64. } from "../../../build/three.module.js";
  65. import { Zlib } from "../libs/inflate.module.min.js";
  66. import { NURBSCurve } from "../curves/NURBSCurve.js";
  67. var FBXLoader = ( function () {
  68. var fbxTree;
  69. var connections;
  70. var sceneGraph;
  71. function FBXLoader( manager ) {
  72. Loader.call( this, manager );
  73. }
  74. FBXLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  75. constructor: FBXLoader,
  76. load: function ( url, onLoad, onProgress, onError ) {
  77. var self = this;
  78. var path = ( self.path === '' ) ? LoaderUtils.extractUrlBase( url ) : self.path;
  79. var loader = new FileLoader( this.manager );
  80. loader.setPath( self.path );
  81. loader.setResponseType( 'arraybuffer' );
  82. loader.load( url, function ( buffer ) {
  83. try {
  84. onLoad( self.parse( buffer, path ) );
  85. } catch ( error ) {
  86. setTimeout( function () {
  87. if ( onError ) onError( error );
  88. self.manager.itemError( url );
  89. }, 0 );
  90. }
  91. }, onProgress, onError );
  92. },
  93. parse: function ( FBXBuffer, path ) {
  94. if ( isFbxFormatBinary( FBXBuffer ) ) {
  95. fbxTree = new BinaryParser().parse( FBXBuffer );
  96. } else {
  97. var FBXText = convertArrayBufferToString( FBXBuffer );
  98. if ( ! isFbxFormatASCII( FBXText ) ) {
  99. throw new Error( 'THREE.FBXLoader: Unknown format.' );
  100. }
  101. if ( getFbxVersion( FBXText ) < 7000 ) {
  102. throw new Error( 'THREE.FBXLoader: FBX version not supported, FileVersion: ' + getFbxVersion( FBXText ) );
  103. }
  104. fbxTree = new TextParser().parse( FBXText );
  105. }
  106. // console.log( fbxTree );
  107. var textureLoader = new TextureLoader( this.manager ).setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  108. return new FBXTreeParser( textureLoader, this.manager ).parse( fbxTree );
  109. }
  110. } );
  111. // Parse the FBXTree object returned by the BinaryParser or TextParser and return a Group
  112. function FBXTreeParser( textureLoader, manager ) {
  113. this.textureLoader = textureLoader;
  114. this.manager = manager;
  115. }
  116. FBXTreeParser.prototype = {
  117. constructor: FBXTreeParser,
  118. parse: function () {
  119. connections = this.parseConnections();
  120. var images = this.parseImages();
  121. var textures = this.parseTextures( images );
  122. var materials = this.parseMaterials( textures );
  123. var deformers = this.parseDeformers();
  124. var geometryMap = new GeometryParser().parse( deformers );
  125. this.parseScene( deformers, geometryMap, materials );
  126. return sceneGraph;
  127. },
  128. // Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry )
  129. // and details the connection type
  130. parseConnections: function () {
  131. var connectionMap = new Map();
  132. if ( 'Connections' in fbxTree ) {
  133. var rawConnections = fbxTree.Connections.connections;
  134. rawConnections.forEach( function ( rawConnection ) {
  135. var fromID = rawConnection[ 0 ];
  136. var toID = rawConnection[ 1 ];
  137. var relationship = rawConnection[ 2 ];
  138. if ( ! connectionMap.has( fromID ) ) {
  139. connectionMap.set( fromID, {
  140. parents: [],
  141. children: []
  142. } );
  143. }
  144. var parentRelationship = { ID: toID, relationship: relationship };
  145. connectionMap.get( fromID ).parents.push( parentRelationship );
  146. if ( ! connectionMap.has( toID ) ) {
  147. connectionMap.set( toID, {
  148. parents: [],
  149. children: []
  150. } );
  151. }
  152. var childRelationship = { ID: fromID, relationship: relationship };
  153. connectionMap.get( toID ).children.push( childRelationship );
  154. } );
  155. }
  156. return connectionMap;
  157. },
  158. // Parse FBXTree.Objects.Video for embedded image data
  159. // These images are connected to textures in FBXTree.Objects.Textures
  160. // via FBXTree.Connections.
  161. parseImages: function () {
  162. var images = {};
  163. var blobs = {};
  164. if ( 'Video' in fbxTree.Objects ) {
  165. var videoNodes = fbxTree.Objects.Video;
  166. for ( var nodeID in videoNodes ) {
  167. var videoNode = videoNodes[ nodeID ];
  168. var id = parseInt( nodeID );
  169. images[ id ] = videoNode.RelativeFilename || videoNode.Filename;
  170. // raw image data is in videoNode.Content
  171. if ( 'Content' in videoNode ) {
  172. var arrayBufferContent = ( videoNode.Content instanceof ArrayBuffer ) && ( videoNode.Content.byteLength > 0 );
  173. var base64Content = ( typeof videoNode.Content === 'string' ) && ( videoNode.Content !== '' );
  174. if ( arrayBufferContent || base64Content ) {
  175. var image = this.parseImage( videoNodes[ nodeID ] );
  176. blobs[ videoNode.RelativeFilename || videoNode.Filename ] = image;
  177. }
  178. }
  179. }
  180. }
  181. for ( var id in images ) {
  182. var filename = images[ id ];
  183. if ( blobs[ filename ] !== undefined ) images[ id ] = blobs[ filename ];
  184. else images[ id ] = images[ id ].split( '\\' ).pop();
  185. }
  186. return images;
  187. },
  188. // Parse embedded image data in FBXTree.Video.Content
  189. parseImage: function ( videoNode ) {
  190. var content = videoNode.Content;
  191. var fileName = videoNode.RelativeFilename || videoNode.Filename;
  192. var extension = fileName.slice( fileName.lastIndexOf( '.' ) + 1 ).toLowerCase();
  193. var type;
  194. switch ( extension ) {
  195. case 'bmp':
  196. type = 'image/bmp';
  197. break;
  198. case 'jpg':
  199. case 'jpeg':
  200. type = 'image/jpeg';
  201. break;
  202. case 'png':
  203. type = 'image/png';
  204. break;
  205. case 'tif':
  206. type = 'image/tiff';
  207. break;
  208. case 'tga':
  209. if ( this.manager.getHandler( '.tga' ) === null ) {
  210. console.warn( 'FBXLoader: TGA loader not found, skipping ', fileName );
  211. }
  212. type = 'image/tga';
  213. break;
  214. default:
  215. console.warn( 'FBXLoader: Image type "' + extension + '" is not supported.' );
  216. return;
  217. }
  218. if ( typeof content === 'string' ) { // ASCII format
  219. return 'data:' + type + ';base64,' + content;
  220. } else { // Binary Format
  221. var array = new Uint8Array( content );
  222. return window.URL.createObjectURL( new Blob( [ array ], { type: type } ) );
  223. }
  224. },
  225. // Parse nodes in FBXTree.Objects.Texture
  226. // These contain details such as UV scaling, cropping, rotation etc and are connected
  227. // to images in FBXTree.Objects.Video
  228. parseTextures: function ( images ) {
  229. var textureMap = new Map();
  230. if ( 'Texture' in fbxTree.Objects ) {
  231. var textureNodes = fbxTree.Objects.Texture;
  232. for ( var nodeID in textureNodes ) {
  233. var texture = this.parseTexture( textureNodes[ nodeID ], images );
  234. textureMap.set( parseInt( nodeID ), texture );
  235. }
  236. }
  237. return textureMap;
  238. },
  239. // Parse individual node in FBXTree.Objects.Texture
  240. parseTexture: function ( textureNode, images ) {
  241. var texture = this.loadTexture( textureNode, images );
  242. texture.ID = textureNode.id;
  243. texture.name = textureNode.attrName;
  244. var wrapModeU = textureNode.WrapModeU;
  245. var wrapModeV = textureNode.WrapModeV;
  246. var valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
  247. var valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
  248. // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
  249. // 0: repeat(default), 1: clamp
  250. texture.wrapS = valueU === 0 ? RepeatWrapping : ClampToEdgeWrapping;
  251. texture.wrapT = valueV === 0 ? RepeatWrapping : ClampToEdgeWrapping;
  252. if ( 'Scaling' in textureNode ) {
  253. var values = textureNode.Scaling.value;
  254. texture.repeat.x = values[ 0 ];
  255. texture.repeat.y = values[ 1 ];
  256. }
  257. return texture;
  258. },
  259. // load a texture specified as a blob or data URI, or via an external URL using TextureLoader
  260. loadTexture: function ( textureNode, images ) {
  261. var fileName;
  262. var currentPath = this.textureLoader.path;
  263. var children = connections.get( textureNode.id ).children;
  264. if ( children !== undefined && children.length > 0 && images[ children[ 0 ].ID ] !== undefined ) {
  265. fileName = images[ children[ 0 ].ID ];
  266. if ( fileName.indexOf( 'blob:' ) === 0 || fileName.indexOf( 'data:' ) === 0 ) {
  267. this.textureLoader.setPath( undefined );
  268. }
  269. }
  270. var texture;
  271. var extension = textureNode.FileName.slice( - 3 ).toLowerCase();
  272. if ( extension === 'tga' ) {
  273. var loader = this.manager.getHandler( '.tga' );
  274. if ( loader === null ) {
  275. console.warn( 'FBXLoader: TGA loader not found, creating placeholder texture for', textureNode.RelativeFilename );
  276. texture = new Texture();
  277. } else {
  278. texture = loader.load( fileName );
  279. }
  280. } else if ( extension === 'psd' ) {
  281. console.warn( 'FBXLoader: PSD textures are not supported, creating placeholder texture for', textureNode.RelativeFilename );
  282. texture = new Texture();
  283. } else {
  284. texture = this.textureLoader.load( fileName );
  285. }
  286. this.textureLoader.setPath( currentPath );
  287. return texture;
  288. },
  289. // Parse nodes in FBXTree.Objects.Material
  290. parseMaterials: function ( textureMap ) {
  291. var materialMap = new Map();
  292. if ( 'Material' in fbxTree.Objects ) {
  293. var materialNodes = fbxTree.Objects.Material;
  294. for ( var nodeID in materialNodes ) {
  295. var material = this.parseMaterial( materialNodes[ nodeID ], textureMap );
  296. if ( material !== null ) materialMap.set( parseInt( nodeID ), material );
  297. }
  298. }
  299. return materialMap;
  300. },
  301. // Parse single node in FBXTree.Objects.Material
  302. // Materials are connected to texture maps in FBXTree.Objects.Textures
  303. // FBX format currently only supports Lambert and Phong shading models
  304. parseMaterial: function ( materialNode, textureMap ) {
  305. var ID = materialNode.id;
  306. var name = materialNode.attrName;
  307. var type = materialNode.ShadingModel;
  308. // Case where FBX wraps shading model in property object.
  309. if ( typeof type === 'object' ) {
  310. type = type.value;
  311. }
  312. // Ignore unused materials which don't have any connections.
  313. if ( ! connections.has( ID ) ) return null;
  314. var parameters = this.parseParameters( materialNode, textureMap, ID );
  315. var material;
  316. switch ( type.toLowerCase() ) {
  317. case 'phong':
  318. material = new MeshPhongMaterial();
  319. break;
  320. case 'lambert':
  321. material = new MeshLambertMaterial();
  322. break;
  323. default:
  324. console.warn( 'THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.', type );
  325. material = new MeshPhongMaterial();
  326. break;
  327. }
  328. material.setValues( parameters );
  329. material.name = name;
  330. return material;
  331. },
  332. // Parse FBX material and return parameters suitable for a three.js material
  333. // Also parse the texture map and return any textures associated with the material
  334. parseParameters: function ( materialNode, textureMap, ID ) {
  335. var parameters = {};
  336. if ( materialNode.BumpFactor ) {
  337. parameters.bumpScale = materialNode.BumpFactor.value;
  338. }
  339. if ( materialNode.Diffuse ) {
  340. parameters.color = new Color().fromArray( materialNode.Diffuse.value );
  341. } else if ( materialNode.DiffuseColor && materialNode.DiffuseColor.type === 'Color' ) {
  342. // The blender exporter exports diffuse here instead of in materialNode.Diffuse
  343. parameters.color = new Color().fromArray( materialNode.DiffuseColor.value );
  344. }
  345. if ( materialNode.DisplacementFactor ) {
  346. parameters.displacementScale = materialNode.DisplacementFactor.value;
  347. }
  348. if ( materialNode.Emissive ) {
  349. parameters.emissive = new Color().fromArray( materialNode.Emissive.value );
  350. } else if ( materialNode.EmissiveColor && materialNode.EmissiveColor.type === 'Color' ) {
  351. // The blender exporter exports emissive color here instead of in materialNode.Emissive
  352. parameters.emissive = new Color().fromArray( materialNode.EmissiveColor.value );
  353. }
  354. if ( materialNode.EmissiveFactor ) {
  355. parameters.emissiveIntensity = parseFloat( materialNode.EmissiveFactor.value );
  356. }
  357. if ( materialNode.Opacity ) {
  358. parameters.opacity = parseFloat( materialNode.Opacity.value );
  359. }
  360. if ( parameters.opacity < 1.0 ) {
  361. parameters.transparent = true;
  362. }
  363. if ( materialNode.ReflectionFactor ) {
  364. parameters.reflectivity = materialNode.ReflectionFactor.value;
  365. }
  366. if ( materialNode.Shininess ) {
  367. parameters.shininess = materialNode.Shininess.value;
  368. }
  369. if ( materialNode.Specular ) {
  370. parameters.specular = new Color().fromArray( materialNode.Specular.value );
  371. } else if ( materialNode.SpecularColor && materialNode.SpecularColor.type === 'Color' ) {
  372. // The blender exporter exports specular color here instead of in materialNode.Specular
  373. parameters.specular = new Color().fromArray( materialNode.SpecularColor.value );
  374. }
  375. var self = this;
  376. connections.get( ID ).children.forEach( function ( child ) {
  377. var type = child.relationship;
  378. switch ( type ) {
  379. case 'Bump':
  380. parameters.bumpMap = self.getTexture( textureMap, child.ID );
  381. break;
  382. case 'Maya|TEX_ao_map':
  383. parameters.aoMap = self.getTexture( textureMap, child.ID );
  384. break;
  385. case 'DiffuseColor':
  386. case 'Maya|TEX_color_map':
  387. parameters.map = self.getTexture( textureMap, child.ID );
  388. parameters.map.encoding = sRGBEncoding;
  389. break;
  390. case 'DisplacementColor':
  391. parameters.displacementMap = self.getTexture( textureMap, child.ID );
  392. break;
  393. case 'EmissiveColor':
  394. parameters.emissiveMap = self.getTexture( textureMap, child.ID );
  395. parameters.emissiveMap.encoding = sRGBEncoding;
  396. break;
  397. case 'NormalMap':
  398. case 'Maya|TEX_normal_map':
  399. parameters.normalMap = self.getTexture( textureMap, child.ID );
  400. break;
  401. case 'ReflectionColor':
  402. parameters.envMap = self.getTexture( textureMap, child.ID );
  403. parameters.envMap.mapping = EquirectangularReflectionMapping;
  404. parameters.envMap.encoding = sRGBEncoding;
  405. break;
  406. case 'SpecularColor':
  407. parameters.specularMap = self.getTexture( textureMap, child.ID );
  408. parameters.specularMap.encoding = sRGBEncoding;
  409. break;
  410. case 'TransparentColor':
  411. parameters.alphaMap = self.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 self = this;
  520. modelMap.forEach( function ( model ) {
  521. var modelNode = modelNodes[ model.ID ];
  522. self.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 = VertexColors;
  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 self = 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. self.setupMorphMaterial( child, material, i );
  883. } );
  884. } else {
  885. self.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. geoInfo.uv.push( this.parseUVs( geoNode.LayerElementUV[ i ] ) );
  1050. i ++;
  1051. }
  1052. }
  1053. geoInfo.weightTable = {};
  1054. if ( skeleton !== null ) {
  1055. geoInfo.skeleton = skeleton;
  1056. skeleton.rawBones.forEach( function ( rawBone, i ) {
  1057. // loop over the bone's vertex indices and weights
  1058. rawBone.indices.forEach( function ( index, j ) {
  1059. if ( geoInfo.weightTable[ index ] === undefined ) geoInfo.weightTable[ index ] = [];
  1060. geoInfo.weightTable[ index ].push( {
  1061. id: i,
  1062. weight: rawBone.weights[ j ],
  1063. } );
  1064. } );
  1065. } );
  1066. }
  1067. return geoInfo;
  1068. },
  1069. genBuffers: function ( geoInfo ) {
  1070. var buffers = {
  1071. vertex: [],
  1072. normal: [],
  1073. colors: [],
  1074. uvs: [],
  1075. materialIndex: [],
  1076. vertexWeights: [],
  1077. weightsIndices: [],
  1078. };
  1079. var polygonIndex = 0;
  1080. var faceLength = 0;
  1081. var displayedWeightsWarning = false;
  1082. // these will hold data for a single face
  1083. var facePositionIndexes = [];
  1084. var faceNormals = [];
  1085. var faceColors = [];
  1086. var faceUVs = [];
  1087. var faceWeights = [];
  1088. var faceWeightIndices = [];
  1089. var self = this;
  1090. geoInfo.vertexIndices.forEach( function ( vertexIndex, polygonVertexIndex ) {
  1091. var endOfFace = false;
  1092. // Face index and vertex index arrays are combined in a single array
  1093. // A cube with quad faces looks like this:
  1094. // PolygonVertexIndex: *24 {
  1095. // a: 0, 1, 3, -3, 2, 3, 5, -5, 4, 5, 7, -7, 6, 7, 1, -1, 1, 7, 5, -4, 6, 0, 2, -5
  1096. // }
  1097. // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3
  1098. // to find index of last vertex bit shift the index: ^ - 1
  1099. if ( vertexIndex < 0 ) {
  1100. vertexIndex = vertexIndex ^ - 1; // equivalent to ( x * -1 ) - 1
  1101. endOfFace = true;
  1102. }
  1103. var weightIndices = [];
  1104. var weights = [];
  1105. facePositionIndexes.push( vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2 );
  1106. if ( geoInfo.color ) {
  1107. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.color );
  1108. faceColors.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  1109. }
  1110. if ( geoInfo.skeleton ) {
  1111. if ( geoInfo.weightTable[ vertexIndex ] !== undefined ) {
  1112. geoInfo.weightTable[ vertexIndex ].forEach( function ( wt ) {
  1113. weights.push( wt.weight );
  1114. weightIndices.push( wt.id );
  1115. } );
  1116. }
  1117. if ( weights.length > 4 ) {
  1118. if ( ! displayedWeightsWarning ) {
  1119. console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
  1120. displayedWeightsWarning = true;
  1121. }
  1122. var wIndex = [ 0, 0, 0, 0 ];
  1123. var Weight = [ 0, 0, 0, 0 ];
  1124. weights.forEach( function ( weight, weightIndex ) {
  1125. var currentWeight = weight;
  1126. var currentIndex = weightIndices[ weightIndex ];
  1127. Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) {
  1128. if ( currentWeight > comparedWeight ) {
  1129. comparedWeightArray[ comparedWeightIndex ] = currentWeight;
  1130. currentWeight = comparedWeight;
  1131. var tmp = wIndex[ comparedWeightIndex ];
  1132. wIndex[ comparedWeightIndex ] = currentIndex;
  1133. currentIndex = tmp;
  1134. }
  1135. } );
  1136. } );
  1137. weightIndices = wIndex;
  1138. weights = Weight;
  1139. }
  1140. // if the weight array is shorter than 4 pad with 0s
  1141. while ( weights.length < 4 ) {
  1142. weights.push( 0 );
  1143. weightIndices.push( 0 );
  1144. }
  1145. for ( var i = 0; i < 4; ++ i ) {
  1146. faceWeights.push( weights[ i ] );
  1147. faceWeightIndices.push( weightIndices[ i ] );
  1148. }
  1149. }
  1150. if ( geoInfo.normal ) {
  1151. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.normal );
  1152. faceNormals.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  1153. }
  1154. if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {
  1155. var materialIndex = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.material )[ 0 ];
  1156. }
  1157. if ( geoInfo.uv ) {
  1158. geoInfo.uv.forEach( function ( uv, i ) {
  1159. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, uv );
  1160. if ( faceUVs[ i ] === undefined ) {
  1161. faceUVs[ i ] = [];
  1162. }
  1163. faceUVs[ i ].push( data[ 0 ] );
  1164. faceUVs[ i ].push( data[ 1 ] );
  1165. } );
  1166. }
  1167. faceLength ++;
  1168. if ( endOfFace ) {
  1169. self.genFace( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength );
  1170. polygonIndex ++;
  1171. faceLength = 0;
  1172. // reset arrays for the next face
  1173. facePositionIndexes = [];
  1174. faceNormals = [];
  1175. faceColors = [];
  1176. faceUVs = [];
  1177. faceWeights = [];
  1178. faceWeightIndices = [];
  1179. }
  1180. } );
  1181. return buffers;
  1182. },
  1183. // Generate data for a single face in a geometry. If the face is a quad then split it into 2 tris
  1184. genFace: function ( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength ) {
  1185. for ( var i = 2; i < faceLength; i ++ ) {
  1186. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 0 ] ] );
  1187. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 1 ] ] );
  1188. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 2 ] ] );
  1189. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 ] ] );
  1190. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 1 ] ] );
  1191. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 2 ] ] );
  1192. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 ] ] );
  1193. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 1 ] ] );
  1194. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 2 ] ] );
  1195. if ( geoInfo.skeleton ) {
  1196. buffers.vertexWeights.push( faceWeights[ 0 ] );
  1197. buffers.vertexWeights.push( faceWeights[ 1 ] );
  1198. buffers.vertexWeights.push( faceWeights[ 2 ] );
  1199. buffers.vertexWeights.push( faceWeights[ 3 ] );
  1200. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 ] );
  1201. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 1 ] );
  1202. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 2 ] );
  1203. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 3 ] );
  1204. buffers.vertexWeights.push( faceWeights[ i * 4 ] );
  1205. buffers.vertexWeights.push( faceWeights[ i * 4 + 1 ] );
  1206. buffers.vertexWeights.push( faceWeights[ i * 4 + 2 ] );
  1207. buffers.vertexWeights.push( faceWeights[ i * 4 + 3 ] );
  1208. buffers.weightsIndices.push( faceWeightIndices[ 0 ] );
  1209. buffers.weightsIndices.push( faceWeightIndices[ 1 ] );
  1210. buffers.weightsIndices.push( faceWeightIndices[ 2 ] );
  1211. buffers.weightsIndices.push( faceWeightIndices[ 3 ] );
  1212. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 ] );
  1213. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 1 ] );
  1214. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 2 ] );
  1215. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 3 ] );
  1216. buffers.weightsIndices.push( faceWeightIndices[ i * 4 ] );
  1217. buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 1 ] );
  1218. buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 2 ] );
  1219. buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 3 ] );
  1220. }
  1221. if ( geoInfo.color ) {
  1222. buffers.colors.push( faceColors[ 0 ] );
  1223. buffers.colors.push( faceColors[ 1 ] );
  1224. buffers.colors.push( faceColors[ 2 ] );
  1225. buffers.colors.push( faceColors[ ( i - 1 ) * 3 ] );
  1226. buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 1 ] );
  1227. buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 2 ] );
  1228. buffers.colors.push( faceColors[ i * 3 ] );
  1229. buffers.colors.push( faceColors[ i * 3 + 1 ] );
  1230. buffers.colors.push( faceColors[ i * 3 + 2 ] );
  1231. }
  1232. if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {
  1233. buffers.materialIndex.push( materialIndex );
  1234. buffers.materialIndex.push( materialIndex );
  1235. buffers.materialIndex.push( materialIndex );
  1236. }
  1237. if ( geoInfo.normal ) {
  1238. buffers.normal.push( faceNormals[ 0 ] );
  1239. buffers.normal.push( faceNormals[ 1 ] );
  1240. buffers.normal.push( faceNormals[ 2 ] );
  1241. buffers.normal.push( faceNormals[ ( i - 1 ) * 3 ] );
  1242. buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 1 ] );
  1243. buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 2 ] );
  1244. buffers.normal.push( faceNormals[ i * 3 ] );
  1245. buffers.normal.push( faceNormals[ i * 3 + 1 ] );
  1246. buffers.normal.push( faceNormals[ i * 3 + 2 ] );
  1247. }
  1248. if ( geoInfo.uv ) {
  1249. geoInfo.uv.forEach( function ( uv, j ) {
  1250. if ( buffers.uvs[ j ] === undefined ) buffers.uvs[ j ] = [];
  1251. buffers.uvs[ j ].push( faceUVs[ j ][ 0 ] );
  1252. buffers.uvs[ j ].push( faceUVs[ j ][ 1 ] );
  1253. buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 ] );
  1254. buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 + 1 ] );
  1255. buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 ] );
  1256. buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 + 1 ] );
  1257. } );
  1258. }
  1259. }
  1260. },
  1261. addMorphTargets: function ( parentGeo, parentGeoNode, morphTargets, preTransform ) {
  1262. if ( morphTargets.length === 0 ) return;
  1263. parentGeo.morphTargetsRelative = true;
  1264. parentGeo.morphAttributes.position = [];
  1265. // parentGeo.morphAttributes.normal = []; // not implemented
  1266. var self = this;
  1267. morphTargets.forEach( function ( morphTarget ) {
  1268. morphTarget.rawTargets.forEach( function ( rawTarget ) {
  1269. var morphGeoNode = fbxTree.Objects.Geometry[ rawTarget.geoID ];
  1270. if ( morphGeoNode !== undefined ) {
  1271. self.genMorphGeometry( parentGeo, parentGeoNode, morphGeoNode, preTransform, rawTarget.name );
  1272. }
  1273. } );
  1274. } );
  1275. },
  1276. // a morph geometry node is similar to a standard node, and the node is also contained
  1277. // in FBXTree.Objects.Geometry, however it can only have attributes for position, normal
  1278. // and a special attribute Index defining which vertices of the original geometry are affected
  1279. // Normal and position attributes only have data for the vertices that are affected by the morph
  1280. genMorphGeometry: function ( parentGeo, parentGeoNode, morphGeoNode, preTransform, name ) {
  1281. var vertexIndices = ( parentGeoNode.PolygonVertexIndex !== undefined ) ? parentGeoNode.PolygonVertexIndex.a : [];
  1282. var morphPositionsSparse = ( morphGeoNode.Vertices !== undefined ) ? morphGeoNode.Vertices.a : [];
  1283. var indices = ( morphGeoNode.Indexes !== undefined ) ? morphGeoNode.Indexes.a : [];
  1284. var length = parentGeo.attributes.position.count * 3;
  1285. var morphPositions = new Float32Array( length );
  1286. for ( var i = 0; i < indices.length; i ++ ) {
  1287. var morphIndex = indices[ i ] * 3;
  1288. morphPositions[ morphIndex ] = morphPositionsSparse[ i * 3 ];
  1289. morphPositions[ morphIndex + 1 ] = morphPositionsSparse[ i * 3 + 1 ];
  1290. morphPositions[ morphIndex + 2 ] = morphPositionsSparse[ i * 3 + 2 ];
  1291. }
  1292. // TODO: add morph normal support
  1293. var morphGeoInfo = {
  1294. vertexIndices: vertexIndices,
  1295. vertexPositions: morphPositions,
  1296. };
  1297. var morphBuffers = this.genBuffers( morphGeoInfo );
  1298. var positionAttribute = new Float32BufferAttribute( morphBuffers.vertex, 3 );
  1299. positionAttribute.name = name || morphGeoNode.attrName;
  1300. positionAttribute.applyMatrix4( preTransform );
  1301. parentGeo.morphAttributes.position.push( positionAttribute );
  1302. },
  1303. // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists
  1304. parseNormals: function ( NormalNode ) {
  1305. var mappingType = NormalNode.MappingInformationType;
  1306. var referenceType = NormalNode.ReferenceInformationType;
  1307. var buffer = NormalNode.Normals.a;
  1308. var indexBuffer = [];
  1309. if ( referenceType === 'IndexToDirect' ) {
  1310. if ( 'NormalIndex' in NormalNode ) {
  1311. indexBuffer = NormalNode.NormalIndex.a;
  1312. } else if ( 'NormalsIndex' in NormalNode ) {
  1313. indexBuffer = NormalNode.NormalsIndex.a;
  1314. }
  1315. }
  1316. return {
  1317. dataSize: 3,
  1318. buffer: buffer,
  1319. indices: indexBuffer,
  1320. mappingType: mappingType,
  1321. referenceType: referenceType
  1322. };
  1323. },
  1324. // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists
  1325. parseUVs: function ( UVNode ) {
  1326. var mappingType = UVNode.MappingInformationType;
  1327. var referenceType = UVNode.ReferenceInformationType;
  1328. var buffer = UVNode.UV.a;
  1329. var indexBuffer = [];
  1330. if ( referenceType === 'IndexToDirect' ) {
  1331. indexBuffer = UVNode.UVIndex.a;
  1332. }
  1333. return {
  1334. dataSize: 2,
  1335. buffer: buffer,
  1336. indices: indexBuffer,
  1337. mappingType: mappingType,
  1338. referenceType: referenceType
  1339. };
  1340. },
  1341. // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists
  1342. parseVertexColors: function ( ColorNode ) {
  1343. var mappingType = ColorNode.MappingInformationType;
  1344. var referenceType = ColorNode.ReferenceInformationType;
  1345. var buffer = ColorNode.Colors.a;
  1346. var indexBuffer = [];
  1347. if ( referenceType === 'IndexToDirect' ) {
  1348. indexBuffer = ColorNode.ColorIndex.a;
  1349. }
  1350. return {
  1351. dataSize: 4,
  1352. buffer: buffer,
  1353. indices: indexBuffer,
  1354. mappingType: mappingType,
  1355. referenceType: referenceType
  1356. };
  1357. },
  1358. // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists
  1359. parseMaterialIndices: function ( MaterialNode ) {
  1360. var mappingType = MaterialNode.MappingInformationType;
  1361. var referenceType = MaterialNode.ReferenceInformationType;
  1362. if ( mappingType === 'NoMappingInformation' ) {
  1363. return {
  1364. dataSize: 1,
  1365. buffer: [ 0 ],
  1366. indices: [ 0 ],
  1367. mappingType: 'AllSame',
  1368. referenceType: referenceType
  1369. };
  1370. }
  1371. var materialIndexBuffer = MaterialNode.Materials.a;
  1372. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  1373. // we expect.So we create an intermediate buffer that points to the index in the buffer,
  1374. // for conforming with the other functions we've written for other data.
  1375. var materialIndices = [];
  1376. for ( var i = 0; i < materialIndexBuffer.length; ++ i ) {
  1377. materialIndices.push( i );
  1378. }
  1379. return {
  1380. dataSize: 1,
  1381. buffer: materialIndexBuffer,
  1382. indices: materialIndices,
  1383. mappingType: mappingType,
  1384. referenceType: referenceType
  1385. };
  1386. },
  1387. // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry
  1388. parseNurbsGeometry: function ( geoNode ) {
  1389. if ( NURBSCurve === undefined ) {
  1390. console.error( 'THREE.FBXLoader: The loader relies on NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.' );
  1391. return new BufferGeometry();
  1392. }
  1393. var order = parseInt( geoNode.Order );
  1394. if ( isNaN( order ) ) {
  1395. console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geoNode.Order, geoNode.id );
  1396. return new BufferGeometry();
  1397. }
  1398. var degree = order - 1;
  1399. var knots = geoNode.KnotVector.a;
  1400. var controlPoints = [];
  1401. var pointsValues = geoNode.Points.a;
  1402. for ( var i = 0, l = pointsValues.length; i < l; i += 4 ) {
  1403. controlPoints.push( new Vector4().fromArray( pointsValues, i ) );
  1404. }
  1405. var startKnot, endKnot;
  1406. if ( geoNode.Form === 'Closed' ) {
  1407. controlPoints.push( controlPoints[ 0 ] );
  1408. } else if ( geoNode.Form === 'Periodic' ) {
  1409. startKnot = degree;
  1410. endKnot = knots.length - 1 - startKnot;
  1411. for ( var i = 0; i < degree; ++ i ) {
  1412. controlPoints.push( controlPoints[ i ] );
  1413. }
  1414. }
  1415. var curve = new NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
  1416. var vertices = curve.getPoints( controlPoints.length * 7 );
  1417. var positions = new Float32Array( vertices.length * 3 );
  1418. vertices.forEach( function ( vertex, i ) {
  1419. vertex.toArray( positions, i * 3 );
  1420. } );
  1421. var geometry = new BufferGeometry();
  1422. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  1423. return geometry;
  1424. },
  1425. };
  1426. // parse animation data from FBXTree
  1427. function AnimationParser() {}
  1428. AnimationParser.prototype = {
  1429. constructor: AnimationParser,
  1430. // take raw animation clips and turn them into three.js animation clips
  1431. parse: function () {
  1432. var animationClips = [];
  1433. var rawClips = this.parseClips();
  1434. if ( rawClips !== undefined ) {
  1435. for ( var key in rawClips ) {
  1436. var rawClip = rawClips[ key ];
  1437. var clip = this.addClip( rawClip );
  1438. animationClips.push( clip );
  1439. }
  1440. }
  1441. return animationClips;
  1442. },
  1443. parseClips: function () {
  1444. // since the actual transformation data is stored in FBXTree.Objects.AnimationCurve,
  1445. // if this is undefined we can safely assume there are no animations
  1446. if ( fbxTree.Objects.AnimationCurve === undefined ) return undefined;
  1447. var curveNodesMap = this.parseAnimationCurveNodes();
  1448. this.parseAnimationCurves( curveNodesMap );
  1449. var layersMap = this.parseAnimationLayers( curveNodesMap );
  1450. var rawClips = this.parseAnimStacks( layersMap );
  1451. return rawClips;
  1452. },
  1453. // parse nodes in FBXTree.Objects.AnimationCurveNode
  1454. // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation )
  1455. // and is referenced by an AnimationLayer
  1456. parseAnimationCurveNodes: function () {
  1457. var rawCurveNodes = fbxTree.Objects.AnimationCurveNode;
  1458. var curveNodesMap = new Map();
  1459. for ( var nodeID in rawCurveNodes ) {
  1460. var rawCurveNode = rawCurveNodes[ nodeID ];
  1461. if ( rawCurveNode.attrName.match( /S|R|T|DeformPercent/ ) !== null ) {
  1462. var curveNode = {
  1463. id: rawCurveNode.id,
  1464. attr: rawCurveNode.attrName,
  1465. curves: {},
  1466. };
  1467. curveNodesMap.set( curveNode.id, curveNode );
  1468. }
  1469. }
  1470. return curveNodesMap;
  1471. },
  1472. // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to
  1473. // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated
  1474. // axis ( e.g. times and values of x rotation)
  1475. parseAnimationCurves: function ( curveNodesMap ) {
  1476. var rawCurves = fbxTree.Objects.AnimationCurve;
  1477. // TODO: Many values are identical up to roundoff error, but won't be optimised
  1478. // e.g. position times: [0, 0.4, 0. 8]
  1479. // position values: [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.235384487103147e-7, 93.67520904541016, -0.9982695579528809]
  1480. // clearly, this should be optimised to
  1481. // times: [0], positions [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809]
  1482. // this shows up in nearly every FBX file, and generally time array is length > 100
  1483. for ( var nodeID in rawCurves ) {
  1484. var animationCurve = {
  1485. id: rawCurves[ nodeID ].id,
  1486. times: rawCurves[ nodeID ].KeyTime.a.map( convertFBXTimeToSeconds ),
  1487. values: rawCurves[ nodeID ].KeyValueFloat.a,
  1488. };
  1489. var relationships = connections.get( animationCurve.id );
  1490. if ( relationships !== undefined ) {
  1491. var animationCurveID = relationships.parents[ 0 ].ID;
  1492. var animationCurveRelationship = relationships.parents[ 0 ].relationship;
  1493. if ( animationCurveRelationship.match( /X/ ) ) {
  1494. curveNodesMap.get( animationCurveID ).curves[ 'x' ] = animationCurve;
  1495. } else if ( animationCurveRelationship.match( /Y/ ) ) {
  1496. curveNodesMap.get( animationCurveID ).curves[ 'y' ] = animationCurve;
  1497. } else if ( animationCurveRelationship.match( /Z/ ) ) {
  1498. curveNodesMap.get( animationCurveID ).curves[ 'z' ] = animationCurve;
  1499. } else if ( animationCurveRelationship.match( /d|DeformPercent/ ) && curveNodesMap.has( animationCurveID ) ) {
  1500. curveNodesMap.get( animationCurveID ).curves[ 'morph' ] = animationCurve;
  1501. }
  1502. }
  1503. }
  1504. },
  1505. // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references
  1506. // to various AnimationCurveNodes and is referenced by an AnimationStack node
  1507. // note: theoretically a stack can have multiple layers, however in practice there always seems to be one per stack
  1508. parseAnimationLayers: function ( curveNodesMap ) {
  1509. var rawLayers = fbxTree.Objects.AnimationLayer;
  1510. var layersMap = new Map();
  1511. for ( var nodeID in rawLayers ) {
  1512. var layerCurveNodes = [];
  1513. var connection = connections.get( parseInt( nodeID ) );
  1514. if ( connection !== undefined ) {
  1515. // all the animationCurveNodes used in the layer
  1516. var children = connection.children;
  1517. children.forEach( function ( child, i ) {
  1518. if ( curveNodesMap.has( child.ID ) ) {
  1519. var curveNode = curveNodesMap.get( child.ID );
  1520. // check that the curves are defined for at least one axis, otherwise ignore the curveNode
  1521. if ( curveNode.curves.x !== undefined || curveNode.curves.y !== undefined || curveNode.curves.z !== undefined ) {
  1522. if ( layerCurveNodes[ i ] === undefined ) {
  1523. var modelID = connections.get( child.ID ).parents.filter( function ( parent ) {
  1524. return parent.relationship !== undefined;
  1525. } )[ 0 ].ID;
  1526. if ( modelID !== undefined ) {
  1527. var rawModel = fbxTree.Objects.Model[ modelID.toString() ];
  1528. var node = {
  1529. modelName: rawModel.attrName ? PropertyBinding.sanitizeNodeName( rawModel.attrName ) : '',
  1530. ID: rawModel.id,
  1531. initialPosition: [ 0, 0, 0 ],
  1532. initialRotation: [ 0, 0, 0 ],
  1533. initialScale: [ 1, 1, 1 ],
  1534. };
  1535. sceneGraph.traverse( function ( child ) {
  1536. if ( child.ID === rawModel.id ) {
  1537. node.transform = child.matrix;
  1538. if ( child.userData.transformData ) node.eulerOrder = child.userData.transformData.eulerOrder;
  1539. }
  1540. } );
  1541. if ( ! node.transform ) node.transform = new Matrix4();
  1542. // if the animated model is pre rotated, we'll have to apply the pre rotations to every
  1543. // animation value as well
  1544. if ( 'PreRotation' in rawModel ) node.preRotation = rawModel.PreRotation.value;
  1545. if ( 'PostRotation' in rawModel ) node.postRotation = rawModel.PostRotation.value;
  1546. layerCurveNodes[ i ] = node;
  1547. }
  1548. }
  1549. if ( layerCurveNodes[ i ] ) layerCurveNodes[ i ][ curveNode.attr ] = curveNode;
  1550. } else if ( curveNode.curves.morph !== undefined ) {
  1551. if ( layerCurveNodes[ i ] === undefined ) {
  1552. var deformerID = connections.get( child.ID ).parents.filter( function ( parent ) {
  1553. return parent.relationship !== undefined;
  1554. } )[ 0 ].ID;
  1555. var morpherID = connections.get( deformerID ).parents[ 0 ].ID;
  1556. var geoID = connections.get( morpherID ).parents[ 0 ].ID;
  1557. // assuming geometry is not used in more than one model
  1558. var modelID = connections.get( geoID ).parents[ 0 ].ID;
  1559. var rawModel = fbxTree.Objects.Model[ modelID ];
  1560. var node = {
  1561. modelName: rawModel.attrName ? PropertyBinding.sanitizeNodeName( rawModel.attrName ) : '',
  1562. morphName: fbxTree.Objects.Deformer[ deformerID ].attrName,
  1563. };
  1564. layerCurveNodes[ i ] = node;
  1565. }
  1566. layerCurveNodes[ i ][ curveNode.attr ] = curveNode;
  1567. }
  1568. }
  1569. } );
  1570. layersMap.set( parseInt( nodeID ), layerCurveNodes );
  1571. }
  1572. }
  1573. return layersMap;
  1574. },
  1575. // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation
  1576. // hierarchy. Each Stack node will be used to create a AnimationClip
  1577. parseAnimStacks: function ( layersMap ) {
  1578. var rawStacks = fbxTree.Objects.AnimationStack;
  1579. // connect the stacks (clips) up to the layers
  1580. var rawClips = {};
  1581. for ( var nodeID in rawStacks ) {
  1582. var children = connections.get( parseInt( nodeID ) ).children;
  1583. if ( children.length > 1 ) {
  1584. // it seems like stacks will always be associated with a single layer. But just in case there are files
  1585. // where there are multiple layers per stack, we'll display a warning
  1586. console.warn( 'THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.' );
  1587. }
  1588. var layer = layersMap.get( children[ 0 ].ID );
  1589. rawClips[ nodeID ] = {
  1590. name: rawStacks[ nodeID ].attrName,
  1591. layer: layer,
  1592. };
  1593. }
  1594. return rawClips;
  1595. },
  1596. addClip: function ( rawClip ) {
  1597. var tracks = [];
  1598. var self = this;
  1599. rawClip.layer.forEach( function ( rawTracks ) {
  1600. tracks = tracks.concat( self.generateTracks( rawTracks ) );
  1601. } );
  1602. return new AnimationClip( rawClip.name, - 1, tracks );
  1603. },
  1604. generateTracks: function ( rawTracks ) {
  1605. var tracks = [];
  1606. var initialPosition = new Vector3();
  1607. var initialRotation = new Quaternion();
  1608. var initialScale = new Vector3();
  1609. if ( rawTracks.transform ) rawTracks.transform.decompose( initialPosition, initialRotation, initialScale );
  1610. initialPosition = initialPosition.toArray();
  1611. initialRotation = new Euler().setFromQuaternion( initialRotation, rawTracks.eulerOrder ).toArray();
  1612. initialScale = initialScale.toArray();
  1613. if ( rawTracks.T !== undefined && Object.keys( rawTracks.T.curves ).length > 0 ) {
  1614. var positionTrack = this.generateVectorTrack( rawTracks.modelName, rawTracks.T.curves, initialPosition, 'position' );
  1615. if ( positionTrack !== undefined ) tracks.push( positionTrack );
  1616. }
  1617. if ( rawTracks.R !== undefined && Object.keys( rawTracks.R.curves ).length > 0 ) {
  1618. var rotationTrack = this.generateRotationTrack( rawTracks.modelName, rawTracks.R.curves, initialRotation, rawTracks.preRotation, rawTracks.postRotation, rawTracks.eulerOrder );
  1619. if ( rotationTrack !== undefined ) tracks.push( rotationTrack );
  1620. }
  1621. if ( rawTracks.S !== undefined && Object.keys( rawTracks.S.curves ).length > 0 ) {
  1622. var scaleTrack = this.generateVectorTrack( rawTracks.modelName, rawTracks.S.curves, initialScale, 'scale' );
  1623. if ( scaleTrack !== undefined ) tracks.push( scaleTrack );
  1624. }
  1625. if ( rawTracks.DeformPercent !== undefined ) {
  1626. var morphTrack = this.generateMorphTrack( rawTracks );
  1627. if ( morphTrack !== undefined ) tracks.push( morphTrack );
  1628. }
  1629. return tracks;
  1630. },
  1631. generateVectorTrack: function ( modelName, curves, initialValue, type ) {
  1632. var times = this.getTimesForAllAxes( curves );
  1633. var values = this.getKeyframeTrackValues( times, curves, initialValue );
  1634. return new VectorKeyframeTrack( modelName + '.' + type, times, values );
  1635. },
  1636. generateRotationTrack: function ( modelName, curves, initialValue, preRotation, postRotation, eulerOrder ) {
  1637. if ( curves.x !== undefined ) {
  1638. this.interpolateRotations( curves.x );
  1639. curves.x.values = curves.x.values.map( MathUtils.degToRad );
  1640. }
  1641. if ( curves.y !== undefined ) {
  1642. this.interpolateRotations( curves.y );
  1643. curves.y.values = curves.y.values.map( MathUtils.degToRad );
  1644. }
  1645. if ( curves.z !== undefined ) {
  1646. this.interpolateRotations( curves.z );
  1647. curves.z.values = curves.z.values.map( MathUtils.degToRad );
  1648. }
  1649. var times = this.getTimesForAllAxes( curves );
  1650. var values = this.getKeyframeTrackValues( times, curves, initialValue );
  1651. if ( preRotation !== undefined ) {
  1652. preRotation = preRotation.map( MathUtils.degToRad );
  1653. preRotation.push( eulerOrder );
  1654. preRotation = new Euler().fromArray( preRotation );
  1655. preRotation = new Quaternion().setFromEuler( preRotation );
  1656. }
  1657. if ( postRotation !== undefined ) {
  1658. postRotation = postRotation.map( MathUtils.degToRad );
  1659. postRotation.push( eulerOrder );
  1660. postRotation = new Euler().fromArray( postRotation );
  1661. postRotation = new Quaternion().setFromEuler( postRotation ).inverse();
  1662. }
  1663. var quaternion = new Quaternion();
  1664. var euler = new Euler();
  1665. var quaternionValues = [];
  1666. for ( var i = 0; i < values.length; i += 3 ) {
  1667. euler.set( values[ i ], values[ i + 1 ], values[ i + 2 ], eulerOrder );
  1668. quaternion.setFromEuler( euler );
  1669. if ( preRotation !== undefined ) quaternion.premultiply( preRotation );
  1670. if ( postRotation !== undefined ) quaternion.multiply( postRotation );
  1671. quaternion.toArray( quaternionValues, ( i / 3 ) * 4 );
  1672. }
  1673. return new QuaternionKeyframeTrack( modelName + '.quaternion', times, quaternionValues );
  1674. },
  1675. generateMorphTrack: function ( rawTracks ) {
  1676. var curves = rawTracks.DeformPercent.curves.morph;
  1677. var values = curves.values.map( function ( val ) {
  1678. return val / 100;
  1679. } );
  1680. var morphNum = sceneGraph.getObjectByName( rawTracks.modelName ).morphTargetDictionary[ rawTracks.morphName ];
  1681. return new NumberKeyframeTrack( rawTracks.modelName + '.morphTargetInfluences[' + morphNum + ']', curves.times, values );
  1682. },
  1683. // For all animated objects, times are defined separately for each axis
  1684. // Here we'll combine the times into one sorted array without duplicates
  1685. getTimesForAllAxes: function ( curves ) {
  1686. var times = [];
  1687. // first join together the times for each axis, if defined
  1688. if ( curves.x !== undefined ) times = times.concat( curves.x.times );
  1689. if ( curves.y !== undefined ) times = times.concat( curves.y.times );
  1690. if ( curves.z !== undefined ) times = times.concat( curves.z.times );
  1691. // then sort them and remove duplicates
  1692. times = times.sort( function ( a, b ) {
  1693. return a - b;
  1694. } ).filter( function ( elem, index, array ) {
  1695. return array.indexOf( elem ) == index;
  1696. } );
  1697. return times;
  1698. },
  1699. getKeyframeTrackValues: function ( times, curves, initialValue ) {
  1700. var prevValue = initialValue;
  1701. var values = [];
  1702. var xIndex = - 1;
  1703. var yIndex = - 1;
  1704. var zIndex = - 1;
  1705. times.forEach( function ( time ) {
  1706. if ( curves.x ) xIndex = curves.x.times.indexOf( time );
  1707. if ( curves.y ) yIndex = curves.y.times.indexOf( time );
  1708. if ( curves.z ) zIndex = curves.z.times.indexOf( time );
  1709. // if there is an x value defined for this frame, use that
  1710. if ( xIndex !== - 1 ) {
  1711. var xValue = curves.x.values[ xIndex ];
  1712. values.push( xValue );
  1713. prevValue[ 0 ] = xValue;
  1714. } else {
  1715. // otherwise use the x value from the previous frame
  1716. values.push( prevValue[ 0 ] );
  1717. }
  1718. if ( yIndex !== - 1 ) {
  1719. var yValue = curves.y.values[ yIndex ];
  1720. values.push( yValue );
  1721. prevValue[ 1 ] = yValue;
  1722. } else {
  1723. values.push( prevValue[ 1 ] );
  1724. }
  1725. if ( zIndex !== - 1 ) {
  1726. var zValue = curves.z.values[ zIndex ];
  1727. values.push( zValue );
  1728. prevValue[ 2 ] = zValue;
  1729. } else {
  1730. values.push( prevValue[ 2 ] );
  1731. }
  1732. } );
  1733. return values;
  1734. },
  1735. // Rotations are defined as Euler angles which can have values of any size
  1736. // These will be converted to quaternions which don't support values greater than
  1737. // PI, so we'll interpolate large rotations
  1738. interpolateRotations: function ( curve ) {
  1739. for ( var i = 1; i < curve.values.length; i ++ ) {
  1740. var initialValue = curve.values[ i - 1 ];
  1741. var valuesSpan = curve.values[ i ] - initialValue;
  1742. var absoluteSpan = Math.abs( valuesSpan );
  1743. if ( absoluteSpan >= 180 ) {
  1744. var numSubIntervals = absoluteSpan / 180;
  1745. var step = valuesSpan / numSubIntervals;
  1746. var nextValue = initialValue + step;
  1747. var initialTime = curve.times[ i - 1 ];
  1748. var timeSpan = curve.times[ i ] - initialTime;
  1749. var interval = timeSpan / numSubIntervals;
  1750. var nextTime = initialTime + interval;
  1751. var interpolatedTimes = [];
  1752. var interpolatedValues = [];
  1753. while ( nextTime < curve.times[ i ] ) {
  1754. interpolatedTimes.push( nextTime );
  1755. nextTime += interval;
  1756. interpolatedValues.push( nextValue );
  1757. nextValue += step;
  1758. }
  1759. curve.times = inject( curve.times, i, interpolatedTimes );
  1760. curve.values = inject( curve.values, i, interpolatedValues );
  1761. }
  1762. }
  1763. },
  1764. };
  1765. // parse an FBX file in ASCII format
  1766. function TextParser() {}
  1767. TextParser.prototype = {
  1768. constructor: TextParser,
  1769. getPrevNode: function () {
  1770. return this.nodeStack[ this.currentIndent - 2 ];
  1771. },
  1772. getCurrentNode: function () {
  1773. return this.nodeStack[ this.currentIndent - 1 ];
  1774. },
  1775. getCurrentProp: function () {
  1776. return this.currentProp;
  1777. },
  1778. pushStack: function ( node ) {
  1779. this.nodeStack.push( node );
  1780. this.currentIndent += 1;
  1781. },
  1782. popStack: function () {
  1783. this.nodeStack.pop();
  1784. this.currentIndent -= 1;
  1785. },
  1786. setCurrentProp: function ( val, name ) {
  1787. this.currentProp = val;
  1788. this.currentPropName = name;
  1789. },
  1790. parse: function ( text ) {
  1791. this.currentIndent = 0;
  1792. this.allNodes = new FBXTree();
  1793. this.nodeStack = [];
  1794. this.currentProp = [];
  1795. this.currentPropName = '';
  1796. var self = this;
  1797. var split = text.split( /[\r\n]+/ );
  1798. split.forEach( function ( line, i ) {
  1799. var matchComment = line.match( /^[\s\t]*;/ );
  1800. var matchEmpty = line.match( /^[\s\t]*$/ );
  1801. if ( matchComment || matchEmpty ) return;
  1802. var matchBeginning = line.match( '^\\t{' + self.currentIndent + '}(\\w+):(.*){', '' );
  1803. var matchProperty = line.match( '^\\t{' + ( self.currentIndent ) + '}(\\w+):[\\s\\t\\r\\n](.*)' );
  1804. var matchEnd = line.match( '^\\t{' + ( self.currentIndent - 1 ) + '}}' );
  1805. if ( matchBeginning ) {
  1806. self.parseNodeBegin( line, matchBeginning );
  1807. } else if ( matchProperty ) {
  1808. self.parseNodeProperty( line, matchProperty, split[ ++ i ] );
  1809. } else if ( matchEnd ) {
  1810. self.popStack();
  1811. } else if ( line.match( /^[^\s\t}]/ ) ) {
  1812. // large arrays are split over multiple lines terminated with a ',' character
  1813. // if this is encountered the line needs to be joined to the previous line
  1814. self.parseNodePropertyContinued( line );
  1815. }
  1816. } );
  1817. return this.allNodes;
  1818. },
  1819. parseNodeBegin: function ( line, property ) {
  1820. var nodeName = property[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  1821. var nodeAttrs = property[ 2 ].split( ',' ).map( function ( attr ) {
  1822. return attr.trim().replace( /^"/, '' ).replace( /"$/, '' );
  1823. } );
  1824. var node = { name: nodeName };
  1825. var attrs = this.parseNodeAttr( nodeAttrs );
  1826. var currentNode = this.getCurrentNode();
  1827. // a top node
  1828. if ( this.currentIndent === 0 ) {
  1829. this.allNodes.add( nodeName, node );
  1830. } else { // a subnode
  1831. // if the subnode already exists, append it
  1832. if ( nodeName in currentNode ) {
  1833. // special case Pose needs PoseNodes as an array
  1834. if ( nodeName === 'PoseNode' ) {
  1835. currentNode.PoseNode.push( node );
  1836. } else if ( currentNode[ nodeName ].id !== undefined ) {
  1837. currentNode[ nodeName ] = {};
  1838. currentNode[ nodeName ][ currentNode[ nodeName ].id ] = currentNode[ nodeName ];
  1839. }
  1840. if ( attrs.id !== '' ) currentNode[ nodeName ][ attrs.id ] = node;
  1841. } else if ( typeof attrs.id === 'number' ) {
  1842. currentNode[ nodeName ] = {};
  1843. currentNode[ nodeName ][ attrs.id ] = node;
  1844. } else if ( nodeName !== 'Properties70' ) {
  1845. if ( nodeName === 'PoseNode' ) currentNode[ nodeName ] = [ node ];
  1846. else currentNode[ nodeName ] = node;
  1847. }
  1848. }
  1849. if ( typeof attrs.id === 'number' ) node.id = attrs.id;
  1850. if ( attrs.name !== '' ) node.attrName = attrs.name;
  1851. if ( attrs.type !== '' ) node.attrType = attrs.type;
  1852. this.pushStack( node );
  1853. },
  1854. parseNodeAttr: function ( attrs ) {
  1855. var id = attrs[ 0 ];
  1856. if ( attrs[ 0 ] !== '' ) {
  1857. id = parseInt( attrs[ 0 ] );
  1858. if ( isNaN( id ) ) {
  1859. id = attrs[ 0 ];
  1860. }
  1861. }
  1862. var name = '', type = '';
  1863. if ( attrs.length > 1 ) {
  1864. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  1865. type = attrs[ 2 ];
  1866. }
  1867. return { id: id, name: name, type: type };
  1868. },
  1869. parseNodeProperty: function ( line, property, contentLine ) {
  1870. var propName = property[ 1 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  1871. var propValue = property[ 2 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  1872. // for special case: base64 image data follows "Content: ," line
  1873. // Content: ,
  1874. // "/9j/4RDaRXhpZgAATU0A..."
  1875. if ( propName === 'Content' && propValue === ',' ) {
  1876. propValue = contentLine.replace( /"/g, '' ).replace( /,$/, '' ).trim();
  1877. }
  1878. var currentNode = this.getCurrentNode();
  1879. var parentName = currentNode.name;
  1880. if ( parentName === 'Properties70' ) {
  1881. this.parseNodeSpecialProperty( line, propName, propValue );
  1882. return;
  1883. }
  1884. // Connections
  1885. if ( propName === 'C' ) {
  1886. var connProps = propValue.split( ',' ).slice( 1 );
  1887. var from = parseInt( connProps[ 0 ] );
  1888. var to = parseInt( connProps[ 1 ] );
  1889. var rest = propValue.split( ',' ).slice( 3 );
  1890. rest = rest.map( function ( elem ) {
  1891. return elem.trim().replace( /^"/, '' );
  1892. } );
  1893. propName = 'connections';
  1894. propValue = [ from, to ];
  1895. append( propValue, rest );
  1896. if ( currentNode[ propName ] === undefined ) {
  1897. currentNode[ propName ] = [];
  1898. }
  1899. }
  1900. // Node
  1901. if ( propName === 'Node' ) currentNode.id = propValue;
  1902. // connections
  1903. if ( propName in currentNode && Array.isArray( currentNode[ propName ] ) ) {
  1904. currentNode[ propName ].push( propValue );
  1905. } else {
  1906. if ( propName !== 'a' ) currentNode[ propName ] = propValue;
  1907. else currentNode.a = propValue;
  1908. }
  1909. this.setCurrentProp( currentNode, propName );
  1910. // convert string to array, unless it ends in ',' in which case more will be added to it
  1911. if ( propName === 'a' && propValue.slice( - 1 ) !== ',' ) {
  1912. currentNode.a = parseNumberArray( propValue );
  1913. }
  1914. },
  1915. parseNodePropertyContinued: function ( line ) {
  1916. var currentNode = this.getCurrentNode();
  1917. currentNode.a += line;
  1918. // if the line doesn't end in ',' we have reached the end of the property value
  1919. // so convert the string to an array
  1920. if ( line.slice( - 1 ) !== ',' ) {
  1921. currentNode.a = parseNumberArray( currentNode.a );
  1922. }
  1923. },
  1924. // parse "Property70"
  1925. parseNodeSpecialProperty: function ( line, propName, propValue ) {
  1926. // split this
  1927. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  1928. // into array like below
  1929. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  1930. var props = propValue.split( '",' ).map( function ( prop ) {
  1931. return prop.trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  1932. } );
  1933. var innerPropName = props[ 0 ];
  1934. var innerPropType1 = props[ 1 ];
  1935. var innerPropType2 = props[ 2 ];
  1936. var innerPropFlag = props[ 3 ];
  1937. var innerPropValue = props[ 4 ];
  1938. // cast values where needed, otherwise leave as strings
  1939. switch ( innerPropType1 ) {
  1940. case 'int':
  1941. case 'enum':
  1942. case 'bool':
  1943. case 'ULongLong':
  1944. case 'double':
  1945. case 'Number':
  1946. case 'FieldOfView':
  1947. innerPropValue = parseFloat( innerPropValue );
  1948. break;
  1949. case 'Color':
  1950. case 'ColorRGB':
  1951. case 'Vector3D':
  1952. case 'Lcl_Translation':
  1953. case 'Lcl_Rotation':
  1954. case 'Lcl_Scaling':
  1955. innerPropValue = parseNumberArray( innerPropValue );
  1956. break;
  1957. }
  1958. // CAUTION: these props must append to parent's parent
  1959. this.getPrevNode()[ innerPropName ] = {
  1960. 'type': innerPropType1,
  1961. 'type2': innerPropType2,
  1962. 'flag': innerPropFlag,
  1963. 'value': innerPropValue
  1964. };
  1965. this.setCurrentProp( this.getPrevNode(), innerPropName );
  1966. },
  1967. };
  1968. // Parse an FBX file in Binary format
  1969. function BinaryParser() {}
  1970. BinaryParser.prototype = {
  1971. constructor: BinaryParser,
  1972. parse: function ( buffer ) {
  1973. var reader = new BinaryReader( buffer );
  1974. reader.skip( 23 ); // skip magic 23 bytes
  1975. var version = reader.getUint32();
  1976. console.log( 'THREE.FBXLoader: FBX binary version: ' + version );
  1977. var allNodes = new FBXTree();
  1978. while ( ! this.endOfContent( reader ) ) {
  1979. var node = this.parseNode( reader, version );
  1980. if ( node !== null ) allNodes.add( node.name, node );
  1981. }
  1982. return allNodes;
  1983. },
  1984. // Check if reader has reached the end of content.
  1985. endOfContent: function ( reader ) {
  1986. // footer size: 160bytes + 16-byte alignment padding
  1987. // - 16bytes: magic
  1988. // - padding til 16-byte alignment (at least 1byte?)
  1989. // (seems like some exporters embed fixed 15 or 16bytes?)
  1990. // - 4bytes: magic
  1991. // - 4bytes: version
  1992. // - 120bytes: zero
  1993. // - 16bytes: magic
  1994. if ( reader.size() % 16 === 0 ) {
  1995. return ( ( reader.getOffset() + 160 + 16 ) & ~ 0xf ) >= reader.size();
  1996. } else {
  1997. return reader.getOffset() + 160 + 16 >= reader.size();
  1998. }
  1999. },
  2000. // recursively parse nodes until the end of the file is reached
  2001. parseNode: function ( reader, version ) {
  2002. var node = {};
  2003. // The first three data sizes depends on version.
  2004. var endOffset = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  2005. var numProperties = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  2006. // note: do not remove this even if you get a linter warning as it moves the buffer forward
  2007. var propertyListLen = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  2008. var nameLen = reader.getUint8();
  2009. var name = reader.getString( nameLen );
  2010. // Regards this node as NULL-record if endOffset is zero
  2011. if ( endOffset === 0 ) return null;
  2012. var propertyList = [];
  2013. for ( var i = 0; i < numProperties; i ++ ) {
  2014. propertyList.push( this.parseProperty( reader ) );
  2015. }
  2016. // Regards the first three elements in propertyList as id, attrName, and attrType
  2017. var id = propertyList.length > 0 ? propertyList[ 0 ] : '';
  2018. var attrName = propertyList.length > 1 ? propertyList[ 1 ] : '';
  2019. var attrType = propertyList.length > 2 ? propertyList[ 2 ] : '';
  2020. // check if this node represents just a single property
  2021. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  2022. node.singleProperty = ( numProperties === 1 && reader.getOffset() === endOffset ) ? true : false;
  2023. while ( endOffset > reader.getOffset() ) {
  2024. var subNode = this.parseNode( reader, version );
  2025. if ( subNode !== null ) this.parseSubNode( name, node, subNode );
  2026. }
  2027. node.propertyList = propertyList; // raw property list used by parent
  2028. if ( typeof id === 'number' ) node.id = id;
  2029. if ( attrName !== '' ) node.attrName = attrName;
  2030. if ( attrType !== '' ) node.attrType = attrType;
  2031. if ( name !== '' ) node.name = name;
  2032. return node;
  2033. },
  2034. parseSubNode: function ( name, node, subNode ) {
  2035. // special case: child node is single property
  2036. if ( subNode.singleProperty === true ) {
  2037. var value = subNode.propertyList[ 0 ];
  2038. if ( Array.isArray( value ) ) {
  2039. node[ subNode.name ] = subNode;
  2040. subNode.a = value;
  2041. } else {
  2042. node[ subNode.name ] = value;
  2043. }
  2044. } else if ( name === 'Connections' && subNode.name === 'C' ) {
  2045. var array = [];
  2046. subNode.propertyList.forEach( function ( property, i ) {
  2047. // first Connection is FBX type (OO, OP, etc.). We'll discard these
  2048. if ( i !== 0 ) array.push( property );
  2049. } );
  2050. if ( node.connections === undefined ) {
  2051. node.connections = [];
  2052. }
  2053. node.connections.push( array );
  2054. } else if ( subNode.name === 'Properties70' ) {
  2055. var keys = Object.keys( subNode );
  2056. keys.forEach( function ( key ) {
  2057. node[ key ] = subNode[ key ];
  2058. } );
  2059. } else if ( name === 'Properties70' && subNode.name === 'P' ) {
  2060. var innerPropName = subNode.propertyList[ 0 ];
  2061. var innerPropType1 = subNode.propertyList[ 1 ];
  2062. var innerPropType2 = subNode.propertyList[ 2 ];
  2063. var innerPropFlag = subNode.propertyList[ 3 ];
  2064. var innerPropValue;
  2065. if ( innerPropName.indexOf( 'Lcl ' ) === 0 ) innerPropName = innerPropName.replace( 'Lcl ', 'Lcl_' );
  2066. if ( innerPropType1.indexOf( 'Lcl ' ) === 0 ) innerPropType1 = innerPropType1.replace( 'Lcl ', 'Lcl_' );
  2067. if ( innerPropType1 === 'Color' || innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' || innerPropType1 === 'Vector3D' || innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  2068. innerPropValue = [
  2069. subNode.propertyList[ 4 ],
  2070. subNode.propertyList[ 5 ],
  2071. subNode.propertyList[ 6 ]
  2072. ];
  2073. } else {
  2074. innerPropValue = subNode.propertyList[ 4 ];
  2075. }
  2076. // this will be copied to parent, see above
  2077. node[ innerPropName ] = {
  2078. 'type': innerPropType1,
  2079. 'type2': innerPropType2,
  2080. 'flag': innerPropFlag,
  2081. 'value': innerPropValue
  2082. };
  2083. } else if ( node[ subNode.name ] === undefined ) {
  2084. if ( typeof subNode.id === 'number' ) {
  2085. node[ subNode.name ] = {};
  2086. node[ subNode.name ][ subNode.id ] = subNode;
  2087. } else {
  2088. node[ subNode.name ] = subNode;
  2089. }
  2090. } else {
  2091. if ( subNode.name === 'PoseNode' ) {
  2092. if ( ! Array.isArray( node[ subNode.name ] ) ) {
  2093. node[ subNode.name ] = [ node[ subNode.name ] ];
  2094. }
  2095. node[ subNode.name ].push( subNode );
  2096. } else if ( node[ subNode.name ][ subNode.id ] === undefined ) {
  2097. node[ subNode.name ][ subNode.id ] = subNode;
  2098. }
  2099. }
  2100. },
  2101. parseProperty: function ( reader ) {
  2102. var type = reader.getString( 1 );
  2103. switch ( type ) {
  2104. case 'C':
  2105. return reader.getBoolean();
  2106. case 'D':
  2107. return reader.getFloat64();
  2108. case 'F':
  2109. return reader.getFloat32();
  2110. case 'I':
  2111. return reader.getInt32();
  2112. case 'L':
  2113. return reader.getInt64();
  2114. case 'R':
  2115. var length = reader.getUint32();
  2116. return reader.getArrayBuffer( length );
  2117. case 'S':
  2118. var length = reader.getUint32();
  2119. return reader.getString( length );
  2120. case 'Y':
  2121. return reader.getInt16();
  2122. case 'b':
  2123. case 'c':
  2124. case 'd':
  2125. case 'f':
  2126. case 'i':
  2127. case 'l':
  2128. var arrayLength = reader.getUint32();
  2129. var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  2130. var compressedLength = reader.getUint32();
  2131. if ( encoding === 0 ) {
  2132. switch ( type ) {
  2133. case 'b':
  2134. case 'c':
  2135. return reader.getBooleanArray( arrayLength );
  2136. case 'd':
  2137. return reader.getFloat64Array( arrayLength );
  2138. case 'f':
  2139. return reader.getFloat32Array( arrayLength );
  2140. case 'i':
  2141. return reader.getInt32Array( arrayLength );
  2142. case 'l':
  2143. return reader.getInt64Array( arrayLength );
  2144. }
  2145. }
  2146. if ( typeof Zlib === 'undefined' ) {
  2147. console.error( 'THREE.FBXLoader: External library Inflate.min.js required, obtain or import from https://github.com/imaya/zlib.js' );
  2148. }
  2149. var inflate = new Zlib.Inflate( new Uint8Array( reader.getArrayBuffer( compressedLength ) ) ); // eslint-disable-line no-undef
  2150. var reader2 = new BinaryReader( inflate.decompress().buffer );
  2151. switch ( type ) {
  2152. case 'b':
  2153. case 'c':
  2154. return reader2.getBooleanArray( arrayLength );
  2155. case 'd':
  2156. return reader2.getFloat64Array( arrayLength );
  2157. case 'f':
  2158. return reader2.getFloat32Array( arrayLength );
  2159. case 'i':
  2160. return reader2.getInt32Array( arrayLength );
  2161. case 'l':
  2162. return reader2.getInt64Array( arrayLength );
  2163. }
  2164. default:
  2165. throw new Error( 'THREE.FBXLoader: Unknown property type ' + type );
  2166. }
  2167. }
  2168. };
  2169. function BinaryReader( buffer, littleEndian ) {
  2170. this.dv = new DataView( buffer );
  2171. this.offset = 0;
  2172. this.littleEndian = ( littleEndian !== undefined ) ? littleEndian : true;
  2173. }
  2174. BinaryReader.prototype = {
  2175. constructor: BinaryReader,
  2176. getOffset: function () {
  2177. return this.offset;
  2178. },
  2179. size: function () {
  2180. return this.dv.buffer.byteLength;
  2181. },
  2182. skip: function ( length ) {
  2183. this.offset += length;
  2184. },
  2185. // seems like true/false representation depends on exporter.
  2186. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  2187. // then sees LSB.
  2188. getBoolean: function () {
  2189. return ( this.getUint8() & 1 ) === 1;
  2190. },
  2191. getBooleanArray: function ( size ) {
  2192. var a = [];
  2193. for ( var i = 0; i < size; i ++ ) {
  2194. a.push( this.getBoolean() );
  2195. }
  2196. return a;
  2197. },
  2198. getUint8: function () {
  2199. var value = this.dv.getUint8( this.offset );
  2200. this.offset += 1;
  2201. return value;
  2202. },
  2203. getInt16: function () {
  2204. var value = this.dv.getInt16( this.offset, this.littleEndian );
  2205. this.offset += 2;
  2206. return value;
  2207. },
  2208. getInt32: function () {
  2209. var value = this.dv.getInt32( this.offset, this.littleEndian );
  2210. this.offset += 4;
  2211. return value;
  2212. },
  2213. getInt32Array: function ( size ) {
  2214. var a = [];
  2215. for ( var i = 0; i < size; i ++ ) {
  2216. a.push( this.getInt32() );
  2217. }
  2218. return a;
  2219. },
  2220. getUint32: function () {
  2221. var value = this.dv.getUint32( this.offset, this.littleEndian );
  2222. this.offset += 4;
  2223. return value;
  2224. },
  2225. // JavaScript doesn't support 64-bit integer so calculate this here
  2226. // 1 << 32 will return 1 so using multiply operation instead here.
  2227. // There's a possibility that this method returns wrong value if the value
  2228. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  2229. // TODO: safely handle 64-bit integer
  2230. getInt64: function () {
  2231. var low, high;
  2232. if ( this.littleEndian ) {
  2233. low = this.getUint32();
  2234. high = this.getUint32();
  2235. } else {
  2236. high = this.getUint32();
  2237. low = this.getUint32();
  2238. }
  2239. // calculate negative value
  2240. if ( high & 0x80000000 ) {
  2241. high = ~ high & 0xFFFFFFFF;
  2242. low = ~ low & 0xFFFFFFFF;
  2243. if ( low === 0xFFFFFFFF ) high = ( high + 1 ) & 0xFFFFFFFF;
  2244. low = ( low + 1 ) & 0xFFFFFFFF;
  2245. return - ( high * 0x100000000 + low );
  2246. }
  2247. return high * 0x100000000 + low;
  2248. },
  2249. getInt64Array: function ( size ) {
  2250. var a = [];
  2251. for ( var i = 0; i < size; i ++ ) {
  2252. a.push( this.getInt64() );
  2253. }
  2254. return a;
  2255. },
  2256. // Note: see getInt64() comment
  2257. getUint64: function () {
  2258. var low, high;
  2259. if ( this.littleEndian ) {
  2260. low = this.getUint32();
  2261. high = this.getUint32();
  2262. } else {
  2263. high = this.getUint32();
  2264. low = this.getUint32();
  2265. }
  2266. return high * 0x100000000 + low;
  2267. },
  2268. getFloat32: function () {
  2269. var value = this.dv.getFloat32( this.offset, this.littleEndian );
  2270. this.offset += 4;
  2271. return value;
  2272. },
  2273. getFloat32Array: function ( size ) {
  2274. var a = [];
  2275. for ( var i = 0; i < size; i ++ ) {
  2276. a.push( this.getFloat32() );
  2277. }
  2278. return a;
  2279. },
  2280. getFloat64: function () {
  2281. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  2282. this.offset += 8;
  2283. return value;
  2284. },
  2285. getFloat64Array: function ( size ) {
  2286. var a = [];
  2287. for ( var i = 0; i < size; i ++ ) {
  2288. a.push( this.getFloat64() );
  2289. }
  2290. return a;
  2291. },
  2292. getArrayBuffer: function ( size ) {
  2293. var value = this.dv.buffer.slice( this.offset, this.offset + size );
  2294. this.offset += size;
  2295. return value;
  2296. },
  2297. getString: function ( size ) {
  2298. // note: safari 9 doesn't support Uint8Array.indexOf; create intermediate array instead
  2299. var a = [];
  2300. for ( var i = 0; i < size; i ++ ) {
  2301. a[ i ] = this.getUint8();
  2302. }
  2303. var nullByte = a.indexOf( 0 );
  2304. if ( nullByte >= 0 ) a = a.slice( 0, nullByte );
  2305. return LoaderUtils.decodeText( new Uint8Array( a ) );
  2306. }
  2307. };
  2308. // FBXTree holds a representation of the FBX data, returned by the TextParser ( FBX ASCII format)
  2309. // and BinaryParser( FBX Binary format)
  2310. function FBXTree() {}
  2311. FBXTree.prototype = {
  2312. constructor: FBXTree,
  2313. add: function ( key, val ) {
  2314. this[ key ] = val;
  2315. },
  2316. };
  2317. // ************** UTILITY FUNCTIONS **************
  2318. function isFbxFormatBinary( buffer ) {
  2319. var CORRECT = 'Kaydara FBX Binary \0';
  2320. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString( buffer, 0, CORRECT.length );
  2321. }
  2322. function isFbxFormatASCII( text ) {
  2323. var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  2324. var cursor = 0;
  2325. function read( offset ) {
  2326. var result = text[ offset - 1 ];
  2327. text = text.slice( cursor + offset );
  2328. cursor ++;
  2329. return result;
  2330. }
  2331. for ( var i = 0; i < CORRECT.length; ++ i ) {
  2332. var num = read( 1 );
  2333. if ( num === CORRECT[ i ] ) {
  2334. return false;
  2335. }
  2336. }
  2337. return true;
  2338. }
  2339. function getFbxVersion( text ) {
  2340. var versionRegExp = /FBXVersion: (\d+)/;
  2341. var match = text.match( versionRegExp );
  2342. if ( match ) {
  2343. var version = parseInt( match[ 1 ] );
  2344. return version;
  2345. }
  2346. throw new Error( 'THREE.FBXLoader: Cannot find the version number for the file given.' );
  2347. }
  2348. // Converts FBX ticks into real time seconds.
  2349. function convertFBXTimeToSeconds( time ) {
  2350. return time / 46186158000;
  2351. }
  2352. var dataArray = [];
  2353. // extracts the data from the correct position in the FBX array based on indexing type
  2354. function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  2355. var index;
  2356. switch ( infoObject.mappingType ) {
  2357. case 'ByPolygonVertex' :
  2358. index = polygonVertexIndex;
  2359. break;
  2360. case 'ByPolygon' :
  2361. index = polygonIndex;
  2362. break;
  2363. case 'ByVertice' :
  2364. index = vertexIndex;
  2365. break;
  2366. case 'AllSame' :
  2367. index = infoObject.indices[ 0 ];
  2368. break;
  2369. default :
  2370. console.warn( 'THREE.FBXLoader: unknown attribute mapping type ' + infoObject.mappingType );
  2371. }
  2372. if ( infoObject.referenceType === 'IndexToDirect' ) index = infoObject.indices[ index ];
  2373. var from = index * infoObject.dataSize;
  2374. var to = from + infoObject.dataSize;
  2375. return slice( dataArray, infoObject.buffer, from, to );
  2376. }
  2377. var tempEuler = new Euler();
  2378. var tempVec = new Vector3();
  2379. // generate transformation from FBX transform data
  2380. // ref: https://help.autodesk.com/view/FBX/2017/ENU/?guid=__files_GUID_10CDD63C_79C1_4F2D_BB28_AD2BE65A02ED_htm
  2381. // 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
  2382. function generateTransform( transformData ) {
  2383. var lTranslationM = new Matrix4();
  2384. var lPreRotationM = new Matrix4();
  2385. var lRotationM = new Matrix4();
  2386. var lPostRotationM = new Matrix4();
  2387. var lScalingM = new Matrix4();
  2388. var lScalingPivotM = new Matrix4();
  2389. var lScalingOffsetM = new Matrix4();
  2390. var lRotationOffsetM = new Matrix4();
  2391. var lRotationPivotM = new Matrix4();
  2392. var lParentGX = new Matrix4();
  2393. var lGlobalT = new Matrix4();
  2394. var inheritType = ( transformData.inheritType ) ? transformData.inheritType : 0;
  2395. if ( transformData.translation ) lTranslationM.setPosition( tempVec.fromArray( transformData.translation ) );
  2396. if ( transformData.preRotation ) {
  2397. var array = transformData.preRotation.map( MathUtils.degToRad );
  2398. array.push( transformData.eulerOrder );
  2399. lPreRotationM.makeRotationFromEuler( tempEuler.fromArray( array ) );
  2400. }
  2401. if ( transformData.rotation ) {
  2402. var array = transformData.rotation.map( MathUtils.degToRad );
  2403. array.push( transformData.eulerOrder );
  2404. lRotationM.makeRotationFromEuler( tempEuler.fromArray( array ) );
  2405. }
  2406. if ( transformData.postRotation ) {
  2407. var array = transformData.postRotation.map( MathUtils.degToRad );
  2408. array.push( transformData.eulerOrder );
  2409. lPostRotationM.makeRotationFromEuler( tempEuler.fromArray( array ) );
  2410. }
  2411. if ( transformData.scale ) lScalingM.scale( tempVec.fromArray( transformData.scale ) );
  2412. // Pivots and offsets
  2413. if ( transformData.scalingOffset ) lScalingOffsetM.setPosition( tempVec.fromArray( transformData.scalingOffset ) );
  2414. if ( transformData.scalingPivot ) lScalingPivotM.setPosition( tempVec.fromArray( transformData.scalingPivot ) );
  2415. if ( transformData.rotationOffset ) lRotationOffsetM.setPosition( tempVec.fromArray( transformData.rotationOffset ) );
  2416. if ( transformData.rotationPivot ) lRotationPivotM.setPosition( tempVec.fromArray( transformData.rotationPivot ) );
  2417. // parent transform
  2418. if ( transformData.parentMatrixWorld ) lParentGX = transformData.parentMatrixWorld;
  2419. // Global Rotation
  2420. var lLRM = lPreRotationM.multiply( lRotationM ).multiply( lPostRotationM );
  2421. var lParentGRM = new Matrix4();
  2422. lParentGX.extractRotation( lParentGRM );
  2423. // Global Shear*Scaling
  2424. var lParentTM = new Matrix4();
  2425. var lLSM;
  2426. var lParentGSM;
  2427. var lParentGRSM;
  2428. lParentTM.copyPosition( lParentGX );
  2429. lParentGRSM = lParentTM.getInverse( lParentTM ).multiply( lParentGX );
  2430. lParentGSM = lParentGRM.getInverse( lParentGRM ).multiply( lParentGRSM );
  2431. lLSM = lScalingM;
  2432. var lGlobalRS;
  2433. if ( inheritType === 0 ) {
  2434. lGlobalRS = lParentGRM.multiply( lLRM ).multiply( lParentGSM ).multiply( lLSM );
  2435. } else if ( inheritType === 1 ) {
  2436. lGlobalRS = lParentGRM.multiply( lParentGSM ).multiply( lLRM ).multiply( lLSM );
  2437. } else {
  2438. var lParentLSM = new Matrix4().copy( lScalingM );
  2439. var lParentGSM_noLocal = lParentGSM.multiply( lParentLSM.getInverse( lParentLSM ) );
  2440. lGlobalRS = lParentGRM.multiply( lLRM ).multiply( lParentGSM_noLocal ).multiply( lLSM );
  2441. }
  2442. // Calculate the local transform matrix
  2443. var lTransform = lTranslationM.multiply( lRotationOffsetM ).multiply( lRotationPivotM ).multiply( lPreRotationM ).multiply( lRotationM ).multiply( lPostRotationM ).multiply( lRotationPivotM.getInverse( lRotationPivotM ) ).multiply( lScalingOffsetM ).multiply( lScalingPivotM ).multiply( lScalingM ).multiply( lScalingPivotM.getInverse( lScalingPivotM ) );
  2444. var lLocalTWithAllPivotAndOffsetInfo = new Matrix4().copyPosition( lTransform );
  2445. var lGlobalTranslation = lParentGX.multiply( lLocalTWithAllPivotAndOffsetInfo );
  2446. lGlobalT.copyPosition( lGlobalTranslation );
  2447. lTransform = lGlobalT.multiply( lGlobalRS );
  2448. return lTransform;
  2449. }
  2450. // Returns the three.js intrinsic Euler order corresponding to FBX extrinsic Euler order
  2451. // ref: http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_euler_html
  2452. function getEulerOrder( order ) {
  2453. order = order || 0;
  2454. var enums = [
  2455. 'ZYX', // -> XYZ extrinsic
  2456. 'YZX', // -> XZY extrinsic
  2457. 'XZY', // -> YZX extrinsic
  2458. 'ZXY', // -> YXZ extrinsic
  2459. 'YXZ', // -> ZXY extrinsic
  2460. 'XYZ', // -> ZYX extrinsic
  2461. //'SphericXYZ', // not possible to support
  2462. ];
  2463. if ( order === 6 ) {
  2464. console.warn( 'THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect.' );
  2465. return enums[ 0 ];
  2466. }
  2467. return enums[ order ];
  2468. }
  2469. // Parses comma separated list of numbers and returns them an array.
  2470. // Used internally by the TextParser
  2471. function parseNumberArray( value ) {
  2472. var array = value.split( ',' ).map( function ( val ) {
  2473. return parseFloat( val );
  2474. } );
  2475. return array;
  2476. }
  2477. function convertArrayBufferToString( buffer, from, to ) {
  2478. if ( from === undefined ) from = 0;
  2479. if ( to === undefined ) to = buffer.byteLength;
  2480. return LoaderUtils.decodeText( new Uint8Array( buffer, from, to ) );
  2481. }
  2482. function append( a, b ) {
  2483. for ( var i = 0, j = a.length, l = b.length; i < l; i ++, j ++ ) {
  2484. a[ j ] = b[ i ];
  2485. }
  2486. }
  2487. function slice( a, b, from, to ) {
  2488. for ( var i = from, j = 0; i < to; i ++, j ++ ) {
  2489. a[ j ] = b[ i ];
  2490. }
  2491. return a;
  2492. }
  2493. // inject array a2 into array a1 at index
  2494. function inject( a1, index, a2 ) {
  2495. return a1.slice( 0, index ).concat( a2 ).concat( a1.slice( index ) );
  2496. }
  2497. return FBXLoader;
  2498. } )();
  2499. export { FBXLoader };