FBXLoader.js 85 KB

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