2
0

FBXLoader.js 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521
  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 skeletons = parseDeformers( FBXTree, connections );
  63. var geometryMap = parseGeometries( FBXTree, connections, skeletons );
  64. var sceneGraph = parseScene( FBXTree, connections, 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. if ( 'Deformer' in FBXTree.Objects ) {
  365. var DeformerNodes = FBXTree.Objects.Deformer;
  366. for ( var nodeID in DeformerNodes ) {
  367. var deformerNode = DeformerNodes[ nodeID ];
  368. if ( deformerNode.attrType === 'Skin' ) {
  369. var relationships = connections.get( parseInt( nodeID ) );
  370. var skeleton = parseSkeleton( relationships, DeformerNodes );
  371. skeleton.ID = nodeID;
  372. if ( relationships.parents.length > 1 ) console.warn( 'THREE.FBXLoader: skeleton attached to more than one geometry is not supported.' );
  373. skeleton.geometryID = relationships.parents[ 0 ].ID;
  374. skeletons[ nodeID ] = skeleton;
  375. }
  376. }
  377. }
  378. return skeletons;
  379. }
  380. // Parse single nodes in FBXTree.Objects.Deformer
  381. // The top level deformer nodes have type 'Skin' and subDeformer nodes have type 'Cluster'
  382. // Each skin node represents a skeleton and each cluster node represents a bone
  383. function parseSkeleton( connections, deformerNodes ) {
  384. var rawBones = [];
  385. connections.children.forEach( function ( child ) {
  386. var subDeformerNode = deformerNodes[ child.ID ];
  387. if ( subDeformerNode.attrType !== 'Cluster' ) return;
  388. var rawBone = {
  389. ID: child.ID,
  390. indices: [],
  391. weights: [],
  392. transform: new THREE.Matrix4().fromArray( subDeformerNode.Transform.a ),
  393. transformLink: new THREE.Matrix4().fromArray( subDeformerNode.TransformLink.a ),
  394. linkMode: subDeformerNode.Mode,
  395. };
  396. if ( 'Indexes' in subDeformerNode ) {
  397. rawBone.indices = subDeformerNode.Indexes.a;
  398. rawBone.weights = subDeformerNode.Weights.a;
  399. }
  400. rawBones.push( rawBone );
  401. } );
  402. return {
  403. rawBones: rawBones,
  404. bones: []
  405. };
  406. }
  407. // Parse nodes in FBXTree.Objects.Geometry
  408. function parseGeometries( FBXTree, connections, skeletons ) {
  409. var geometryMap = new Map();
  410. if ( 'Geometry' in FBXTree.Objects ) {
  411. var geometryNodes = FBXTree.Objects.Geometry;
  412. for ( var nodeID in geometryNodes ) {
  413. var relationships = connections.get( parseInt( nodeID ) );
  414. var geo = parseGeometry( FBXTree, relationships, geometryNodes[ nodeID ], skeletons );
  415. geometryMap.set( parseInt( nodeID ), geo );
  416. }
  417. }
  418. return geometryMap;
  419. }
  420. // Parse single node in FBXTree.Objects.Geometry
  421. function parseGeometry( FBXTree, relationships, geometryNode, skeletons ) {
  422. switch ( geometryNode.attrType ) {
  423. case 'Mesh':
  424. return parseMeshGeometry( FBXTree, relationships, geometryNode, skeletons );
  425. break;
  426. case 'NurbsCurve':
  427. return parseNurbsGeometry( geometryNode );
  428. break;
  429. }
  430. }
  431. // Parse single node mesh geometry in FBXTree.Objects.Geometry
  432. function parseMeshGeometry( FBXTree, relationships, geometryNode, skeletons ) {
  433. var modelNodes = relationships.parents.map( function ( parent ) {
  434. return FBXTree.Objects.Model[ parent.ID ];
  435. } );
  436. // don't create geometry if it is not associated with any models
  437. if ( modelNodes.length === 0 ) return;
  438. var skeleton = relationships.children.reduce( function ( skeleton, child ) {
  439. if ( skeletons[ child.ID ] !== undefined ) skeleton = skeletons[ child.ID ];
  440. return skeleton;
  441. }, null );
  442. var preTransform = new THREE.Matrix4();
  443. // TODO: if there is more than one model associated with the geometry, AND the models have
  444. // different geometric transforms, then this will cause problems
  445. // if ( modelNodes.length > 1 ) { }
  446. // For now just assume one model and get the preRotations from that
  447. var modelNode = modelNodes[ 0 ];
  448. if ( 'GeometricRotation' in modelNode ) {
  449. var array = modelNode.GeometricRotation.value.map( THREE.Math.degToRad );
  450. array[ 3 ] = 'ZYX';
  451. preTransform.makeRotationFromEuler( new THREE.Euler().fromArray( array ) );
  452. }
  453. if ( 'GeometricTranslation' in modelNode ) {
  454. preTransform.setPosition( new THREE.Vector3().fromArray( modelNode.GeometricTranslation.value ) );
  455. }
  456. if ( 'GeometricScaling' in modelNode ) {
  457. preTransform.scale( new THREE.Vector3().fromArray( modelNode.GeometricScaling.value ) );
  458. }
  459. return genGeometry( FBXTree, relationships, geometryNode, skeleton, preTransform );
  460. }
  461. // Generate a THREE.BufferGeometry from a node in FBXTree.Objects.Geometry
  462. function genGeometry( FBXTree, relationships, geometryNode, skeleton, preTransform ) {
  463. var vertexPositions = ( geometryNode.Vertices !== undefined ) ? geometryNode.Vertices.a : [];
  464. var vertexIndices = ( geometryNode.PolygonVertexIndex !== undefined ) ? geometryNode.PolygonVertexIndex.a : [];
  465. // create arrays to hold the final data used to build the buffergeometry
  466. var vertexBuffer = [];
  467. var normalBuffer = [];
  468. var colorsBuffer = [];
  469. var uvsBuffer = [];
  470. var materialIndexBuffer = [];
  471. var vertexWeightsBuffer = [];
  472. var weightsIndicesBuffer = [];
  473. if ( geometryNode.LayerElementColor ) {
  474. var colorInfo = getColors( geometryNode.LayerElementColor[ 0 ] );
  475. }
  476. if ( geometryNode.LayerElementMaterial ) {
  477. var materialInfo = getMaterials( geometryNode.LayerElementMaterial[ 0 ] );
  478. }
  479. if ( geometryNode.LayerElementNormal ) {
  480. var normalInfo = getNormals( geometryNode.LayerElementNormal[ 0 ] );
  481. }
  482. if ( geometryNode.LayerElementUV ) {
  483. var uvInfo = [];
  484. var i = 0;
  485. while ( geometryNode.LayerElementUV[ i ] ) {
  486. uvInfo.push( getUVs( geometryNode.LayerElementUV[ i ] ) );
  487. i ++;
  488. }
  489. }
  490. var weightTable = {};
  491. if ( skeleton !== null ) {
  492. skeleton.rawBones.forEach( function ( rawBone, i ) {
  493. // loop over the bone's vertex indices and weights
  494. rawBone.indices.forEach( function ( index, j ) {
  495. if ( weightTable[ index ] === undefined ) weightTable[ index ] = [];
  496. weightTable[ index ].push( {
  497. id: i,
  498. weight: rawBone.weights[ j ],
  499. } );
  500. } );
  501. } );
  502. }
  503. var polygonIndex = 0;
  504. var faceLength = 0;
  505. var displayedWeightsWarning = false;
  506. // these will hold data for a single face
  507. var vertexPositionIndexes = [];
  508. var faceNormals = [];
  509. var faceColors = [];
  510. var faceUVs = [];
  511. var faceWeights = [];
  512. var faceWeightIndices = [];
  513. vertexIndices.forEach( function ( vertexIndex, polygonVertexIndex ) {
  514. var endOfFace = false;
  515. // Face index and vertex index arrays are combined in a single array
  516. // A cube with quad faces looks like this:
  517. // PolygonVertexIndex: *24 {
  518. // 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
  519. // }
  520. // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3
  521. // to find index of last vertex multiply by -1 and subtract 1: -3 * - 1 - 1 = 2
  522. if ( vertexIndex < 0 ) {
  523. vertexIndex = vertexIndex ^ - 1; // equivalent to ( x * -1 ) - 1
  524. vertexIndices[ polygonVertexIndex ] = vertexIndex;
  525. endOfFace = true;
  526. }
  527. var weightIndices = [];
  528. var weights = [];
  529. vertexPositionIndexes.push( vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2 );
  530. if ( colorInfo ) {
  531. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, colorInfo );
  532. faceColors.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  533. }
  534. if ( skeleton ) {
  535. if ( weightTable[ vertexIndex ] !== undefined ) {
  536. weightTable[ vertexIndex ].forEach( function ( wt ) {
  537. weights.push( wt.weight );
  538. weightIndices.push( wt.id );
  539. } );
  540. }
  541. if ( weights.length > 4 ) {
  542. if ( ! displayedWeightsWarning ) {
  543. console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
  544. displayedWeightsWarning = true;
  545. }
  546. var wIndex = [ 0, 0, 0, 0 ];
  547. var Weight = [ 0, 0, 0, 0 ];
  548. weights.forEach( function ( weight, weightIndex ) {
  549. var currentWeight = weight;
  550. var currentIndex = weightIndices[ weightIndex ];
  551. Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) {
  552. if ( currentWeight > comparedWeight ) {
  553. comparedWeightArray[ comparedWeightIndex ] = currentWeight;
  554. currentWeight = comparedWeight;
  555. var tmp = wIndex[ comparedWeightIndex ];
  556. wIndex[ comparedWeightIndex ] = currentIndex;
  557. currentIndex = tmp;
  558. }
  559. } );
  560. } );
  561. weightIndices = wIndex;
  562. weights = Weight;
  563. }
  564. // if the weight array is shorter than 4 pad with 0s
  565. while ( weights.length < 4 ) {
  566. weights.push( 0 );
  567. weightIndices.push( 0 );
  568. }
  569. for ( var i = 0; i < 4; ++ i ) {
  570. faceWeights.push( weights[ i ] );
  571. faceWeightIndices.push( weightIndices[ i ] );
  572. }
  573. }
  574. if ( normalInfo ) {
  575. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, normalInfo );
  576. faceNormals.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  577. }
  578. if ( materialInfo && materialInfo.mappingType !== 'AllSame' ) {
  579. var materialIndex = getData( polygonVertexIndex, polygonIndex, vertexIndex, materialInfo )[ 0 ];
  580. }
  581. if ( uvInfo ) {
  582. uvInfo.forEach( function ( uv, i ) {
  583. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, uv );
  584. if ( faceUVs[ i ] === undefined ) {
  585. faceUVs[ i ] = [];
  586. }
  587. faceUVs[ i ].push( data[ 0 ] );
  588. faceUVs[ i ].push( data[ 1 ] );
  589. } );
  590. }
  591. faceLength ++;
  592. // we have reached the end of a face - it may have 4 sides though
  593. // in which case the data is split to represent two 3 sided faces
  594. if ( endOfFace ) {
  595. for ( var i = 2; i < faceLength; i ++ ) {
  596. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ 0 ] ] );
  597. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ 1 ] ] );
  598. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ 2 ] ] );
  599. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ ( i - 1 ) * 3 ] ] );
  600. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ ( i - 1 ) * 3 + 1 ] ] );
  601. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ ( i - 1 ) * 3 + 2 ] ] );
  602. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ i * 3 ] ] );
  603. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ i * 3 + 1 ] ] );
  604. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ i * 3 + 2 ] ] );
  605. if ( skeleton ) {
  606. vertexWeightsBuffer.push( faceWeights[ 0 ] );
  607. vertexWeightsBuffer.push( faceWeights[ 1 ] );
  608. vertexWeightsBuffer.push( faceWeights[ 2 ] );
  609. vertexWeightsBuffer.push( faceWeights[ 3 ] );
  610. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 ] );
  611. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 + 1 ] );
  612. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 + 2 ] );
  613. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 + 3 ] );
  614. vertexWeightsBuffer.push( faceWeights[ i * 4 ] );
  615. vertexWeightsBuffer.push( faceWeights[ i * 4 + 1 ] );
  616. vertexWeightsBuffer.push( faceWeights[ i * 4 + 2 ] );
  617. vertexWeightsBuffer.push( faceWeights[ i * 4 + 3 ] );
  618. weightsIndicesBuffer.push( faceWeightIndices[ 0 ] );
  619. weightsIndicesBuffer.push( faceWeightIndices[ 1 ] );
  620. weightsIndicesBuffer.push( faceWeightIndices[ 2 ] );
  621. weightsIndicesBuffer.push( faceWeightIndices[ 3 ] );
  622. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 ] );
  623. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 + 1 ] );
  624. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 + 2 ] );
  625. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 + 3 ] );
  626. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 ] );
  627. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 + 1 ] );
  628. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 + 2 ] );
  629. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 + 3 ] );
  630. }
  631. if ( colorInfo ) {
  632. colorsBuffer.push( faceColors[ 0 ] );
  633. colorsBuffer.push( faceColors[ 1 ] );
  634. colorsBuffer.push( faceColors[ 2 ] );
  635. colorsBuffer.push( faceColors[ ( i - 1 ) * 3 ] );
  636. colorsBuffer.push( faceColors[ ( i - 1 ) * 3 + 1 ] );
  637. colorsBuffer.push( faceColors[ ( i - 1 ) * 3 + 2 ] );
  638. colorsBuffer.push( faceColors[ i * 3 ] );
  639. colorsBuffer.push( faceColors[ i * 3 + 1 ] );
  640. colorsBuffer.push( faceColors[ i * 3 + 2 ] );
  641. }
  642. if ( materialInfo && materialInfo.mappingType !== 'AllSame' ) {
  643. materialIndexBuffer.push( materialIndex );
  644. materialIndexBuffer.push( materialIndex );
  645. materialIndexBuffer.push( materialIndex );
  646. }
  647. if ( normalInfo ) {
  648. normalBuffer.push( faceNormals[ 0 ] );
  649. normalBuffer.push( faceNormals[ 1 ] );
  650. normalBuffer.push( faceNormals[ 2 ] );
  651. normalBuffer.push( faceNormals[ ( i - 1 ) * 3 ] );
  652. normalBuffer.push( faceNormals[ ( i - 1 ) * 3 + 1 ] );
  653. normalBuffer.push( faceNormals[ ( i - 1 ) * 3 + 2 ] );
  654. normalBuffer.push( faceNormals[ i * 3 ] );
  655. normalBuffer.push( faceNormals[ i * 3 + 1 ] );
  656. normalBuffer.push( faceNormals[ i * 3 + 2 ] );
  657. }
  658. if ( uvInfo ) {
  659. uvInfo.forEach( function ( uv, j ) {
  660. if ( uvsBuffer[ j ] === undefined ) uvsBuffer[ j ] = [];
  661. uvsBuffer[ j ].push( faceUVs[ j ][ 0 ] );
  662. uvsBuffer[ j ].push( faceUVs[ j ][ 1 ] );
  663. uvsBuffer[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 ] );
  664. uvsBuffer[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 + 1 ] );
  665. uvsBuffer[ j ].push( faceUVs[ j ][ i * 2 ] );
  666. uvsBuffer[ j ].push( faceUVs[ j ][ i * 2 + 1 ] );
  667. } );
  668. }
  669. }
  670. polygonIndex ++;
  671. faceLength = 0;
  672. // reset arrays for the next face
  673. vertexPositionIndexes = [];
  674. faceNormals = [];
  675. faceColors = [];
  676. faceUVs = [];
  677. faceWeights = [];
  678. faceWeightIndices = [];
  679. }
  680. } );
  681. var geo = new THREE.BufferGeometry();
  682. geo.name = geometryNode.name;
  683. var positionAttribute = new THREE.Float32BufferAttribute( vertexBuffer, 3 );
  684. preTransform.applyToBufferAttribute( positionAttribute );
  685. geo.addAttribute( 'position', positionAttribute );
  686. if ( colorsBuffer.length > 0 ) {
  687. geo.addAttribute( 'color', new THREE.Float32BufferAttribute( colorsBuffer, 3 ) );
  688. }
  689. if ( skeleton ) {
  690. geo.addAttribute( 'skinIndex', new THREE.Uint16BufferAttribute( weightsIndicesBuffer, 4 ) );
  691. geo.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( vertexWeightsBuffer, 4 ) );
  692. // used later to bind the skeleton to the model
  693. geo.FBX_Deformer = skeleton;
  694. }
  695. if ( normalBuffer.length > 0 ) {
  696. var normalAttribute = new THREE.Float32BufferAttribute( normalBuffer, 3 );
  697. var normalMatrix = new THREE.Matrix3().getNormalMatrix( preTransform );
  698. normalMatrix.applyToBufferAttribute( normalAttribute );
  699. geo.addAttribute( 'normal', normalAttribute );
  700. }
  701. uvsBuffer.forEach( function ( uvBuffer, i ) {
  702. // subsequent uv buffers are called 'uv1', 'uv2', ...
  703. var name = 'uv' + ( i + 1 ).toString();
  704. // the first uv buffer is just called 'uv'
  705. if ( i === 0 ) {
  706. name = 'uv';
  707. }
  708. geo.addAttribute( name, new THREE.Float32BufferAttribute( uvsBuffer[ i ], 2 ) );
  709. } );
  710. if ( materialInfo && materialInfo.mappingType !== 'AllSame' ) {
  711. // Convert the material indices of each vertex into rendering groups on the geometry.
  712. var prevMaterialIndex = materialIndexBuffer[ 0 ];
  713. var startIndex = 0;
  714. materialIndexBuffer.forEach( function ( currentIndex, i ) {
  715. if ( currentIndex !== prevMaterialIndex ) {
  716. geo.addGroup( startIndex, i - startIndex, prevMaterialIndex );
  717. prevMaterialIndex = currentIndex;
  718. startIndex = i;
  719. }
  720. } );
  721. // the loop above doesn't add the last group, do that here.
  722. if ( geo.groups.length > 0 ) {
  723. var lastGroup = geo.groups[ geo.groups.length - 1 ];
  724. var lastIndex = lastGroup.start + lastGroup.count;
  725. if ( lastIndex !== materialIndexBuffer.length ) {
  726. geo.addGroup( lastIndex, materialIndexBuffer.length - lastIndex, prevMaterialIndex );
  727. }
  728. }
  729. // case where there are multiple materials but the whole geometry is only
  730. // using one of them
  731. if ( geo.groups.length === 0 ) {
  732. geo.addGroup( 0, materialIndexBuffer.length, materialIndexBuffer[ 0 ] );
  733. }
  734. }
  735. return geo;
  736. }
  737. // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists
  738. function getNormals( NormalNode ) {
  739. var mappingType = NormalNode.MappingInformationType;
  740. var referenceType = NormalNode.ReferenceInformationType;
  741. var buffer = NormalNode.Normals.a;
  742. var indexBuffer = [];
  743. if ( referenceType === 'IndexToDirect' ) {
  744. if ( 'NormalIndex' in NormalNode ) {
  745. indexBuffer = NormalNode.NormalIndex.a;
  746. } else if ( 'NormalsIndex' in NormalNode ) {
  747. indexBuffer = NormalNode.NormalsIndex.a;
  748. }
  749. }
  750. return {
  751. dataSize: 3,
  752. buffer: buffer,
  753. indices: indexBuffer,
  754. mappingType: mappingType,
  755. referenceType: referenceType
  756. };
  757. }
  758. // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists
  759. function getUVs( UVNode ) {
  760. var mappingType = UVNode.MappingInformationType;
  761. var referenceType = UVNode.ReferenceInformationType;
  762. var buffer = UVNode.UV.a;
  763. var indexBuffer = [];
  764. if ( referenceType === 'IndexToDirect' ) {
  765. indexBuffer = UVNode.UVIndex.a;
  766. }
  767. return {
  768. dataSize: 2,
  769. buffer: buffer,
  770. indices: indexBuffer,
  771. mappingType: mappingType,
  772. referenceType: referenceType
  773. };
  774. }
  775. // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists
  776. function getColors( ColorNode ) {
  777. var mappingType = ColorNode.MappingInformationType;
  778. var referenceType = ColorNode.ReferenceInformationType;
  779. var buffer = ColorNode.Colors.a;
  780. var indexBuffer = [];
  781. if ( referenceType === 'IndexToDirect' ) {
  782. indexBuffer = ColorNode.ColorIndex.a;
  783. }
  784. return {
  785. dataSize: 4,
  786. buffer: buffer,
  787. indices: indexBuffer,
  788. mappingType: mappingType,
  789. referenceType: referenceType
  790. };
  791. }
  792. // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists
  793. function getMaterials( MaterialNode ) {
  794. var mappingType = MaterialNode.MappingInformationType;
  795. var referenceType = MaterialNode.ReferenceInformationType;
  796. if ( mappingType === 'NoMappingInformation' ) {
  797. return {
  798. dataSize: 1,
  799. buffer: [ 0 ],
  800. indices: [ 0 ],
  801. mappingType: 'AllSame',
  802. referenceType: referenceType
  803. };
  804. }
  805. var materialIndexBuffer = MaterialNode.Materials.a;
  806. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  807. // we expect.So we create an intermediate buffer that points to the index in the buffer,
  808. // for conforming with the other functions we've written for other data.
  809. var materialIndices = [];
  810. for ( var i = 0; i < materialIndexBuffer.length; ++ i ) {
  811. materialIndices.push( i );
  812. }
  813. return {
  814. dataSize: 1,
  815. buffer: materialIndexBuffer,
  816. indices: materialIndices,
  817. mappingType: mappingType,
  818. referenceType: referenceType
  819. };
  820. }
  821. var dataArray = [];
  822. function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  823. var index;
  824. switch ( infoObject.mappingType ) {
  825. case 'ByPolygonVertex' :
  826. index = polygonVertexIndex;
  827. break;
  828. case 'ByPolygon' :
  829. index = polygonIndex;
  830. break;
  831. case 'ByVertice' :
  832. index = vertexIndex;
  833. break;
  834. case 'AllSame' :
  835. index = infoObject.indices[ 0 ];
  836. break;
  837. default :
  838. console.warn( 'THREE.FBXLoader: unknown attribute mapping type ' + infoObject.mappingType );
  839. }
  840. if ( infoObject.referenceType === 'IndexToDirect' ) index = infoObject.indices[ index ];
  841. var from = index * infoObject.dataSize;
  842. var to = from + infoObject.dataSize;
  843. return slice( dataArray, infoObject.buffer, from, to );
  844. }
  845. // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry
  846. function parseNurbsGeometry( geometryNode ) {
  847. if ( THREE.NURBSCurve === undefined ) {
  848. console.error( 'THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.' );
  849. return new THREE.BufferGeometry();
  850. }
  851. var order = parseInt( geometryNode.Order );
  852. if ( isNaN( order ) ) {
  853. console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geometryNode.Order, geometryNode.id );
  854. return new THREE.BufferGeometry();
  855. }
  856. var degree = order - 1;
  857. var knots = geometryNode.KnotVector.a;
  858. var controlPoints = [];
  859. var pointsValues = geometryNode.Points.a;
  860. for ( var i = 0, l = pointsValues.length; i < l; i += 4 ) {
  861. controlPoints.push( new THREE.Vector4().fromArray( pointsValues, i ) );
  862. }
  863. var startKnot, endKnot;
  864. if ( geometryNode.Form === 'Closed' ) {
  865. controlPoints.push( controlPoints[ 0 ] );
  866. } else if ( geometryNode.Form === 'Periodic' ) {
  867. startKnot = degree;
  868. endKnot = knots.length - 1 - startKnot;
  869. for ( var i = 0; i < degree; ++ i ) {
  870. controlPoints.push( controlPoints[ i ] );
  871. }
  872. }
  873. var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
  874. var vertices = curve.getPoints( controlPoints.length * 7 );
  875. var positions = new Float32Array( vertices.length * 3 );
  876. vertices.forEach( function ( vertex, i ) {
  877. vertex.toArray( positions, i * 3 );
  878. } );
  879. var geometry = new THREE.BufferGeometry();
  880. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  881. return geometry;
  882. }
  883. // create the main THREE.Group() to be returned by the loader
  884. function parseScene( FBXTree, connections, skeletons, geometryMap, materialMap ) {
  885. var sceneGraph = new THREE.Group();
  886. var modelMap = parseModels( FBXTree, skeletons, geometryMap, materialMap, connections );
  887. var modelNodes = FBXTree.Objects.Model;
  888. modelMap.forEach( function ( model ) {
  889. var modelNode = modelNodes[ model.ID ];
  890. setLookAtProperties( FBXTree, model, modelNode, connections, sceneGraph );
  891. var parentConnections = connections.get( model.ID ).parents;
  892. parentConnections.forEach( function ( connection ) {
  893. var parent = modelMap.get( connection.ID );
  894. if ( parent !== undefined ) parent.add( model );
  895. } );
  896. if ( model.parent === null ) {
  897. sceneGraph.add( model );
  898. }
  899. } );
  900. bindSkeleton( FBXTree, skeletons, geometryMap, modelMap, connections );
  901. addAnimations( FBXTree, connections, sceneGraph );
  902. createAmbientLight( FBXTree, sceneGraph );
  903. return sceneGraph;
  904. }
  905. // parse nodes in FBXTree.Objects.Model
  906. function parseModels( FBXTree, skeletons, geometryMap, materialMap, connections ) {
  907. var modelMap = new Map();
  908. var modelNodes = FBXTree.Objects.Model;
  909. for ( var nodeID in modelNodes ) {
  910. var id = parseInt( nodeID );
  911. var node = modelNodes[ nodeID ];
  912. var relationships = connections.get( id );
  913. var model = buildSkeleton( relationships, skeletons, id, node.attrName );
  914. if ( ! model ) {
  915. switch ( node.attrType ) {
  916. case 'Camera':
  917. model = createCamera( FBXTree, relationships );
  918. break;
  919. case 'Light':
  920. model = createLight( FBXTree, relationships );
  921. break;
  922. case 'Mesh':
  923. model = createMesh( FBXTree, relationships, geometryMap, materialMap );
  924. break;
  925. case 'NurbsCurve':
  926. model = createCurve( relationships, geometryMap );
  927. break;
  928. case 'LimbNode': // usually associated with a Bone, however if a Bone was not created we'll make a Group instead
  929. case 'Null':
  930. default:
  931. model = new THREE.Group();
  932. break;
  933. }
  934. model.name = THREE.PropertyBinding.sanitizeNodeName( node.attrName );
  935. model.ID = id;
  936. }
  937. setModelTransforms( FBXTree, model, node );
  938. modelMap.set( id, model );
  939. }
  940. return modelMap;
  941. }
  942. function buildSkeleton( relationships, skeletons, id, name ) {
  943. var bone = null;
  944. relationships.parents.forEach( function ( parent ) {
  945. for ( var ID in skeletons ) {
  946. var skeleton = skeletons[ ID ];
  947. skeleton.rawBones.forEach( function ( rawBone, i ) {
  948. if ( rawBone.ID === parent.ID ) {
  949. var subBone = bone;
  950. bone = new THREE.Bone();
  951. bone.matrixWorld.copy( rawBone.transformLink );
  952. // set name and id here - otherwise in cases where "subBone" is created it will not have a name / id
  953. bone.name = THREE.PropertyBinding.sanitizeNodeName( name );
  954. bone.ID = id;
  955. skeleton.bones[ i ] = bone;
  956. // In cases where a bone is shared between multiple meshes
  957. // duplicate the bone here and and it as a child of the first bone
  958. if ( subBone !== null ) {
  959. bone.add( subBone );
  960. }
  961. }
  962. } );
  963. }
  964. } );
  965. return bone;
  966. }
  967. // create a THREE.PerspectiveCamera or THREE.OrthographicCamera
  968. function createCamera( FBXTree, relationships ) {
  969. var model;
  970. var cameraAttribute;
  971. relationships.children.forEach( function ( child ) {
  972. var attr = FBXTree.Objects.NodeAttribute[ child.ID ];
  973. if ( attr !== undefined ) {
  974. cameraAttribute = attr;
  975. }
  976. } );
  977. if ( cameraAttribute === undefined ) {
  978. model = new THREE.Object3D();
  979. } else {
  980. var type = 0;
  981. if ( cameraAttribute.CameraProjectionType !== undefined && cameraAttribute.CameraProjectionType.value === 1 ) {
  982. type = 1;
  983. }
  984. var nearClippingPlane = 1;
  985. if ( cameraAttribute.NearPlane !== undefined ) {
  986. nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
  987. }
  988. var farClippingPlane = 1000;
  989. if ( cameraAttribute.FarPlane !== undefined ) {
  990. farClippingPlane = cameraAttribute.FarPlane.value / 1000;
  991. }
  992. var width = window.innerWidth;
  993. var height = window.innerHeight;
  994. if ( cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined ) {
  995. width = cameraAttribute.AspectWidth.value;
  996. height = cameraAttribute.AspectHeight.value;
  997. }
  998. var aspect = width / height;
  999. var fov = 45;
  1000. if ( cameraAttribute.FieldOfView !== undefined ) {
  1001. fov = cameraAttribute.FieldOfView.value;
  1002. }
  1003. var focalLength = cameraAttribute.FocalLength ? cameraAttribute.FocalLength.value : null;
  1004. switch ( type ) {
  1005. case 0: // Perspective
  1006. model = new THREE.PerspectiveCamera( fov, aspect, nearClippingPlane, farClippingPlane );
  1007. if ( focalLength !== null ) model.setFocalLength( focalLength );
  1008. break;
  1009. case 1: // Orthographic
  1010. model = new THREE.OrthographicCamera( - width / 2, width / 2, height / 2, - height / 2, nearClippingPlane, farClippingPlane );
  1011. break;
  1012. default:
  1013. console.warn( 'THREE.FBXLoader: Unknown camera type ' + type + '.' );
  1014. model = new THREE.Object3D();
  1015. break;
  1016. }
  1017. }
  1018. return model;
  1019. }
  1020. // Create a THREE.DirectionalLight, THREE.PointLight or THREE.SpotLight
  1021. function createLight( FBXTree, relationships ) {
  1022. var model;
  1023. var lightAttribute;
  1024. relationships.children.forEach( function ( child ) {
  1025. var attr = FBXTree.Objects.NodeAttribute[ child.ID ];
  1026. if ( attr !== undefined ) {
  1027. lightAttribute = attr;
  1028. }
  1029. } );
  1030. if ( lightAttribute === undefined ) {
  1031. model = new THREE.Object3D();
  1032. } else {
  1033. var type;
  1034. // LightType can be undefined for Point lights
  1035. if ( lightAttribute.LightType === undefined ) {
  1036. type = 0;
  1037. } else {
  1038. type = lightAttribute.LightType.value;
  1039. }
  1040. var color = 0xffffff;
  1041. if ( lightAttribute.Color !== undefined ) {
  1042. color = new THREE.Color().fromArray( lightAttribute.Color.value );
  1043. }
  1044. var intensity = ( lightAttribute.Intensity === undefined ) ? 1 : lightAttribute.Intensity.value / 100;
  1045. // light disabled
  1046. if ( lightAttribute.CastLightOnObject !== undefined && lightAttribute.CastLightOnObject.value === 0 ) {
  1047. intensity = 0;
  1048. }
  1049. var distance = 0;
  1050. if ( lightAttribute.FarAttenuationEnd !== undefined ) {
  1051. if ( lightAttribute.EnableFarAttenuation !== undefined && lightAttribute.EnableFarAttenuation.value === 0 ) {
  1052. distance = 0;
  1053. } else {
  1054. distance = lightAttribute.FarAttenuationEnd.value;
  1055. }
  1056. }
  1057. // TODO: could this be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
  1058. var decay = 1;
  1059. switch ( type ) {
  1060. case 0: // Point
  1061. model = new THREE.PointLight( color, intensity, distance, decay );
  1062. break;
  1063. case 1: // Directional
  1064. model = new THREE.DirectionalLight( color, intensity );
  1065. break;
  1066. case 2: // Spot
  1067. var angle = Math.PI / 3;
  1068. if ( lightAttribute.InnerAngle !== undefined ) {
  1069. angle = THREE.Math.degToRad( lightAttribute.InnerAngle.value );
  1070. }
  1071. var penumbra = 0;
  1072. if ( lightAttribute.OuterAngle !== undefined ) {
  1073. // TODO: this is not correct - FBX calculates outer and inner angle in degrees
  1074. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  1075. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  1076. penumbra = THREE.Math.degToRad( lightAttribute.OuterAngle.value );
  1077. penumbra = Math.max( penumbra, 1 );
  1078. }
  1079. model = new THREE.SpotLight( color, intensity, distance, angle, penumbra, decay );
  1080. break;
  1081. default:
  1082. console.warn( 'THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a THREE.PointLight.' );
  1083. model = new THREE.PointLight( color, intensity );
  1084. break;
  1085. }
  1086. if ( lightAttribute.CastShadows !== undefined && lightAttribute.CastShadows.value === 1 ) {
  1087. model.castShadow = true;
  1088. }
  1089. }
  1090. return model;
  1091. }
  1092. function createMesh( FBXTree, relationships, geometryMap, materialMap ) {
  1093. var model;
  1094. var geometry = null;
  1095. var material = null;
  1096. var materials = [];
  1097. // get geometry and materials(s) from connections
  1098. relationships.children.forEach( function ( child ) {
  1099. if ( geometryMap.has( child.ID ) ) {
  1100. geometry = geometryMap.get( child.ID );
  1101. }
  1102. if ( materialMap.has( child.ID ) ) {
  1103. materials.push( materialMap.get( child.ID ) );
  1104. }
  1105. } );
  1106. if ( materials.length > 1 ) {
  1107. material = materials;
  1108. } else if ( materials.length > 0 ) {
  1109. material = materials[ 0 ];
  1110. } else {
  1111. material = new THREE.MeshPhongMaterial( { color: 0xcccccc } );
  1112. materials.push( material );
  1113. }
  1114. if ( 'color' in geometry.attributes ) {
  1115. materials.forEach( function ( material ) {
  1116. material.vertexColors = THREE.VertexColors;
  1117. } );
  1118. }
  1119. if ( geometry.FBX_Deformer ) {
  1120. materials.forEach( function ( material ) {
  1121. material.skinning = true;
  1122. } );
  1123. model = new THREE.SkinnedMesh( geometry, material );
  1124. } else {
  1125. model = new THREE.Mesh( geometry, material );
  1126. }
  1127. return model;
  1128. }
  1129. function createCurve( relationships, geometryMap ) {
  1130. var geometry = relationships.children.reduce( function ( geo, child ) {
  1131. if ( geometryMap.has( child.ID ) ) geo = geometryMap.get( child.ID );
  1132. return geo;
  1133. }, null );
  1134. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  1135. var material = new THREE.LineBasicMaterial( { color: 0x3300ff, linewidth: 1 } );
  1136. return new THREE.Line( geometry, material );
  1137. }
  1138. // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light
  1139. function createAmbientLight( FBXTree, sceneGraph ) {
  1140. if ( 'GlobalSettings' in FBXTree && 'AmbientColor' in FBXTree.GlobalSettings ) {
  1141. var ambientColor = FBXTree.GlobalSettings.AmbientColor.value;
  1142. var r = ambientColor[ 0 ];
  1143. var g = ambientColor[ 1 ];
  1144. var b = ambientColor[ 2 ];
  1145. if ( r !== 0 || g !== 0 || b !== 0 ) {
  1146. var color = new THREE.Color( r, g, b );
  1147. sceneGraph.add( new THREE.AmbientLight( color, 1 ) );
  1148. }
  1149. }
  1150. }
  1151. function setLookAtProperties( FBXTree, model, modelNode, connections, sceneGraph ) {
  1152. if ( 'LookAtProperty' in modelNode ) {
  1153. var children = connections.get( model.ID ).children;
  1154. children.forEach( function ( child ) {
  1155. if ( child.relationship === 'LookAtProperty' ) {
  1156. var lookAtTarget = FBXTree.Objects.Model[ child.ID ];
  1157. if ( 'Lcl_Translation' in lookAtTarget ) {
  1158. var pos = lookAtTarget.Lcl_Translation.value;
  1159. // DirectionalLight, SpotLight
  1160. if ( model.target !== undefined ) {
  1161. model.target.position.fromArray( pos );
  1162. sceneGraph.add( model.target );
  1163. } else { // Cameras and other Object3Ds
  1164. model.lookAt( new THREE.Vector3().fromArray( pos ) );
  1165. }
  1166. }
  1167. }
  1168. } );
  1169. }
  1170. }
  1171. // parse the model node for transform details and apply them to the model
  1172. function setModelTransforms( FBXTree, model, modelNode ) {
  1173. // http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_euler_html
  1174. if ( 'RotationOrder' in modelNode ) {
  1175. var enums = [
  1176. 'XYZ', // default
  1177. 'XZY',
  1178. 'YZX',
  1179. 'ZXY',
  1180. 'YXZ',
  1181. 'ZYX',
  1182. 'SphericXYZ',
  1183. ];
  1184. var value = parseInt( modelNode.RotationOrder.value, 10 );
  1185. if ( value > 0 && value < 6 ) {
  1186. // model.rotation.order = enums[ value ];
  1187. // Note: Euler order other than XYZ is currently not supported, so just display a warning for now
  1188. console.warn( 'THREE.FBXLoader: unsupported Euler Order: %s. Currently only XYZ order is supported. Animations and rotations may be incorrect.', enums[ value ] );
  1189. } else if ( value === 6 ) {
  1190. console.warn( 'THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect.' );
  1191. }
  1192. }
  1193. if ( 'Lcl_Translation' in modelNode ) {
  1194. model.position.fromArray( modelNode.Lcl_Translation.value );
  1195. }
  1196. if ( 'Lcl_Rotation' in modelNode ) {
  1197. var rotation = modelNode.Lcl_Rotation.value.map( THREE.Math.degToRad );
  1198. rotation.push( 'ZYX' );
  1199. model.quaternion.setFromEuler( new THREE.Euler().fromArray( rotation ) );
  1200. }
  1201. if ( 'Lcl_Scaling' in modelNode ) {
  1202. model.scale.fromArray( modelNode.Lcl_Scaling.value );
  1203. }
  1204. if ( 'PreRotation' in modelNode ) {
  1205. var array = modelNode.PreRotation.value.map( THREE.Math.degToRad );
  1206. array[ 3 ] = 'ZYX';
  1207. var preRotations = new THREE.Euler().fromArray( array );
  1208. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1209. model.quaternion.premultiply( preRotations );
  1210. }
  1211. }
  1212. function bindSkeleton( FBXTree, skeletons, geometryMap, modelMap, connections ) {
  1213. var bindMatrices = parsePoseNodes( FBXTree );
  1214. for ( var ID in skeletons ) {
  1215. var skeleton = skeletons[ ID ];
  1216. var parents = connections.get( parseInt( skeleton.ID ) ).parents;
  1217. parents.forEach( function ( parent ) {
  1218. if ( geometryMap.has( parent.ID ) ) {
  1219. var geoID = parent.ID;
  1220. var geoRelationships = connections.get( geoID );
  1221. geoRelationships.parents.forEach( function ( geoConnParent ) {
  1222. if ( modelMap.has( geoConnParent.ID ) ) {
  1223. var model = modelMap.get( geoConnParent.ID );
  1224. model.bind( new THREE.Skeleton( skeleton.bones ), bindMatrices[ geoConnParent.ID ] );
  1225. }
  1226. } );
  1227. }
  1228. } );
  1229. }
  1230. }
  1231. function parsePoseNodes( FBXTree ) {
  1232. var bindMatrices = {};
  1233. if ( 'Pose' in FBXTree.Objects ) {
  1234. var BindPoseNode = FBXTree.Objects.Pose;
  1235. for ( var nodeID in BindPoseNode ) {
  1236. if ( BindPoseNode[ nodeID ].attrType === 'BindPose' ) {
  1237. var poseNodes = BindPoseNode[ nodeID ].PoseNode;
  1238. if ( Array.isArray( poseNodes ) ) {
  1239. poseNodes.forEach( function ( poseNode ) {
  1240. bindMatrices[ poseNode.Node ] = new THREE.Matrix4().fromArray( poseNode.Matrix.a );
  1241. } );
  1242. } else {
  1243. bindMatrices[ poseNodes.Node ] = new THREE.Matrix4().fromArray( poseNodes.Matrix.a );
  1244. }
  1245. }
  1246. }
  1247. }
  1248. return bindMatrices;
  1249. }
  1250. function parseAnimations( FBXTree, connections ) {
  1251. // since the actual transformation data is stored in FBXTree.Objects.AnimationCurve,
  1252. // if this is undefined we can safely assume there are no animations
  1253. if ( FBXTree.Objects.AnimationCurve === undefined ) return undefined;
  1254. var curveNodesMap = parseAnimationCurveNodes( FBXTree );
  1255. parseAnimationCurves( FBXTree, connections, curveNodesMap );
  1256. var layersMap = parseAnimationLayers( FBXTree, connections, curveNodesMap );
  1257. var rawClips = parseAnimStacks( FBXTree, connections, layersMap );
  1258. return rawClips;
  1259. }
  1260. // parse nodes in FBXTree.Objects.AnimationCurveNode
  1261. // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation )
  1262. // and is referenced by an AnimationLayer
  1263. function parseAnimationCurveNodes( FBXTree ) {
  1264. var rawCurveNodes = FBXTree.Objects.AnimationCurveNode;
  1265. var curveNodesMap = new Map();
  1266. for ( var nodeID in rawCurveNodes ) {
  1267. var rawCurveNode = rawCurveNodes[ nodeID ];
  1268. if ( rawCurveNode.attrName.match( /S|R|T/ ) !== null ) {
  1269. var curveNode = {
  1270. id: rawCurveNode.id,
  1271. attr: rawCurveNode.attrName,
  1272. curves: {},
  1273. };
  1274. curveNodesMap.set( curveNode.id, curveNode );
  1275. }
  1276. }
  1277. return curveNodesMap;
  1278. }
  1279. // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to
  1280. // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated
  1281. // axis ( e.g. times and values of x rotation)
  1282. function parseAnimationCurves( FBXTree, connections, curveNodesMap ) {
  1283. var rawCurves = FBXTree.Objects.AnimationCurve;
  1284. for ( var nodeID in rawCurves ) {
  1285. var animationCurve = {
  1286. id: rawCurves[ nodeID ].id,
  1287. times: rawCurves[ nodeID ].KeyTime.a.map( convertFBXTimeToSeconds ),
  1288. values: rawCurves[ nodeID ].KeyValueFloat.a,
  1289. };
  1290. var relationships = connections.get( animationCurve.id );
  1291. if ( relationships !== undefined ) {
  1292. var animationCurveID = relationships.parents[ 0 ].ID;
  1293. var animationCurveRelationship = relationships.parents[ 0 ].relationship;
  1294. var axis = '';
  1295. if ( animationCurveRelationship.match( /X/ ) ) {
  1296. axis = 'x';
  1297. } else if ( animationCurveRelationship.match( /Y/ ) ) {
  1298. axis = 'y';
  1299. } else if ( animationCurveRelationship.match( /Z/ ) ) {
  1300. axis = 'z';
  1301. } else {
  1302. continue;
  1303. }
  1304. curveNodesMap.get( animationCurveID ).curves[ axis ] = animationCurve;
  1305. }
  1306. }
  1307. }
  1308. // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references
  1309. // to various AnimationCurveNodes and is referenced by an AnimationStack node
  1310. // note: theoretically a stack can multiple layers, however in practice there always seems to be one per stack
  1311. function parseAnimationLayers( FBXTree, connections, curveNodesMap ) {
  1312. var rawLayers = FBXTree.Objects.AnimationLayer;
  1313. var layersMap = new Map();
  1314. for ( var nodeID in rawLayers ) {
  1315. var layerCurveNodes = [];
  1316. var connection = connections.get( parseInt( nodeID ) );
  1317. if ( connection !== undefined ) {
  1318. // all the animationCurveNodes used in the layer
  1319. var children = connection.children;
  1320. children.forEach( function ( child, i ) {
  1321. if ( curveNodesMap.has( child.ID ) ) {
  1322. var curveNode = curveNodesMap.get( child.ID );
  1323. // check that the curves are defined for at least one axis, otherwise ignore the curveNode
  1324. if ( curveNode.curves.x !== undefined || curveNode.curves.y !== undefined || curveNode.curves.z !== undefined ) {
  1325. if ( layerCurveNodes[ i ] === undefined ) {
  1326. var modelID;
  1327. connections.get( child.ID ).parents.forEach( function ( parent ) {
  1328. if ( parent.relationship !== undefined ) modelID = parent.ID;
  1329. } );
  1330. var rawModel = FBXTree.Objects.Model[ modelID.toString() ];
  1331. var node = {
  1332. modelName: THREE.PropertyBinding.sanitizeNodeName( rawModel.attrName ),
  1333. initialPosition: [ 0, 0, 0 ],
  1334. initialRotation: [ 0, 0, 0 ],
  1335. initialScale: [ 1, 1, 1 ],
  1336. };
  1337. if ( 'Lcl_Translation' in rawModel ) node.initialPosition = rawModel.Lcl_Translation.value;
  1338. if ( 'Lcl_Rotation' in rawModel ) node.initialRotation = rawModel.Lcl_Rotation.value;
  1339. if ( 'Lcl_Scaling' in rawModel ) node.initialScale = rawModel.Lcl_Scaling.value;
  1340. // if the animated model is pre rotated, we'll have to apply the pre rotations to every
  1341. // animation value as well
  1342. if ( 'PreRotation' in rawModel ) node.preRotations = rawModel.PreRotation.value;
  1343. layerCurveNodes[ i ] = node;
  1344. }
  1345. layerCurveNodes[ i ][ curveNode.attr ] = curveNode;
  1346. }
  1347. }
  1348. } );
  1349. layersMap.set( parseInt( nodeID ), layerCurveNodes );
  1350. }
  1351. }
  1352. return layersMap;
  1353. }
  1354. // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation
  1355. // hierarchy. Each Stack node will be used to create a THREE.AnimationClip
  1356. function parseAnimStacks( FBXTree, connections, layersMap ) {
  1357. var rawStacks = FBXTree.Objects.AnimationStack;
  1358. // connect the stacks (clips) up to the layers
  1359. var rawClips = {};
  1360. for ( var nodeID in rawStacks ) {
  1361. var children = connections.get( parseInt( nodeID ) ).children;
  1362. if ( children.length > 1 ) {
  1363. // it seems like stacks will always be associated with a single layer. But just in case there are files
  1364. // where there are multiple layers per stack, we'll display a warning
  1365. console.warn( 'THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.' );
  1366. }
  1367. var layer = layersMap.get( children[ 0 ].ID );
  1368. rawClips[ nodeID ] = {
  1369. name: rawStacks[ nodeID ].attrName,
  1370. layer: layer,
  1371. };
  1372. }
  1373. return rawClips;
  1374. }
  1375. // take raw animation data from parseAnimations and connect it up to the loaded models
  1376. function addAnimations( FBXTree, connections, sceneGraph ) {
  1377. sceneGraph.animations = [];
  1378. var rawClips = parseAnimations( FBXTree, connections );
  1379. if ( rawClips === undefined ) return;
  1380. for ( var key in rawClips ) {
  1381. var rawClip = rawClips[ key ];
  1382. var clip = addClip( rawClip );
  1383. sceneGraph.animations.push( clip );
  1384. }
  1385. }
  1386. function addClip( rawClip ) {
  1387. var tracks = [];
  1388. rawClip.layer.forEach( function ( rawTracks ) {
  1389. tracks = tracks.concat( generateTracks( rawTracks ) );
  1390. } );
  1391. return new THREE.AnimationClip( rawClip.name, - 1, tracks );
  1392. }
  1393. function generateTracks( rawTracks ) {
  1394. var tracks = [];
  1395. if ( rawTracks.T !== undefined && Object.keys( rawTracks.T.curves ).length > 0 ) {
  1396. var positionTrack = generateVectorTrack( rawTracks.modelName, rawTracks.T.curves, rawTracks.initialPosition, 'position' );
  1397. if ( positionTrack !== undefined ) tracks.push( positionTrack );
  1398. }
  1399. if ( rawTracks.R !== undefined && Object.keys( rawTracks.R.curves ).length > 0 ) {
  1400. var rotationTrack = generateRotationTrack( rawTracks.modelName, rawTracks.R.curves, rawTracks.initialRotation, rawTracks.preRotations );
  1401. if ( rotationTrack !== undefined ) tracks.push( rotationTrack );
  1402. }
  1403. if ( rawTracks.S !== undefined && Object.keys( rawTracks.S.curves ).length > 0 ) {
  1404. var scaleTrack = generateVectorTrack( rawTracks.modelName, rawTracks.S.curves, rawTracks.initialScale, 'scale' );
  1405. if ( scaleTrack !== undefined ) tracks.push( scaleTrack );
  1406. }
  1407. return tracks;
  1408. }
  1409. function generateVectorTrack( modelName, curves, initialValue, type ) {
  1410. var times = getTimesForAllAxes( curves );
  1411. var values = getKeyframeTrackValues( times, curves, initialValue );
  1412. return new THREE.VectorKeyframeTrack( modelName + '.' + type, times, values );
  1413. }
  1414. function generateRotationTrack( modelName, curves, initialValue, preRotations ) {
  1415. if ( curves.x !== undefined ) curves.x.values = curves.x.values.map( THREE.Math.degToRad );
  1416. if ( curves.y !== undefined ) curves.y.values = curves.y.values.map( THREE.Math.degToRad );
  1417. if ( curves.z !== undefined ) curves.z.values = curves.z.values.map( THREE.Math.degToRad );
  1418. var times = getTimesForAllAxes( curves );
  1419. var values = getKeyframeTrackValues( times, curves, initialValue );
  1420. if ( preRotations !== undefined ) {
  1421. preRotations = preRotations.map( THREE.Math.degToRad );
  1422. preRotations.push( 'ZYX' );
  1423. preRotations = new THREE.Euler().fromArray( preRotations );
  1424. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1425. }
  1426. var quaternion = new THREE.Quaternion();
  1427. var euler = new THREE.Euler();
  1428. var quaternionValues = [];
  1429. for ( var i = 0; i < values.length; i += 3 ) {
  1430. euler.set( values[ i ], values[ i + 1 ], values[ i + 2 ], 'ZYX' );
  1431. quaternion.setFromEuler( euler );
  1432. if ( preRotations !== undefined )quaternion.premultiply( preRotations );
  1433. quaternion.toArray( quaternionValues, ( i / 3 ) * 4 );
  1434. }
  1435. return new THREE.QuaternionKeyframeTrack( modelName + '.quaternion', times, quaternionValues );
  1436. }
  1437. function getKeyframeTrackValues( times, curves, initialValue ) {
  1438. var prevValue = initialValue;
  1439. var values = [];
  1440. var xIndex = - 1;
  1441. var yIndex = - 1;
  1442. var zIndex = - 1;
  1443. times.forEach( function ( time ) {
  1444. if ( curves.x ) xIndex = curves.x.times.indexOf( time );
  1445. if ( curves.y ) yIndex = curves.y.times.indexOf( time );
  1446. if ( curves.z ) zIndex = curves.z.times.indexOf( time );
  1447. // if there is an x value defined for this frame, use that
  1448. if ( xIndex !== - 1 ) {
  1449. var xValue = curves.x.values[ xIndex ];
  1450. values.push( xValue );
  1451. prevValue[ 0 ] = xValue;
  1452. } else {
  1453. // otherwise use the x value from the previous frame
  1454. values.push( prevValue[ 0 ] );
  1455. }
  1456. if ( yIndex !== - 1 ) {
  1457. var yValue = curves.y.values[ yIndex ];
  1458. values.push( yValue );
  1459. prevValue[ 1 ] = yValue;
  1460. } else {
  1461. values.push( prevValue[ 1 ] );
  1462. }
  1463. if ( zIndex !== - 1 ) {
  1464. var zValue = curves.z.values[ zIndex ];
  1465. values.push( zValue );
  1466. prevValue[ 2 ] = zValue;
  1467. } else {
  1468. values.push( prevValue[ 2 ] );
  1469. }
  1470. } );
  1471. return values;
  1472. }
  1473. // For all animated objects, times are defined separately for each axis
  1474. // Here we'll combine the times into one sorted array without duplicates
  1475. function getTimesForAllAxes( curves ) {
  1476. var times = [];
  1477. // first join together the times for each axis, if defined
  1478. if ( curves.x !== undefined ) times = times.concat( curves.x.times );
  1479. if ( curves.y !== undefined ) times = times.concat( curves.y.times );
  1480. if ( curves.z !== undefined ) times = times.concat( curves.z.times );
  1481. // then sort them and remove duplicates
  1482. times = times.sort( function ( a, b ) {
  1483. return a - b;
  1484. } ).filter( function ( elem, index, array ) {
  1485. return array.indexOf( elem ) == index;
  1486. } );
  1487. return times;
  1488. }
  1489. // parse an FBX file in ASCII format
  1490. function TextParser() {}
  1491. Object.assign( TextParser.prototype, {
  1492. getPrevNode: function () {
  1493. return this.nodeStack[ this.currentIndent - 2 ];
  1494. },
  1495. getCurrentNode: function () {
  1496. return this.nodeStack[ this.currentIndent - 1 ];
  1497. },
  1498. getCurrentProp: function () {
  1499. return this.currentProp;
  1500. },
  1501. pushStack: function ( node ) {
  1502. this.nodeStack.push( node );
  1503. this.currentIndent += 1;
  1504. },
  1505. popStack: function () {
  1506. this.nodeStack.pop();
  1507. this.currentIndent -= 1;
  1508. },
  1509. setCurrentProp: function ( val, name ) {
  1510. this.currentProp = val;
  1511. this.currentPropName = name;
  1512. },
  1513. parse: function ( text ) {
  1514. this.currentIndent = 0;
  1515. this.allNodes = new FBXTree();
  1516. this.nodeStack = [];
  1517. this.currentProp = [];
  1518. this.currentPropName = '';
  1519. var self = this;
  1520. var split = text.split( '\n' );
  1521. split.forEach( function ( line, i ) {
  1522. var matchComment = line.match( /^[\s\t]*;/ );
  1523. var matchEmpty = line.match( /^[\s\t]*$/ );
  1524. if ( matchComment || matchEmpty ) return;
  1525. var matchBeginning = line.match( '^\\t{' + self.currentIndent + '}(\\w+):(.*){', '' );
  1526. var matchProperty = line.match( '^\\t{' + ( self.currentIndent ) + '}(\\w+):[\\s\\t\\r\\n](.*)' );
  1527. var matchEnd = line.match( '^\\t{' + ( self.currentIndent - 1 ) + '}}' );
  1528. if ( matchBeginning ) {
  1529. self.parseNodeBegin( line, matchBeginning );
  1530. } else if ( matchProperty ) {
  1531. self.parseNodeProperty( line, matchProperty, split[ ++ i ] );
  1532. } else if ( matchEnd ) {
  1533. self.popStack();
  1534. } else if ( line.match( /^[^\s\t}]/ ) ) {
  1535. // large arrays are split over multiple lines terminated with a ',' character
  1536. // if this is encountered the line needs to be joined to the previous line
  1537. self.parseNodePropertyContinued( line );
  1538. }
  1539. } );
  1540. return this.allNodes;
  1541. },
  1542. parseNodeBegin: function ( line, property ) {
  1543. var nodeName = property[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  1544. var nodeAttrs = property[ 2 ].split( ',' ).map( function ( attr ) {
  1545. return attr.trim().replace( /^"/, '' ).replace( /"$/, '' );
  1546. } );
  1547. var node = { name: nodeName };
  1548. var attrs = this.parseNodeAttr( nodeAttrs );
  1549. var currentNode = this.getCurrentNode();
  1550. // a top node
  1551. if ( this.currentIndent === 0 ) {
  1552. this.allNodes.add( nodeName, node );
  1553. } else { // a subnode
  1554. // if the subnode already exists, append it
  1555. if ( nodeName in currentNode ) {
  1556. // special case Pose needs PoseNodes as an array
  1557. if ( nodeName === 'PoseNode' ) {
  1558. currentNode.PoseNode.push( node );
  1559. } else if ( currentNode[ nodeName ].id !== undefined ) {
  1560. currentNode[ nodeName ] = {};
  1561. currentNode[ nodeName ][ currentNode[ nodeName ].id ] = currentNode[ nodeName ];
  1562. }
  1563. if ( attrs.id !== '' ) currentNode[ nodeName ][ attrs.id ] = node;
  1564. } else if ( typeof attrs.id === 'number' ) {
  1565. currentNode[ nodeName ] = {};
  1566. currentNode[ nodeName ][ attrs.id ] = node;
  1567. } else if ( nodeName !== 'Properties70' ) {
  1568. if ( nodeName === 'PoseNode' ) currentNode[ nodeName ] = [ node ];
  1569. else currentNode[ nodeName ] = node;
  1570. }
  1571. }
  1572. if ( typeof attrs.id === 'number' ) node.id = attrs.id;
  1573. if ( attrs.name !== '' ) node.attrName = attrs.name;
  1574. if ( attrs.type !== '' ) node.attrType = attrs.type;
  1575. this.pushStack( node );
  1576. },
  1577. parseNodeAttr: function ( attrs ) {
  1578. var id = attrs[ 0 ];
  1579. if ( attrs[ 0 ] !== '' ) {
  1580. id = parseInt( attrs[ 0 ] );
  1581. if ( isNaN( id ) ) {
  1582. id = attrs[ 0 ];
  1583. }
  1584. }
  1585. var name = '', type = '';
  1586. if ( attrs.length > 1 ) {
  1587. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  1588. type = attrs[ 2 ];
  1589. }
  1590. return { id: id, name: name, type: type };
  1591. },
  1592. parseNodeProperty: function ( line, property, contentLine ) {
  1593. var propName = property[ 1 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  1594. var propValue = property[ 2 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  1595. // for special case: base64 image data follows "Content: ," line
  1596. // Content: ,
  1597. // "/9j/4RDaRXhpZgAATU0A..."
  1598. if ( propName === 'Content' && propValue === ',' ) {
  1599. propValue = contentLine.replace( /"/g, '' ).replace( /,$/, '' ).trim();
  1600. }
  1601. var currentNode = this.getCurrentNode();
  1602. var parentName = currentNode.name;
  1603. if ( parentName === 'Properties70' ) {
  1604. this.parseNodeSpecialProperty( line, propName, propValue );
  1605. return;
  1606. }
  1607. // Connections
  1608. if ( propName === 'C' ) {
  1609. var connProps = propValue.split( ',' ).slice( 1 );
  1610. var from = parseInt( connProps[ 0 ] );
  1611. var to = parseInt( connProps[ 1 ] );
  1612. var rest = propValue.split( ',' ).slice( 3 );
  1613. rest = rest.map( function ( elem ) {
  1614. return elem.trim().replace( /^"/, '' );
  1615. } );
  1616. propName = 'connections';
  1617. propValue = [ from, to ];
  1618. append( propValue, rest );
  1619. if ( currentNode[ propName ] === undefined ) {
  1620. currentNode[ propName ] = [];
  1621. }
  1622. }
  1623. // Node
  1624. if ( propName === 'Node' ) currentNode.id = propValue;
  1625. // connections
  1626. if ( propName in currentNode && Array.isArray( currentNode[ propName ] ) ) {
  1627. currentNode[ propName ].push( propValue );
  1628. } else {
  1629. if ( propName !== 'a' ) currentNode[ propName ] = propValue;
  1630. else currentNode.a = propValue;
  1631. }
  1632. this.setCurrentProp( currentNode, propName );
  1633. // convert string to array, unless it ends in ',' in which case more will be added to it
  1634. if ( propName === 'a' && propValue.slice( - 1 ) !== ',' ) {
  1635. currentNode.a = parseNumberArray( propValue );
  1636. }
  1637. },
  1638. parseNodePropertyContinued: function ( line ) {
  1639. var currentNode = this.getCurrentNode();
  1640. currentNode.a += line;
  1641. // if the line doesn't end in ',' we have reached the end of the property value
  1642. // so convert the string to an array
  1643. if ( line.slice( - 1 ) !== ',' ) {
  1644. currentNode.a = parseNumberArray( currentNode.a );
  1645. }
  1646. },
  1647. // parse "Property70"
  1648. parseNodeSpecialProperty: function ( line, propName, propValue ) {
  1649. // split this
  1650. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  1651. // into array like below
  1652. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  1653. var props = propValue.split( '",' ).map( function ( prop ) {
  1654. return prop.trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  1655. } );
  1656. var innerPropName = props[ 0 ];
  1657. var innerPropType1 = props[ 1 ];
  1658. var innerPropType2 = props[ 2 ];
  1659. var innerPropFlag = props[ 3 ];
  1660. var innerPropValue = props[ 4 ];
  1661. // cast values where needed, otherwise leave as strings
  1662. switch ( innerPropType1 ) {
  1663. case 'int':
  1664. case 'enum':
  1665. case 'bool':
  1666. case 'ULongLong':
  1667. case 'double':
  1668. case 'Number':
  1669. case 'FieldOfView':
  1670. innerPropValue = parseFloat( innerPropValue );
  1671. break;
  1672. case 'Color':
  1673. case 'ColorRGB':
  1674. case 'Vector3D':
  1675. case 'Lcl_Translation':
  1676. case 'Lcl_Rotation':
  1677. case 'Lcl_Scaling':
  1678. innerPropValue = parseNumberArray( innerPropValue );
  1679. break;
  1680. }
  1681. // CAUTION: these props must append to parent's parent
  1682. this.getPrevNode()[ innerPropName ] = {
  1683. 'type': innerPropType1,
  1684. 'type2': innerPropType2,
  1685. 'flag': innerPropFlag,
  1686. 'value': innerPropValue
  1687. };
  1688. this.setCurrentProp( this.getPrevNode(), innerPropName );
  1689. },
  1690. } );
  1691. // Parse an FBX file in Binary format
  1692. function BinaryParser() {}
  1693. Object.assign( BinaryParser.prototype, {
  1694. parse: function ( buffer ) {
  1695. var reader = new BinaryReader( buffer );
  1696. reader.skip( 23 ); // skip magic 23 bytes
  1697. var version = reader.getUint32();
  1698. console.log( 'THREE.FBXLoader: FBX binary version: ' + version );
  1699. var allNodes = new FBXTree();
  1700. while ( ! this.endOfContent( reader ) ) {
  1701. var node = this.parseNode( reader, version );
  1702. if ( node !== null ) allNodes.add( node.name, node );
  1703. }
  1704. return allNodes;
  1705. },
  1706. // Check if reader has reached the end of content.
  1707. endOfContent: function ( reader ) {
  1708. // footer size: 160bytes + 16-byte alignment padding
  1709. // - 16bytes: magic
  1710. // - padding til 16-byte alignment (at least 1byte?)
  1711. // (seems like some exporters embed fixed 15 or 16bytes?)
  1712. // - 4bytes: magic
  1713. // - 4bytes: version
  1714. // - 120bytes: zero
  1715. // - 16bytes: magic
  1716. if ( reader.size() % 16 === 0 ) {
  1717. return ( ( reader.getOffset() + 160 + 16 ) & ~ 0xf ) >= reader.size();
  1718. } else {
  1719. return reader.getOffset() + 160 + 16 >= reader.size();
  1720. }
  1721. },
  1722. // recursively parse nodes until the end of the file is reached
  1723. parseNode: function ( reader, version ) {
  1724. var node = {};
  1725. // The first three data sizes depends on version.
  1726. var endOffset = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  1727. var numProperties = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  1728. // note: do not remove this even if you get a linter warning as it moves the buffer forward
  1729. var propertyListLen = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  1730. var nameLen = reader.getUint8();
  1731. var name = reader.getString( nameLen );
  1732. // Regards this node as NULL-record if endOffset is zero
  1733. if ( endOffset === 0 ) return null;
  1734. var propertyList = [];
  1735. for ( var i = 0; i < numProperties; i ++ ) {
  1736. propertyList.push( this.parseProperty( reader ) );
  1737. }
  1738. // Regards the first three elements in propertyList as id, attrName, and attrType
  1739. var id = propertyList.length > 0 ? propertyList[ 0 ] : '';
  1740. var attrName = propertyList.length > 1 ? propertyList[ 1 ] : '';
  1741. var attrType = propertyList.length > 2 ? propertyList[ 2 ] : '';
  1742. // check if this node represents just a single property
  1743. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  1744. node.singleProperty = ( numProperties === 1 && reader.getOffset() === endOffset ) ? true : false;
  1745. while ( endOffset > reader.getOffset() ) {
  1746. var subNode = this.parseNode( reader, version );
  1747. if ( subNode !== null ) this.parseSubNode( name, node, subNode );
  1748. }
  1749. node.propertyList = propertyList; // raw property list used by parent
  1750. if ( typeof id === 'number' ) node.id = id;
  1751. if ( attrName !== '' ) node.attrName = attrName;
  1752. if ( attrType !== '' ) node.attrType = attrType;
  1753. if ( name !== '' ) node.name = name;
  1754. return node;
  1755. },
  1756. parseSubNode: function ( name, node, subNode ) {
  1757. // special case: child node is single property
  1758. if ( subNode.singleProperty === true ) {
  1759. var value = subNode.propertyList[ 0 ];
  1760. if ( Array.isArray( value ) ) {
  1761. node[ subNode.name ] = subNode;
  1762. subNode.a = value;
  1763. } else {
  1764. node[ subNode.name ] = value;
  1765. }
  1766. } else if ( name === 'Connections' && subNode.name === 'C' ) {
  1767. var array = [];
  1768. subNode.propertyList.forEach( function ( property, i ) {
  1769. // first Connection is FBX type (OO, OP, etc.). We'll discard these
  1770. if ( i !== 0 ) array.push( property );
  1771. } );
  1772. if ( node.connections === undefined ) {
  1773. node.connections = [];
  1774. }
  1775. node.connections.push( array );
  1776. } else if ( subNode.name === 'Properties70' ) {
  1777. var keys = Object.keys( subNode );
  1778. keys.forEach( function ( key ) {
  1779. node[ key ] = subNode[ key ];
  1780. } );
  1781. } else if ( name === 'Properties70' && subNode.name === 'P' ) {
  1782. var innerPropName = subNode.propertyList[ 0 ];
  1783. var innerPropType1 = subNode.propertyList[ 1 ];
  1784. var innerPropType2 = subNode.propertyList[ 2 ];
  1785. var innerPropFlag = subNode.propertyList[ 3 ];
  1786. var innerPropValue;
  1787. if ( innerPropName.indexOf( 'Lcl ' ) === 0 ) innerPropName = innerPropName.replace( 'Lcl ', 'Lcl_' );
  1788. if ( innerPropType1.indexOf( 'Lcl ' ) === 0 ) innerPropType1 = innerPropType1.replace( 'Lcl ', 'Lcl_' );
  1789. if ( innerPropType1 === 'Color' || innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' || innerPropType1 === 'Vector3D' || innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  1790. innerPropValue = [
  1791. subNode.propertyList[ 4 ],
  1792. subNode.propertyList[ 5 ],
  1793. subNode.propertyList[ 6 ]
  1794. ];
  1795. } else {
  1796. innerPropValue = subNode.propertyList[ 4 ];
  1797. }
  1798. // this will be copied to parent, see above
  1799. node[ innerPropName ] = {
  1800. 'type': innerPropType1,
  1801. 'type2': innerPropType2,
  1802. 'flag': innerPropFlag,
  1803. 'value': innerPropValue
  1804. };
  1805. } else if ( node[ subNode.name ] === undefined ) {
  1806. if ( typeof subNode.id === 'number' ) {
  1807. node[ subNode.name ] = {};
  1808. node[ subNode.name ][ subNode.id ] = subNode;
  1809. } else {
  1810. node[ subNode.name ] = subNode;
  1811. }
  1812. } else {
  1813. if ( subNode.name === 'PoseNode' ) {
  1814. if ( ! Array.isArray( node[ subNode.name ] ) ) {
  1815. node[ subNode.name ] = [ node[ subNode.name ] ];
  1816. }
  1817. node[ subNode.name ].push( subNode );
  1818. } else if ( node[ subNode.name ][ subNode.id ] === undefined ) {
  1819. node[ subNode.name ][ subNode.id ] = subNode;
  1820. }
  1821. }
  1822. },
  1823. parseProperty: function ( reader ) {
  1824. var type = reader.getString( 1 );
  1825. switch ( type ) {
  1826. case 'C':
  1827. return reader.getBoolean();
  1828. case 'D':
  1829. return reader.getFloat64();
  1830. case 'F':
  1831. return reader.getFloat32();
  1832. case 'I':
  1833. return reader.getInt32();
  1834. case 'L':
  1835. return reader.getInt64();
  1836. case 'R':
  1837. var length = reader.getUint32();
  1838. return reader.getArrayBuffer( length );
  1839. case 'S':
  1840. var length = reader.getUint32();
  1841. return reader.getString( length );
  1842. case 'Y':
  1843. return reader.getInt16();
  1844. case 'b':
  1845. case 'c':
  1846. case 'd':
  1847. case 'f':
  1848. case 'i':
  1849. case 'l':
  1850. var arrayLength = reader.getUint32();
  1851. var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  1852. var compressedLength = reader.getUint32();
  1853. if ( encoding === 0 ) {
  1854. switch ( type ) {
  1855. case 'b':
  1856. case 'c':
  1857. return reader.getBooleanArray( arrayLength );
  1858. case 'd':
  1859. return reader.getFloat64Array( arrayLength );
  1860. case 'f':
  1861. return reader.getFloat32Array( arrayLength );
  1862. case 'i':
  1863. return reader.getInt32Array( arrayLength );
  1864. case 'l':
  1865. return reader.getInt64Array( arrayLength );
  1866. }
  1867. }
  1868. if ( window.Zlib === undefined ) {
  1869. console.error( 'THREE.FBXLoader: External library Inflate.min.js required, obtain or import from https://github.com/imaya/zlib.js' );
  1870. }
  1871. var inflate = new Zlib.Inflate( new Uint8Array( reader.getArrayBuffer( compressedLength ) ) ); // eslint-disable-line no-undef
  1872. var reader2 = new BinaryReader( inflate.decompress().buffer );
  1873. switch ( type ) {
  1874. case 'b':
  1875. case 'c':
  1876. return reader2.getBooleanArray( arrayLength );
  1877. case 'd':
  1878. return reader2.getFloat64Array( arrayLength );
  1879. case 'f':
  1880. return reader2.getFloat32Array( arrayLength );
  1881. case 'i':
  1882. return reader2.getInt32Array( arrayLength );
  1883. case 'l':
  1884. return reader2.getInt64Array( arrayLength );
  1885. }
  1886. default:
  1887. throw new Error( 'THREE.FBXLoader: Unknown property type ' + type );
  1888. }
  1889. }
  1890. } );
  1891. function BinaryReader( buffer, littleEndian ) {
  1892. this.dv = new DataView( buffer );
  1893. this.offset = 0;
  1894. this.littleEndian = ( littleEndian !== undefined ) ? littleEndian : true;
  1895. }
  1896. Object.assign( BinaryReader.prototype, {
  1897. getOffset: function () {
  1898. return this.offset;
  1899. },
  1900. size: function () {
  1901. return this.dv.buffer.byteLength;
  1902. },
  1903. skip: function ( length ) {
  1904. this.offset += length;
  1905. },
  1906. // seems like true/false representation depends on exporter.
  1907. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  1908. // then sees LSB.
  1909. getBoolean: function () {
  1910. return ( this.getUint8() & 1 ) === 1;
  1911. },
  1912. getBooleanArray: function ( size ) {
  1913. var a = [];
  1914. for ( var i = 0; i < size; i ++ ) {
  1915. a.push( this.getBoolean() );
  1916. }
  1917. return a;
  1918. },
  1919. getUint8: function () {
  1920. var value = this.dv.getUint8( this.offset );
  1921. this.offset += 1;
  1922. return value;
  1923. },
  1924. getInt16: function () {
  1925. var value = this.dv.getInt16( this.offset, this.littleEndian );
  1926. this.offset += 2;
  1927. return value;
  1928. },
  1929. getInt32: function () {
  1930. var value = this.dv.getInt32( this.offset, this.littleEndian );
  1931. this.offset += 4;
  1932. return value;
  1933. },
  1934. getInt32Array: function ( size ) {
  1935. var a = [];
  1936. for ( var i = 0; i < size; i ++ ) {
  1937. a.push( this.getInt32() );
  1938. }
  1939. return a;
  1940. },
  1941. getUint32: function () {
  1942. var value = this.dv.getUint32( this.offset, this.littleEndian );
  1943. this.offset += 4;
  1944. return value;
  1945. },
  1946. // JavaScript doesn't support 64-bit integer so calculate this here
  1947. // 1 << 32 will return 1 so using multiply operation instead here.
  1948. // There's a possibility that this method returns wrong value if the value
  1949. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  1950. // TODO: safely handle 64-bit integer
  1951. getInt64: function () {
  1952. var low, high;
  1953. if ( this.littleEndian ) {
  1954. low = this.getUint32();
  1955. high = this.getUint32();
  1956. } else {
  1957. high = this.getUint32();
  1958. low = this.getUint32();
  1959. }
  1960. // calculate negative value
  1961. if ( high & 0x80000000 ) {
  1962. high = ~ high & 0xFFFFFFFF;
  1963. low = ~ low & 0xFFFFFFFF;
  1964. if ( low === 0xFFFFFFFF ) high = ( high + 1 ) & 0xFFFFFFFF;
  1965. low = ( low + 1 ) & 0xFFFFFFFF;
  1966. return - ( high * 0x100000000 + low );
  1967. }
  1968. return high * 0x100000000 + low;
  1969. },
  1970. getInt64Array: function ( size ) {
  1971. var a = [];
  1972. for ( var i = 0; i < size; i ++ ) {
  1973. a.push( this.getInt64() );
  1974. }
  1975. return a;
  1976. },
  1977. // Note: see getInt64() comment
  1978. getUint64: function () {
  1979. var low, high;
  1980. if ( this.littleEndian ) {
  1981. low = this.getUint32();
  1982. high = this.getUint32();
  1983. } else {
  1984. high = this.getUint32();
  1985. low = this.getUint32();
  1986. }
  1987. return high * 0x100000000 + low;
  1988. },
  1989. getFloat32: function () {
  1990. var value = this.dv.getFloat32( this.offset, this.littleEndian );
  1991. this.offset += 4;
  1992. return value;
  1993. },
  1994. getFloat32Array: function ( size ) {
  1995. var a = [];
  1996. for ( var i = 0; i < size; i ++ ) {
  1997. a.push( this.getFloat32() );
  1998. }
  1999. return a;
  2000. },
  2001. getFloat64: function () {
  2002. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  2003. this.offset += 8;
  2004. return value;
  2005. },
  2006. getFloat64Array: function ( size ) {
  2007. var a = [];
  2008. for ( var i = 0; i < size; i ++ ) {
  2009. a.push( this.getFloat64() );
  2010. }
  2011. return a;
  2012. },
  2013. getArrayBuffer: function ( size ) {
  2014. var value = this.dv.buffer.slice( this.offset, this.offset + size );
  2015. this.offset += size;
  2016. return value;
  2017. },
  2018. getString: function ( size ) {
  2019. var a = new Uint8Array( size );
  2020. for ( var i = 0; i < size; i ++ ) {
  2021. a[ i ] = this.getUint8();
  2022. }
  2023. var nullByte = a.indexOf( 0 );
  2024. if ( nullByte >= 0 ) a = a.slice( 0, nullByte );
  2025. return THREE.LoaderUtils.decodeText( a );
  2026. }
  2027. } );
  2028. // FBXTree holds a representation of the FBX data, returned by the TextParser ( FBX ASCII format)
  2029. // and BinaryParser( FBX Binary format)
  2030. function FBXTree() {}
  2031. Object.assign( FBXTree.prototype, {
  2032. add: function ( key, val ) {
  2033. this[ key ] = val;
  2034. },
  2035. } );
  2036. function isFbxFormatBinary( buffer ) {
  2037. var CORRECT = 'Kaydara FBX Binary \0';
  2038. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString( buffer, 0, CORRECT.length );
  2039. }
  2040. function isFbxFormatASCII( text ) {
  2041. var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  2042. var cursor = 0;
  2043. function read( offset ) {
  2044. var result = text[ offset - 1 ];
  2045. text = text.slice( cursor + offset );
  2046. cursor ++;
  2047. return result;
  2048. }
  2049. for ( var i = 0; i < CORRECT.length; ++ i ) {
  2050. var num = read( 1 );
  2051. if ( num === CORRECT[ i ] ) {
  2052. return false;
  2053. }
  2054. }
  2055. return true;
  2056. }
  2057. function getFbxVersion( text ) {
  2058. var versionRegExp = /FBXVersion: (\d+)/;
  2059. var match = text.match( versionRegExp );
  2060. if ( match ) {
  2061. var version = parseInt( match[ 1 ] );
  2062. return version;
  2063. }
  2064. throw new Error( 'THREE.FBXLoader: Cannot find the version number for the file given.' );
  2065. }
  2066. // Converts FBX ticks into real time seconds.
  2067. function convertFBXTimeToSeconds( time ) {
  2068. return time / 46186158000;
  2069. }
  2070. // Parses comma separated list of numbers and returns them an array.
  2071. // Used internally by the TextParser
  2072. function parseNumberArray( value ) {
  2073. var array = value.split( ',' ).map( function ( val ) {
  2074. return parseFloat( val );
  2075. } );
  2076. return array;
  2077. }
  2078. function convertArrayBufferToString( buffer, from, to ) {
  2079. if ( from === undefined ) from = 0;
  2080. if ( to === undefined ) to = buffer.byteLength;
  2081. return THREE.LoaderUtils.decodeText( new Uint8Array( buffer, from, to ) );
  2082. }
  2083. function append( a, b ) {
  2084. for ( var i = 0, j = a.length, l = b.length; i < l; i ++, j ++ ) {
  2085. a[ j ] = b[ i ];
  2086. }
  2087. }
  2088. function slice( a, b, from, to ) {
  2089. for ( var i = from, j = 0; i < to; i ++, j ++ ) {
  2090. a[ j ] = b[ i ];
  2091. }
  2092. return a;
  2093. }
  2094. } )();