FBXLoader.js 99 KB

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