2
0

FBXLoader.js 87 KB

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