GLTFLoader.js 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206
  1. /**
  2. * @author Rich Tibbett / https://github.com/richtr
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author Tony Parisi / http://www.tonyparisi.com/
  5. * @author Takahiro / https://github.com/takahirox
  6. * @author Don McCurdy / https://www.donmccurdy.com
  7. */
  8. THREE.GLTFLoader = ( function () {
  9. function GLTFLoader( manager ) {
  10. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11. this.dracoLoader = null;
  12. this.ddsLoader = null;
  13. }
  14. GLTFLoader.prototype = {
  15. constructor: GLTFLoader,
  16. crossOrigin: 'anonymous',
  17. load: function ( url, onLoad, onProgress, onError ) {
  18. var scope = this;
  19. var resourcePath;
  20. if ( this.resourcePath !== undefined ) {
  21. resourcePath = this.resourcePath;
  22. } else if ( this.path !== undefined ) {
  23. resourcePath = this.path;
  24. } else {
  25. resourcePath = THREE.LoaderUtils.extractUrlBase( url );
  26. }
  27. // Tells the LoadingManager to track an extra item, which resolves after
  28. // the model is fully loaded. This means the count of items loaded will
  29. // be incorrect, but ensures manager.onLoad() does not fire early.
  30. scope.manager.itemStart( url );
  31. var _onError = function ( e ) {
  32. if ( onError ) {
  33. onError( e );
  34. } else {
  35. console.error( e );
  36. }
  37. scope.manager.itemError( url );
  38. scope.manager.itemEnd( url );
  39. };
  40. var loader = new THREE.FileLoader( scope.manager );
  41. loader.setPath( this.path );
  42. loader.setResponseType( 'arraybuffer' );
  43. if ( scope.crossOrigin === 'use-credentials' ) {
  44. loader.setWithCredentials( true );
  45. }
  46. loader.load( url, function ( data ) {
  47. try {
  48. scope.parse( data, resourcePath, function ( gltf ) {
  49. onLoad( gltf );
  50. scope.manager.itemEnd( url );
  51. }, _onError );
  52. } catch ( e ) {
  53. _onError( e );
  54. }
  55. }, onProgress, _onError );
  56. },
  57. setCrossOrigin: function ( value ) {
  58. this.crossOrigin = value;
  59. return this;
  60. },
  61. setPath: function ( value ) {
  62. this.path = value;
  63. return this;
  64. },
  65. setResourcePath: function ( value ) {
  66. this.resourcePath = value;
  67. return this;
  68. },
  69. setDRACOLoader: function ( dracoLoader ) {
  70. this.dracoLoader = dracoLoader;
  71. return this;
  72. },
  73. setDDSLoader: function ( ddsLoader ) {
  74. this.ddsLoader = ddsLoader;
  75. return this;
  76. },
  77. parse: function ( data, path, onLoad, onError ) {
  78. var content;
  79. var extensions = {};
  80. if ( typeof data === 'string' ) {
  81. content = data;
  82. } else {
  83. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  84. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  85. try {
  86. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  87. } catch ( error ) {
  88. if ( onError ) onError( error );
  89. return;
  90. }
  91. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  92. } else {
  93. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  94. }
  95. }
  96. var json = JSON.parse( content );
  97. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  98. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.' ) );
  99. return;
  100. }
  101. if ( json.extensionsUsed ) {
  102. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  103. var extensionName = json.extensionsUsed[ i ];
  104. var extensionsRequired = json.extensionsRequired || [];
  105. switch ( extensionName ) {
  106. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  107. extensions[ extensionName ] = new GLTFLightsExtension( json );
  108. break;
  109. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  110. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  111. break;
  112. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  113. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  114. break;
  115. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  116. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  117. break;
  118. case EXTENSIONS.MSFT_TEXTURE_DDS:
  119. extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] = new GLTFTextureDDSExtension( this.ddsLoader );
  120. break;
  121. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  122. extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] = new GLTFTextureTransformExtension();
  123. break;
  124. default:
  125. if ( extensionsRequired.indexOf( extensionName ) >= 0 ) {
  126. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  127. }
  128. }
  129. }
  130. }
  131. var parser = new GLTFParser( json, extensions, {
  132. path: path || this.resourcePath || '',
  133. crossOrigin: this.crossOrigin,
  134. manager: this.manager
  135. } );
  136. parser.parse( onLoad, onError );
  137. }
  138. };
  139. /* GLTFREGISTRY */
  140. function GLTFRegistry() {
  141. var objects = {};
  142. return {
  143. get: function ( key ) {
  144. return objects[ key ];
  145. },
  146. add: function ( key, object ) {
  147. objects[ key ] = object;
  148. },
  149. remove: function ( key ) {
  150. delete objects[ key ];
  151. },
  152. removeAll: function () {
  153. objects = {};
  154. }
  155. };
  156. }
  157. /*********************************/
  158. /********** EXTENSIONS ***********/
  159. /*********************************/
  160. var EXTENSIONS = {
  161. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  162. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  163. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  164. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  165. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  166. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  167. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  168. };
  169. /**
  170. * DDS Texture Extension
  171. *
  172. * Specification:
  173. * https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  174. *
  175. */
  176. function GLTFTextureDDSExtension( ddsLoader ) {
  177. if ( ! ddsLoader ) {
  178. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  179. }
  180. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  181. this.ddsLoader = ddsLoader;
  182. }
  183. /**
  184. * Lights Extension
  185. *
  186. * Specification: PENDING
  187. */
  188. function GLTFLightsExtension( json ) {
  189. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  190. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ] ) || {};
  191. this.lightDefs = extension.lights || [];
  192. }
  193. GLTFLightsExtension.prototype.loadLight = function ( lightIndex ) {
  194. var lightDef = this.lightDefs[ lightIndex ];
  195. var lightNode;
  196. var color = new THREE.Color( 0xffffff );
  197. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  198. var range = lightDef.range !== undefined ? lightDef.range : 0;
  199. switch ( lightDef.type ) {
  200. case 'directional':
  201. lightNode = new THREE.DirectionalLight( color );
  202. lightNode.target.position.set( 0, 0, - 1 );
  203. lightNode.add( lightNode.target );
  204. break;
  205. case 'point':
  206. lightNode = new THREE.PointLight( color );
  207. lightNode.distance = range;
  208. break;
  209. case 'spot':
  210. lightNode = new THREE.SpotLight( color );
  211. lightNode.distance = range;
  212. // Handle spotlight properties.
  213. lightDef.spot = lightDef.spot || {};
  214. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  215. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  216. lightNode.angle = lightDef.spot.outerConeAngle;
  217. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  218. lightNode.target.position.set( 0, 0, - 1 );
  219. lightNode.add( lightNode.target );
  220. break;
  221. default:
  222. throw new Error( 'THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".' );
  223. }
  224. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  225. // here, because node-level parsing will only override position if explicitly specified.
  226. lightNode.position.set( 0, 0, 0 );
  227. lightNode.decay = 2;
  228. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  229. lightNode.name = lightDef.name || ( 'light_' + lightIndex );
  230. return Promise.resolve( lightNode );
  231. };
  232. /**
  233. * Unlit Materials Extension (pending)
  234. *
  235. * PR: https://github.com/KhronosGroup/glTF/pull/1163
  236. */
  237. function GLTFMaterialsUnlitExtension() {
  238. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  239. }
  240. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  241. return THREE.MeshBasicMaterial;
  242. };
  243. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  244. var pending = [];
  245. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  246. materialParams.opacity = 1.0;
  247. var metallicRoughness = materialDef.pbrMetallicRoughness;
  248. if ( metallicRoughness ) {
  249. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  250. var array = metallicRoughness.baseColorFactor;
  251. materialParams.color.fromArray( array );
  252. materialParams.opacity = array[ 3 ];
  253. }
  254. if ( metallicRoughness.baseColorTexture !== undefined ) {
  255. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  256. }
  257. }
  258. return Promise.all( pending );
  259. };
  260. /* BINARY EXTENSION */
  261. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  262. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  263. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  264. function GLTFBinaryExtension( data ) {
  265. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  266. this.content = null;
  267. this.body = null;
  268. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  269. this.header = {
  270. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  271. version: headerView.getUint32( 4, true ),
  272. length: headerView.getUint32( 8, true )
  273. };
  274. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  275. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  276. } else if ( this.header.version < 2.0 ) {
  277. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.' );
  278. }
  279. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  280. var chunkIndex = 0;
  281. while ( chunkIndex < chunkView.byteLength ) {
  282. var chunkLength = chunkView.getUint32( chunkIndex, true );
  283. chunkIndex += 4;
  284. var chunkType = chunkView.getUint32( chunkIndex, true );
  285. chunkIndex += 4;
  286. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  287. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  288. this.content = THREE.LoaderUtils.decodeText( contentArray );
  289. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  290. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  291. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  292. }
  293. // Clients must ignore chunks with unknown types.
  294. chunkIndex += chunkLength;
  295. }
  296. if ( this.content === null ) {
  297. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  298. }
  299. }
  300. /**
  301. * DRACO Mesh Compression Extension
  302. *
  303. * Specification: https://github.com/KhronosGroup/glTF/pull/874
  304. */
  305. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  306. if ( ! dracoLoader ) {
  307. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  308. }
  309. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  310. this.json = json;
  311. this.dracoLoader = dracoLoader;
  312. }
  313. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  314. var json = this.json;
  315. var dracoLoader = this.dracoLoader;
  316. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  317. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  318. var threeAttributeMap = {};
  319. var attributeNormalizedMap = {};
  320. var attributeTypeMap = {};
  321. for ( var attributeName in gltfAttributeMap ) {
  322. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  323. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  324. }
  325. for ( attributeName in primitive.attributes ) {
  326. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  327. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  328. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  329. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  330. attributeTypeMap[ threeAttributeName ] = componentType;
  331. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  332. }
  333. }
  334. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  335. return new Promise( function ( resolve ) {
  336. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  337. for ( var attributeName in geometry.attributes ) {
  338. var attribute = geometry.attributes[ attributeName ];
  339. var normalized = attributeNormalizedMap[ attributeName ];
  340. if ( normalized !== undefined ) attribute.normalized = normalized;
  341. }
  342. resolve( geometry );
  343. }, threeAttributeMap, attributeTypeMap );
  344. } );
  345. } );
  346. };
  347. /**
  348. * Texture Transform Extension
  349. *
  350. * Specification:
  351. */
  352. function GLTFTextureTransformExtension() {
  353. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  354. }
  355. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  356. texture = texture.clone();
  357. if ( transform.offset !== undefined ) {
  358. texture.offset.fromArray( transform.offset );
  359. }
  360. if ( transform.rotation !== undefined ) {
  361. texture.rotation = transform.rotation;
  362. }
  363. if ( transform.scale !== undefined ) {
  364. texture.repeat.fromArray( transform.scale );
  365. }
  366. if ( transform.texCoord !== undefined ) {
  367. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  368. }
  369. texture.needsUpdate = true;
  370. return texture;
  371. };
  372. /**
  373. * Specular-Glossiness Extension
  374. *
  375. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  376. */
  377. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  378. return {
  379. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  380. specularGlossinessParams: [
  381. 'color',
  382. 'map',
  383. 'lightMap',
  384. 'lightMapIntensity',
  385. 'aoMap',
  386. 'aoMapIntensity',
  387. 'emissive',
  388. 'emissiveIntensity',
  389. 'emissiveMap',
  390. 'bumpMap',
  391. 'bumpScale',
  392. 'normalMap',
  393. 'displacementMap',
  394. 'displacementScale',
  395. 'displacementBias',
  396. 'specularMap',
  397. 'specular',
  398. 'glossinessMap',
  399. 'glossiness',
  400. 'alphaMap',
  401. 'envMap',
  402. 'envMapIntensity',
  403. 'refractionRatio',
  404. ],
  405. getMaterialType: function () {
  406. return THREE.ShaderMaterial;
  407. },
  408. extendParams: function ( materialParams, materialDef, parser ) {
  409. var pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  410. var shader = THREE.ShaderLib[ 'standard' ];
  411. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  412. var specularMapParsFragmentChunk = [
  413. '#ifdef USE_SPECULARMAP',
  414. ' uniform sampler2D specularMap;',
  415. '#endif'
  416. ].join( '\n' );
  417. var glossinessMapParsFragmentChunk = [
  418. '#ifdef USE_GLOSSINESSMAP',
  419. ' uniform sampler2D glossinessMap;',
  420. '#endif'
  421. ].join( '\n' );
  422. var specularMapFragmentChunk = [
  423. 'vec3 specularFactor = specular;',
  424. '#ifdef USE_SPECULARMAP',
  425. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  426. ' texelSpecular = sRGBToLinear( texelSpecular );',
  427. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  428. ' specularFactor *= texelSpecular.rgb;',
  429. '#endif'
  430. ].join( '\n' );
  431. var glossinessMapFragmentChunk = [
  432. 'float glossinessFactor = glossiness;',
  433. '#ifdef USE_GLOSSINESSMAP',
  434. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  435. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  436. ' glossinessFactor *= texelGlossiness.a;',
  437. '#endif'
  438. ].join( '\n' );
  439. var lightPhysicalFragmentChunk = [
  440. 'PhysicalMaterial material;',
  441. 'material.diffuseColor = diffuseColor.rgb;',
  442. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  443. 'material.specularColor = specularFactor.rgb;',
  444. ].join( '\n' );
  445. var fragmentShader = shader.fragmentShader
  446. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  447. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  448. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  449. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  450. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  451. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  452. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  453. delete uniforms.roughness;
  454. delete uniforms.metalness;
  455. delete uniforms.roughnessMap;
  456. delete uniforms.metalnessMap;
  457. uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
  458. uniforms.glossiness = { value: 0.5 };
  459. uniforms.specularMap = { value: null };
  460. uniforms.glossinessMap = { value: null };
  461. materialParams.vertexShader = shader.vertexShader;
  462. materialParams.fragmentShader = fragmentShader;
  463. materialParams.uniforms = uniforms;
  464. materialParams.defines = { 'STANDARD': '' };
  465. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  466. materialParams.opacity = 1.0;
  467. var pending = [];
  468. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  469. var array = pbrSpecularGlossiness.diffuseFactor;
  470. materialParams.color.fromArray( array );
  471. materialParams.opacity = array[ 3 ];
  472. }
  473. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  474. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  475. }
  476. materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  477. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  478. materialParams.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  479. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  480. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  481. }
  482. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  483. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  484. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  485. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  486. }
  487. return Promise.all( pending );
  488. },
  489. createMaterial: function ( params ) {
  490. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  491. var material = new THREE.ShaderMaterial( {
  492. defines: params.defines,
  493. vertexShader: params.vertexShader,
  494. fragmentShader: params.fragmentShader,
  495. uniforms: params.uniforms,
  496. fog: true,
  497. lights: true,
  498. opacity: params.opacity,
  499. transparent: params.transparent
  500. } );
  501. material.isGLTFSpecularGlossinessMaterial = true;
  502. material.color = params.color;
  503. material.map = params.map === undefined ? null : params.map;
  504. material.lightMap = null;
  505. material.lightMapIntensity = 1.0;
  506. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  507. material.aoMapIntensity = 1.0;
  508. material.emissive = params.emissive;
  509. material.emissiveIntensity = 1.0;
  510. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  511. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  512. material.bumpScale = 1;
  513. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  514. if ( params.normalScale ) material.normalScale = params.normalScale;
  515. material.displacementMap = null;
  516. material.displacementScale = 1;
  517. material.displacementBias = 0;
  518. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  519. material.specular = params.specular;
  520. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  521. material.glossiness = params.glossiness;
  522. material.alphaMap = null;
  523. material.envMap = params.envMap === undefined ? null : params.envMap;
  524. material.envMapIntensity = 1.0;
  525. material.refractionRatio = 0.98;
  526. material.extensions.derivatives = true;
  527. return material;
  528. },
  529. /**
  530. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  531. * copy only properties it knows about or inherits, and misses many properties that would
  532. * normally be defined by MeshStandardMaterial.
  533. *
  534. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  535. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  536. * AND also updating `.onBeforeRender` on the parent mesh.
  537. *
  538. * @param {THREE.ShaderMaterial} source
  539. * @return {THREE.ShaderMaterial}
  540. */
  541. cloneMaterial: function ( source ) {
  542. var target = source.clone();
  543. target.isGLTFSpecularGlossinessMaterial = true;
  544. var params = this.specularGlossinessParams;
  545. for ( var i = 0, il = params.length; i < il; i ++ ) {
  546. var value = source[ params[ i ] ];
  547. target[ params[ i ] ] = ( value && value.isColor ) ? value.clone() : value;
  548. }
  549. return target;
  550. },
  551. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  552. refreshUniforms: function ( renderer, scene, camera, geometry, material ) {
  553. if ( material.isGLTFSpecularGlossinessMaterial !== true ) {
  554. return;
  555. }
  556. var uniforms = material.uniforms;
  557. var defines = material.defines;
  558. uniforms.opacity.value = material.opacity;
  559. uniforms.diffuse.value.copy( material.color );
  560. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  561. uniforms.map.value = material.map;
  562. uniforms.specularMap.value = material.specularMap;
  563. uniforms.alphaMap.value = material.alphaMap;
  564. uniforms.lightMap.value = material.lightMap;
  565. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  566. uniforms.aoMap.value = material.aoMap;
  567. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  568. // uv repeat and offset setting priorities
  569. // 1. color map
  570. // 2. specular map
  571. // 3. normal map
  572. // 4. bump map
  573. // 5. alpha map
  574. // 6. emissive map
  575. var uvScaleMap;
  576. if ( material.map ) {
  577. uvScaleMap = material.map;
  578. } else if ( material.specularMap ) {
  579. uvScaleMap = material.specularMap;
  580. } else if ( material.displacementMap ) {
  581. uvScaleMap = material.displacementMap;
  582. } else if ( material.normalMap ) {
  583. uvScaleMap = material.normalMap;
  584. } else if ( material.bumpMap ) {
  585. uvScaleMap = material.bumpMap;
  586. } else if ( material.glossinessMap ) {
  587. uvScaleMap = material.glossinessMap;
  588. } else if ( material.alphaMap ) {
  589. uvScaleMap = material.alphaMap;
  590. } else if ( material.emissiveMap ) {
  591. uvScaleMap = material.emissiveMap;
  592. }
  593. if ( uvScaleMap !== undefined ) {
  594. // backwards compatibility
  595. if ( uvScaleMap.isWebGLRenderTarget ) {
  596. uvScaleMap = uvScaleMap.texture;
  597. }
  598. if ( uvScaleMap.matrixAutoUpdate === true ) {
  599. uvScaleMap.updateMatrix();
  600. }
  601. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  602. }
  603. if ( material.envMap ) {
  604. uniforms.envMap.value = material.envMap;
  605. uniforms.envMapIntensity.value = material.envMapIntensity;
  606. // don't flip CubeTexture envMaps, flip everything else:
  607. // WebGLRenderTargetCube will be flipped for backwards compatibility
  608. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  609. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  610. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? - 1 : 1;
  611. uniforms.reflectivity.value = material.reflectivity;
  612. uniforms.refractionRatio.value = material.refractionRatio;
  613. uniforms.maxMipLevel.value = renderer.properties.get( material.envMap ).__maxMipLevel;
  614. }
  615. uniforms.specular.value.copy( material.specular );
  616. uniforms.glossiness.value = material.glossiness;
  617. uniforms.glossinessMap.value = material.glossinessMap;
  618. uniforms.emissiveMap.value = material.emissiveMap;
  619. uniforms.bumpMap.value = material.bumpMap;
  620. uniforms.normalMap.value = material.normalMap;
  621. uniforms.displacementMap.value = material.displacementMap;
  622. uniforms.displacementScale.value = material.displacementScale;
  623. uniforms.displacementBias.value = material.displacementBias;
  624. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  625. defines.USE_GLOSSINESSMAP = '';
  626. // set USE_ROUGHNESSMAP to enable vUv
  627. defines.USE_ROUGHNESSMAP = '';
  628. }
  629. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  630. delete defines.USE_GLOSSINESSMAP;
  631. delete defines.USE_ROUGHNESSMAP;
  632. }
  633. }
  634. };
  635. }
  636. /*********************************/
  637. /********** INTERPOLATION ********/
  638. /*********************************/
  639. // Spline Interpolation
  640. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  641. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  642. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  643. }
  644. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  645. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  646. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  647. // Copies a sample value to the result buffer. See description of glTF
  648. // CUBICSPLINE values layout in interpolate_() function below.
  649. var result = this.resultBuffer,
  650. values = this.sampleValues,
  651. valueSize = this.valueSize,
  652. offset = index * valueSize * 3 + valueSize;
  653. for ( var i = 0; i !== valueSize; i ++ ) {
  654. result[ i ] = values[ offset + i ];
  655. }
  656. return result;
  657. };
  658. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  659. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  660. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  661. var result = this.resultBuffer;
  662. var values = this.sampleValues;
  663. var stride = this.valueSize;
  664. var stride2 = stride * 2;
  665. var stride3 = stride * 3;
  666. var td = t1 - t0;
  667. var p = ( t - t0 ) / td;
  668. var pp = p * p;
  669. var ppp = pp * p;
  670. var offset1 = i1 * stride3;
  671. var offset0 = offset1 - stride3;
  672. var s2 = - 2 * ppp + 3 * pp;
  673. var s3 = ppp - pp;
  674. var s0 = 1 - s2;
  675. var s1 = s3 - pp + p;
  676. // Layout of keyframe output values for CUBICSPLINE animations:
  677. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  678. for ( var i = 0; i !== stride; i ++ ) {
  679. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  680. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  681. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  682. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  683. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  684. }
  685. return result;
  686. };
  687. /*********************************/
  688. /********** INTERNALS ************/
  689. /*********************************/
  690. /* CONSTANTS */
  691. var WEBGL_CONSTANTS = {
  692. FLOAT: 5126,
  693. //FLOAT_MAT2: 35674,
  694. FLOAT_MAT3: 35675,
  695. FLOAT_MAT4: 35676,
  696. FLOAT_VEC2: 35664,
  697. FLOAT_VEC3: 35665,
  698. FLOAT_VEC4: 35666,
  699. LINEAR: 9729,
  700. REPEAT: 10497,
  701. SAMPLER_2D: 35678,
  702. POINTS: 0,
  703. LINES: 1,
  704. LINE_LOOP: 2,
  705. LINE_STRIP: 3,
  706. TRIANGLES: 4,
  707. TRIANGLE_STRIP: 5,
  708. TRIANGLE_FAN: 6,
  709. UNSIGNED_BYTE: 5121,
  710. UNSIGNED_SHORT: 5123
  711. };
  712. var WEBGL_COMPONENT_TYPES = {
  713. 5120: Int8Array,
  714. 5121: Uint8Array,
  715. 5122: Int16Array,
  716. 5123: Uint16Array,
  717. 5125: Uint32Array,
  718. 5126: Float32Array
  719. };
  720. var WEBGL_FILTERS = {
  721. 9728: THREE.NearestFilter,
  722. 9729: THREE.LinearFilter,
  723. 9984: THREE.NearestMipmapNearestFilter,
  724. 9985: THREE.LinearMipmapNearestFilter,
  725. 9986: THREE.NearestMipmapLinearFilter,
  726. 9987: THREE.LinearMipmapLinearFilter
  727. };
  728. var WEBGL_WRAPPINGS = {
  729. 33071: THREE.ClampToEdgeWrapping,
  730. 33648: THREE.MirroredRepeatWrapping,
  731. 10497: THREE.RepeatWrapping
  732. };
  733. var WEBGL_TYPE_SIZES = {
  734. 'SCALAR': 1,
  735. 'VEC2': 2,
  736. 'VEC3': 3,
  737. 'VEC4': 4,
  738. 'MAT2': 4,
  739. 'MAT3': 9,
  740. 'MAT4': 16
  741. };
  742. var ATTRIBUTES = {
  743. POSITION: 'position',
  744. NORMAL: 'normal',
  745. TANGENT: 'tangent',
  746. TEXCOORD_0: 'uv',
  747. TEXCOORD_1: 'uv2',
  748. COLOR_0: 'color',
  749. WEIGHTS_0: 'skinWeight',
  750. JOINTS_0: 'skinIndex',
  751. };
  752. var PATH_PROPERTIES = {
  753. scale: 'scale',
  754. translation: 'position',
  755. rotation: 'quaternion',
  756. weights: 'morphTargetInfluences'
  757. };
  758. var INTERPOLATION = {
  759. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  760. // keyframe track will be initialized with a default interpolation type, then modified.
  761. LINEAR: THREE.InterpolateLinear,
  762. STEP: THREE.InterpolateDiscrete
  763. };
  764. var ALPHA_MODES = {
  765. OPAQUE: 'OPAQUE',
  766. MASK: 'MASK',
  767. BLEND: 'BLEND'
  768. };
  769. var MIME_TYPE_FORMATS = {
  770. 'image/png': THREE.RGBAFormat,
  771. 'image/jpeg': THREE.RGBFormat
  772. };
  773. /* UTILITY FUNCTIONS */
  774. function resolveURL( url, path ) {
  775. // Invalid URL
  776. if ( typeof url !== 'string' || url === '' ) return '';
  777. // Absolute URL http://,https://,//
  778. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  779. // Data URI
  780. if ( /^data:.*,.*$/i.test( url ) ) return url;
  781. // Blob URL
  782. if ( /^blob:.*$/i.test( url ) ) return url;
  783. // Relative URL
  784. return path + url;
  785. }
  786. var defaultMaterial;
  787. /**
  788. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  789. */
  790. function createDefaultMaterial() {
  791. defaultMaterial = defaultMaterial || new THREE.MeshStandardMaterial( {
  792. color: 0xFFFFFF,
  793. emissive: 0x000000,
  794. metalness: 1,
  795. roughness: 1,
  796. transparent: false,
  797. depthTest: true,
  798. side: THREE.FrontSide
  799. } );
  800. return defaultMaterial;
  801. }
  802. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  803. // Add unknown glTF extensions to an object's userData.
  804. for ( var name in objectDef.extensions ) {
  805. if ( knownExtensions[ name ] === undefined ) {
  806. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  807. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  808. }
  809. }
  810. }
  811. /**
  812. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  813. * @param {GLTF.definition} gltfDef
  814. */
  815. function assignExtrasToUserData( object, gltfDef ) {
  816. if ( gltfDef.extras !== undefined ) {
  817. if ( typeof gltfDef.extras === 'object' ) {
  818. Object.assign( object.userData, gltfDef.extras );
  819. } else {
  820. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  821. }
  822. }
  823. }
  824. /**
  825. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  826. *
  827. * @param {THREE.BufferGeometry} geometry
  828. * @param {Array<GLTF.Target>} targets
  829. * @param {GLTFParser} parser
  830. * @return {Promise<THREE.BufferGeometry>}
  831. */
  832. function addMorphTargets( geometry, targets, parser ) {
  833. var hasMorphPosition = false;
  834. var hasMorphNormal = false;
  835. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  836. var target = targets[ i ];
  837. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  838. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  839. if ( hasMorphPosition && hasMorphNormal ) break;
  840. }
  841. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  842. var pendingPositionAccessors = [];
  843. var pendingNormalAccessors = [];
  844. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  845. var target = targets[ i ];
  846. if ( hasMorphPosition ) {
  847. var pendingAccessor = target.POSITION !== undefined
  848. ? parser.getDependency( 'accessor', target.POSITION )
  849. : geometry.attributes.position;
  850. pendingPositionAccessors.push( pendingAccessor );
  851. }
  852. if ( hasMorphNormal ) {
  853. var pendingAccessor = target.NORMAL !== undefined
  854. ? parser.getDependency( 'accessor', target.NORMAL )
  855. : geometry.attributes.normal;
  856. pendingNormalAccessors.push( pendingAccessor );
  857. }
  858. }
  859. return Promise.all( [
  860. Promise.all( pendingPositionAccessors ),
  861. Promise.all( pendingNormalAccessors )
  862. ] ).then( function ( accessors ) {
  863. var morphPositions = accessors[ 0 ];
  864. var morphNormals = accessors[ 1 ];
  865. // Clone morph target accessors before modifying them.
  866. for ( var i = 0, il = morphPositions.length; i < il; i ++ ) {
  867. if ( geometry.attributes.position === morphPositions[ i ] ) continue;
  868. morphPositions[ i ] = cloneBufferAttribute( morphPositions[ i ] );
  869. }
  870. for ( var i = 0, il = morphNormals.length; i < il; i ++ ) {
  871. if ( geometry.attributes.normal === morphNormals[ i ] ) continue;
  872. morphNormals[ i ] = cloneBufferAttribute( morphNormals[ i ] );
  873. }
  874. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  875. var target = targets[ i ];
  876. var attributeName = 'morphTarget' + i;
  877. if ( hasMorphPosition ) {
  878. // Three.js morph position is absolute value. The formula is
  879. // basePosition
  880. // + weight0 * ( morphPosition0 - basePosition )
  881. // + weight1 * ( morphPosition1 - basePosition )
  882. // ...
  883. // while the glTF one is relative
  884. // basePosition
  885. // + weight0 * glTFmorphPosition0
  886. // + weight1 * glTFmorphPosition1
  887. // ...
  888. // then we need to convert from relative to absolute here.
  889. if ( target.POSITION !== undefined ) {
  890. var positionAttribute = morphPositions[ i ];
  891. positionAttribute.name = attributeName;
  892. var position = geometry.attributes.position;
  893. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  894. positionAttribute.setXYZ(
  895. j,
  896. positionAttribute.getX( j ) + position.getX( j ),
  897. positionAttribute.getY( j ) + position.getY( j ),
  898. positionAttribute.getZ( j ) + position.getZ( j )
  899. );
  900. }
  901. }
  902. }
  903. if ( hasMorphNormal ) {
  904. // see target.POSITION's comment
  905. if ( target.NORMAL !== undefined ) {
  906. var normalAttribute = morphNormals[ i ];
  907. normalAttribute.name = attributeName;
  908. var normal = geometry.attributes.normal;
  909. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  910. normalAttribute.setXYZ(
  911. j,
  912. normalAttribute.getX( j ) + normal.getX( j ),
  913. normalAttribute.getY( j ) + normal.getY( j ),
  914. normalAttribute.getZ( j ) + normal.getZ( j )
  915. );
  916. }
  917. }
  918. }
  919. }
  920. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  921. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  922. return geometry;
  923. } );
  924. }
  925. /**
  926. * @param {THREE.Mesh} mesh
  927. * @param {GLTF.Mesh} meshDef
  928. */
  929. function updateMorphTargets( mesh, meshDef ) {
  930. mesh.updateMorphTargets();
  931. if ( meshDef.weights !== undefined ) {
  932. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  933. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  934. }
  935. }
  936. // .extras has user-defined data, so check that .extras.targetNames is an array.
  937. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  938. var targetNames = meshDef.extras.targetNames;
  939. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  940. mesh.morphTargetDictionary = {};
  941. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  942. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  943. }
  944. } else {
  945. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  946. }
  947. }
  948. }
  949. function createPrimitiveKey( primitiveDef ) {
  950. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  951. var geometryKey;
  952. if ( dracoExtension ) {
  953. geometryKey = 'draco:' + dracoExtension.bufferView
  954. + ':' + dracoExtension.indices
  955. + ':' + createAttributesKey( dracoExtension.attributes );
  956. } else {
  957. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  958. }
  959. return geometryKey;
  960. }
  961. function createAttributesKey( attributes ) {
  962. var attributesKey = '';
  963. var keys = Object.keys( attributes ).sort();
  964. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  965. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  966. }
  967. return attributesKey;
  968. }
  969. function cloneBufferAttribute( attribute ) {
  970. if ( attribute.isInterleavedBufferAttribute ) {
  971. var count = attribute.count;
  972. var itemSize = attribute.itemSize;
  973. var array = attribute.array.slice( 0, count * itemSize );
  974. for ( var i = 0, j = 0; i < count; ++ i ) {
  975. array[ j ++ ] = attribute.getX( i );
  976. if ( itemSize >= 2 ) array[ j ++ ] = attribute.getY( i );
  977. if ( itemSize >= 3 ) array[ j ++ ] = attribute.getZ( i );
  978. if ( itemSize >= 4 ) array[ j ++ ] = attribute.getW( i );
  979. }
  980. return new THREE.BufferAttribute( array, itemSize, attribute.normalized );
  981. }
  982. return attribute.clone();
  983. }
  984. /* GLTF PARSER */
  985. function GLTFParser( json, extensions, options ) {
  986. this.json = json || {};
  987. this.extensions = extensions || {};
  988. this.options = options || {};
  989. // loader object cache
  990. this.cache = new GLTFRegistry();
  991. // BufferGeometry caching
  992. this.primitiveCache = {};
  993. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  994. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  995. this.fileLoader = new THREE.FileLoader( this.options.manager );
  996. this.fileLoader.setResponseType( 'arraybuffer' );
  997. if ( this.options.crossOrigin === 'use-credentials' ) {
  998. this.fileLoader.setWithCredentials( true );
  999. }
  1000. }
  1001. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  1002. var parser = this;
  1003. var json = this.json;
  1004. var extensions = this.extensions;
  1005. // Clear the loader cache
  1006. this.cache.removeAll();
  1007. // Mark the special nodes/meshes in json for efficient parse
  1008. this.markDefs();
  1009. Promise.all( [
  1010. this.getDependencies( 'scene' ),
  1011. this.getDependencies( 'animation' ),
  1012. this.getDependencies( 'camera' ),
  1013. ] ).then( function ( dependencies ) {
  1014. var result = {
  1015. scene: dependencies[ 0 ][ json.scene || 0 ],
  1016. scenes: dependencies[ 0 ],
  1017. animations: dependencies[ 1 ],
  1018. cameras: dependencies[ 2 ],
  1019. asset: json.asset,
  1020. parser: parser,
  1021. userData: {}
  1022. };
  1023. addUnknownExtensionsToUserData( extensions, result, json );
  1024. assignExtrasToUserData( result, json );
  1025. onLoad( result );
  1026. } ).catch( onError );
  1027. };
  1028. /**
  1029. * Marks the special nodes/meshes in json for efficient parse.
  1030. */
  1031. GLTFParser.prototype.markDefs = function () {
  1032. var nodeDefs = this.json.nodes || [];
  1033. var skinDefs = this.json.skins || [];
  1034. var meshDefs = this.json.meshes || [];
  1035. var meshReferences = {};
  1036. var meshUses = {};
  1037. // Nothing in the node definition indicates whether it is a Bone or an
  1038. // Object3D. Use the skins' joint references to mark bones.
  1039. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  1040. var joints = skinDefs[ skinIndex ].joints;
  1041. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  1042. nodeDefs[ joints[ i ] ].isBone = true;
  1043. }
  1044. }
  1045. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  1046. // avoid having more than one THREE.Mesh with the same name, count
  1047. // references and rename instances below.
  1048. //
  1049. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  1050. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  1051. var nodeDef = nodeDefs[ nodeIndex ];
  1052. if ( nodeDef.mesh !== undefined ) {
  1053. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  1054. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  1055. }
  1056. meshReferences[ nodeDef.mesh ] ++;
  1057. // Nothing in the mesh definition indicates whether it is
  1058. // a SkinnedMesh or Mesh. Use the node's mesh reference
  1059. // to mark SkinnedMesh if node has skin.
  1060. if ( nodeDef.skin !== undefined ) {
  1061. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  1062. }
  1063. }
  1064. }
  1065. this.json.meshReferences = meshReferences;
  1066. this.json.meshUses = meshUses;
  1067. };
  1068. /**
  1069. * Requests the specified dependency asynchronously, with caching.
  1070. * @param {string} type
  1071. * @param {number} index
  1072. * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>}
  1073. */
  1074. GLTFParser.prototype.getDependency = function ( type, index ) {
  1075. var cacheKey = type + ':' + index;
  1076. var dependency = this.cache.get( cacheKey );
  1077. if ( ! dependency ) {
  1078. switch ( type ) {
  1079. case 'scene':
  1080. dependency = this.loadScene( index );
  1081. break;
  1082. case 'node':
  1083. dependency = this.loadNode( index );
  1084. break;
  1085. case 'mesh':
  1086. dependency = this.loadMesh( index );
  1087. break;
  1088. case 'accessor':
  1089. dependency = this.loadAccessor( index );
  1090. break;
  1091. case 'bufferView':
  1092. dependency = this.loadBufferView( index );
  1093. break;
  1094. case 'buffer':
  1095. dependency = this.loadBuffer( index );
  1096. break;
  1097. case 'material':
  1098. dependency = this.loadMaterial( index );
  1099. break;
  1100. case 'texture':
  1101. dependency = this.loadTexture( index );
  1102. break;
  1103. case 'skin':
  1104. dependency = this.loadSkin( index );
  1105. break;
  1106. case 'animation':
  1107. dependency = this.loadAnimation( index );
  1108. break;
  1109. case 'camera':
  1110. dependency = this.loadCamera( index );
  1111. break;
  1112. case 'light':
  1113. dependency = this.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].loadLight( index );
  1114. break;
  1115. default:
  1116. throw new Error( 'Unknown type: ' + type );
  1117. }
  1118. this.cache.add( cacheKey, dependency );
  1119. }
  1120. return dependency;
  1121. };
  1122. /**
  1123. * Requests all dependencies of the specified type asynchronously, with caching.
  1124. * @param {string} type
  1125. * @return {Promise<Array<Object>>}
  1126. */
  1127. GLTFParser.prototype.getDependencies = function ( type ) {
  1128. var dependencies = this.cache.get( type );
  1129. if ( ! dependencies ) {
  1130. var parser = this;
  1131. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  1132. dependencies = Promise.all( defs.map( function ( def, index ) {
  1133. return parser.getDependency( type, index );
  1134. } ) );
  1135. this.cache.add( type, dependencies );
  1136. }
  1137. return dependencies;
  1138. };
  1139. /**
  1140. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1141. * @param {number} bufferIndex
  1142. * @return {Promise<ArrayBuffer>}
  1143. */
  1144. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  1145. var bufferDef = this.json.buffers[ bufferIndex ];
  1146. var loader = this.fileLoader;
  1147. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  1148. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  1149. }
  1150. // If present, GLB container is required to be the first buffer.
  1151. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  1152. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  1153. }
  1154. var options = this.options;
  1155. return new Promise( function ( resolve, reject ) {
  1156. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  1157. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  1158. } );
  1159. } );
  1160. };
  1161. /**
  1162. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1163. * @param {number} bufferViewIndex
  1164. * @return {Promise<ArrayBuffer>}
  1165. */
  1166. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  1167. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  1168. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  1169. var byteLength = bufferViewDef.byteLength || 0;
  1170. var byteOffset = bufferViewDef.byteOffset || 0;
  1171. return buffer.slice( byteOffset, byteOffset + byteLength );
  1172. } );
  1173. };
  1174. /**
  1175. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  1176. * @param {number} accessorIndex
  1177. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  1178. */
  1179. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  1180. var parser = this;
  1181. var json = this.json;
  1182. var accessorDef = this.json.accessors[ accessorIndex ];
  1183. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  1184. // Ignore empty accessors, which may be used to declare runtime
  1185. // information about attributes coming from another source (e.g. Draco
  1186. // compression extension).
  1187. return Promise.resolve( null );
  1188. }
  1189. var pendingBufferViews = [];
  1190. if ( accessorDef.bufferView !== undefined ) {
  1191. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  1192. } else {
  1193. pendingBufferViews.push( null );
  1194. }
  1195. if ( accessorDef.sparse !== undefined ) {
  1196. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  1197. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  1198. }
  1199. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  1200. var bufferView = bufferViews[ 0 ];
  1201. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  1202. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  1203. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  1204. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  1205. var itemBytes = elementBytes * itemSize;
  1206. var byteOffset = accessorDef.byteOffset || 0;
  1207. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  1208. var normalized = accessorDef.normalized === true;
  1209. var array, bufferAttribute;
  1210. // The buffer is not interleaved if the stride is the item size in bytes.
  1211. if ( byteStride && byteStride !== itemBytes ) {
  1212. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  1213. // This makes sure that IBA.count reflects accessor.count properly
  1214. var ibSlice = Math.floor( byteOffset / byteStride );
  1215. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  1216. var ib = parser.cache.get( ibCacheKey );
  1217. if ( ! ib ) {
  1218. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
  1219. // Integer parameters to IB/IBA are in array elements, not bytes.
  1220. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  1221. parser.cache.add( ibCacheKey, ib );
  1222. }
  1223. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, (byteOffset % byteStride) / elementBytes, normalized );
  1224. } else {
  1225. if ( bufferView === null ) {
  1226. array = new TypedArray( accessorDef.count * itemSize );
  1227. } else {
  1228. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  1229. }
  1230. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  1231. }
  1232. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  1233. if ( accessorDef.sparse !== undefined ) {
  1234. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  1235. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  1236. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  1237. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  1238. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  1239. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  1240. if ( bufferView !== null ) {
  1241. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  1242. bufferAttribute.setArray( bufferAttribute.array.slice() );
  1243. }
  1244. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  1245. var index = sparseIndices[ i ];
  1246. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  1247. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  1248. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  1249. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  1250. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  1251. }
  1252. }
  1253. return bufferAttribute;
  1254. } );
  1255. };
  1256. /**
  1257. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  1258. * @param {number} textureIndex
  1259. * @return {Promise<THREE.Texture>}
  1260. */
  1261. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  1262. var parser = this;
  1263. var json = this.json;
  1264. var options = this.options;
  1265. var textureLoader = this.textureLoader;
  1266. var URL = window.URL || window.webkitURL;
  1267. var textureDef = json.textures[ textureIndex ];
  1268. var textureExtensions = textureDef.extensions || {};
  1269. var source;
  1270. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  1271. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  1272. } else {
  1273. source = json.images[ textureDef.source ];
  1274. }
  1275. var sourceURI = source.uri;
  1276. var isObjectURL = false;
  1277. if ( source.bufferView !== undefined ) {
  1278. // Load binary image data from bufferView, if provided.
  1279. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  1280. isObjectURL = true;
  1281. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  1282. sourceURI = URL.createObjectURL( blob );
  1283. return sourceURI;
  1284. } );
  1285. }
  1286. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  1287. // Load Texture resource.
  1288. var loader = THREE.Loader.Handlers.get( sourceURI );
  1289. if ( ! loader ) {
  1290. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  1291. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  1292. : textureLoader;
  1293. }
  1294. return new Promise( function ( resolve, reject ) {
  1295. loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  1296. } );
  1297. } ).then( function ( texture ) {
  1298. // Clean up resources and configure Texture.
  1299. if ( isObjectURL === true ) {
  1300. URL.revokeObjectURL( sourceURI );
  1301. }
  1302. texture.flipY = false;
  1303. if ( textureDef.name !== undefined ) texture.name = textureDef.name;
  1304. // Ignore unknown mime types, like DDS files.
  1305. if ( source.mimeType in MIME_TYPE_FORMATS ) {
  1306. texture.format = MIME_TYPE_FORMATS[ source.mimeType ];
  1307. }
  1308. var samplers = json.samplers || {};
  1309. var sampler = samplers[ textureDef.sampler ] || {};
  1310. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  1311. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipmapLinearFilter;
  1312. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  1313. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  1314. return texture;
  1315. } );
  1316. };
  1317. /**
  1318. * Asynchronously assigns a texture to the given material parameters.
  1319. * @param {Object} materialParams
  1320. * @param {string} mapName
  1321. * @param {Object} mapDef
  1322. * @return {Promise}
  1323. */
  1324. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  1325. var parser = this;
  1326. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  1327. if ( ! texture.isCompressedTexture ) {
  1328. switch ( mapName ) {
  1329. case 'aoMap':
  1330. case 'emissiveMap':
  1331. case 'metalnessMap':
  1332. case 'normalMap':
  1333. case 'roughnessMap':
  1334. texture.format = THREE.RGBFormat;
  1335. break;
  1336. }
  1337. }
  1338. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  1339. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  1340. if ( transform ) {
  1341. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  1342. }
  1343. }
  1344. materialParams[ mapName ] = texture;
  1345. } );
  1346. };
  1347. /**
  1348. * Assigns final material to a Mesh, Line, or Points instance. The instance
  1349. * already has a material (generated from the glTF material options alone)
  1350. * but reuse of the same glTF material may require multiple threejs materials
  1351. * to accomodate different primitive types, defines, etc. New materials will
  1352. * be created if necessary, and reused from a cache.
  1353. * @param {THREE.Object3D} mesh Mesh, Line, or Points instance.
  1354. */
  1355. GLTFParser.prototype.assignFinalMaterial = function ( mesh ) {
  1356. var geometry = mesh.geometry;
  1357. var material = mesh.material;
  1358. var extensions = this.extensions;
  1359. var useVertexTangents = geometry.attributes.tangent !== undefined;
  1360. var useVertexColors = geometry.attributes.color !== undefined;
  1361. var useFlatShading = geometry.attributes.normal === undefined;
  1362. var useSkinning = mesh.isSkinnedMesh === true;
  1363. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  1364. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  1365. if ( mesh.isPoints ) {
  1366. var cacheKey = 'PointsMaterial:' + material.uuid;
  1367. var pointsMaterial = this.cache.get( cacheKey );
  1368. if ( ! pointsMaterial ) {
  1369. pointsMaterial = new THREE.PointsMaterial();
  1370. THREE.Material.prototype.copy.call( pointsMaterial, material );
  1371. pointsMaterial.color.copy( material.color );
  1372. pointsMaterial.map = material.map;
  1373. pointsMaterial.lights = false; // PointsMaterial doesn't support lights yet
  1374. this.cache.add( cacheKey, pointsMaterial );
  1375. }
  1376. material = pointsMaterial;
  1377. } else if ( mesh.isLine ) {
  1378. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  1379. var lineMaterial = this.cache.get( cacheKey );
  1380. if ( ! lineMaterial ) {
  1381. lineMaterial = new THREE.LineBasicMaterial();
  1382. THREE.Material.prototype.copy.call( lineMaterial, material );
  1383. lineMaterial.color.copy( material.color );
  1384. lineMaterial.lights = false; // LineBasicMaterial doesn't support lights yet
  1385. this.cache.add( cacheKey, lineMaterial );
  1386. }
  1387. material = lineMaterial;
  1388. }
  1389. // Clone the material if it will be modified
  1390. if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  1391. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  1392. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  1393. if ( useSkinning ) cacheKey += 'skinning:';
  1394. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  1395. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  1396. if ( useFlatShading ) cacheKey += 'flat-shading:';
  1397. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  1398. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  1399. var cachedMaterial = this.cache.get( cacheKey );
  1400. if ( ! cachedMaterial ) {
  1401. cachedMaterial = material.isGLTFSpecularGlossinessMaterial
  1402. ? extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].cloneMaterial( material )
  1403. : material.clone();
  1404. if ( useSkinning ) cachedMaterial.skinning = true;
  1405. if ( useVertexTangents ) cachedMaterial.vertexTangents = true;
  1406. if ( useVertexColors ) cachedMaterial.vertexColors = THREE.VertexColors;
  1407. if ( useFlatShading ) cachedMaterial.flatShading = true;
  1408. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  1409. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  1410. this.cache.add( cacheKey, cachedMaterial );
  1411. }
  1412. material = cachedMaterial;
  1413. }
  1414. // workarounds for mesh and geometry
  1415. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  1416. console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' );
  1417. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  1418. }
  1419. if ( material.isGLTFSpecularGlossinessMaterial ) {
  1420. // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update
  1421. mesh.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  1422. }
  1423. mesh.material = material;
  1424. };
  1425. /**
  1426. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  1427. * @param {number} materialIndex
  1428. * @return {Promise<THREE.Material>}
  1429. */
  1430. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  1431. var parser = this;
  1432. var json = this.json;
  1433. var extensions = this.extensions;
  1434. var materialDef = json.materials[ materialIndex ];
  1435. var materialType;
  1436. var materialParams = {};
  1437. var materialExtensions = materialDef.extensions || {};
  1438. var pending = [];
  1439. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  1440. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  1441. materialType = sgExtension.getMaterialType();
  1442. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  1443. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  1444. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  1445. materialType = kmuExtension.getMaterialType();
  1446. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  1447. } else {
  1448. // Specification:
  1449. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  1450. materialType = THREE.MeshStandardMaterial;
  1451. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  1452. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  1453. materialParams.opacity = 1.0;
  1454. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  1455. var array = metallicRoughness.baseColorFactor;
  1456. materialParams.color.fromArray( array );
  1457. materialParams.opacity = array[ 3 ];
  1458. }
  1459. if ( metallicRoughness.baseColorTexture !== undefined ) {
  1460. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  1461. }
  1462. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  1463. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  1464. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  1465. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  1466. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  1467. }
  1468. }
  1469. if ( materialDef.doubleSided === true ) {
  1470. materialParams.side = THREE.DoubleSide;
  1471. }
  1472. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  1473. if ( alphaMode === ALPHA_MODES.BLEND ) {
  1474. materialParams.transparent = true;
  1475. } else {
  1476. materialParams.transparent = false;
  1477. if ( alphaMode === ALPHA_MODES.MASK ) {
  1478. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  1479. }
  1480. }
  1481. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1482. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  1483. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  1484. if ( materialDef.normalTexture.scale !== undefined ) {
  1485. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  1486. }
  1487. }
  1488. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1489. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  1490. if ( materialDef.occlusionTexture.strength !== undefined ) {
  1491. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  1492. }
  1493. }
  1494. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1495. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  1496. }
  1497. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1498. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  1499. }
  1500. return Promise.all( pending ).then( function () {
  1501. var material;
  1502. if ( materialType === THREE.ShaderMaterial ) {
  1503. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  1504. } else {
  1505. material = new materialType( materialParams );
  1506. }
  1507. if ( materialDef.name !== undefined ) material.name = materialDef.name;
  1508. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  1509. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  1510. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  1511. if ( material.specularMap ) material.specularMap.encoding = THREE.sRGBEncoding;
  1512. assignExtrasToUserData( material, materialDef );
  1513. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  1514. return material;
  1515. } );
  1516. };
  1517. /**
  1518. * @param {THREE.BufferGeometry} geometry
  1519. * @param {GLTF.Primitive} primitiveDef
  1520. * @param {GLTFParser} parser
  1521. * @return {Promise<THREE.BufferGeometry>}
  1522. */
  1523. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  1524. var attributes = primitiveDef.attributes;
  1525. var pending = [];
  1526. function assignAttributeAccessor( accessorIndex, attributeName ) {
  1527. return parser.getDependency( 'accessor', accessorIndex )
  1528. .then( function ( accessor ) {
  1529. geometry.addAttribute( attributeName, accessor );
  1530. } );
  1531. }
  1532. for ( var gltfAttributeName in attributes ) {
  1533. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  1534. // Skip attributes already provided by e.g. Draco extension.
  1535. if ( threeAttributeName in geometry.attributes ) continue;
  1536. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  1537. }
  1538. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  1539. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  1540. geometry.setIndex( accessor );
  1541. } );
  1542. pending.push( accessor );
  1543. }
  1544. assignExtrasToUserData( geometry, primitiveDef );
  1545. return Promise.all( pending ).then( function () {
  1546. return primitiveDef.targets !== undefined
  1547. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  1548. : geometry;
  1549. } );
  1550. }
  1551. /**
  1552. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  1553. *
  1554. * Creates BufferGeometries from primitives.
  1555. *
  1556. * @param {Array<GLTF.Primitive>} primitives
  1557. * @return {Promise<Array<THREE.BufferGeometry>>}
  1558. */
  1559. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  1560. var parser = this;
  1561. var extensions = this.extensions;
  1562. var cache = this.primitiveCache;
  1563. function createDracoPrimitive( primitive ) {
  1564. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  1565. .decodePrimitive( primitive, parser )
  1566. .then( function ( geometry ) {
  1567. return addPrimitiveAttributes( geometry, primitive, parser );
  1568. } );
  1569. }
  1570. var pending = [];
  1571. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1572. var primitive = primitives[ i ];
  1573. var cacheKey = createPrimitiveKey( primitive );
  1574. // See if we've already created this geometry
  1575. var cached = cache[ cacheKey ];
  1576. if ( cached ) {
  1577. // Use the cached geometry if it exists
  1578. pending.push( cached.promise );
  1579. } else {
  1580. var geometryPromise;
  1581. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  1582. // Use DRACO geometry if available
  1583. geometryPromise = createDracoPrimitive( primitive );
  1584. } else {
  1585. // Otherwise create a new geometry
  1586. geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
  1587. }
  1588. // Cache this geometry
  1589. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  1590. pending.push( geometryPromise );
  1591. }
  1592. }
  1593. return Promise.all( pending );
  1594. };
  1595. /**
  1596. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  1597. * @param {number} meshIndex
  1598. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  1599. */
  1600. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  1601. var parser = this;
  1602. var json = this.json;
  1603. var meshDef = json.meshes[ meshIndex ];
  1604. var primitives = meshDef.primitives;
  1605. var pending = [];
  1606. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1607. var material = primitives[ i ].material === undefined
  1608. ? createDefaultMaterial()
  1609. : this.getDependency( 'material', primitives[ i ].material );
  1610. pending.push( material );
  1611. }
  1612. return Promise.all( pending ).then( function ( originalMaterials ) {
  1613. return parser.loadGeometries( primitives ).then( function ( geometries ) {
  1614. var meshes = [];
  1615. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  1616. var geometry = geometries[ i ];
  1617. var primitive = primitives[ i ];
  1618. // 1. create Mesh
  1619. var mesh;
  1620. var material = originalMaterials[ i ];
  1621. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  1622. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  1623. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  1624. primitive.mode === undefined ) {
  1625. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  1626. mesh = meshDef.isSkinnedMesh === true
  1627. ? new THREE.SkinnedMesh( geometry, material )
  1628. : new THREE.Mesh( geometry, material );
  1629. if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) {
  1630. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  1631. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  1632. mesh.normalizeSkinWeights();
  1633. }
  1634. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  1635. mesh.drawMode = THREE.TriangleStripDrawMode;
  1636. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  1637. mesh.drawMode = THREE.TriangleFanDrawMode;
  1638. }
  1639. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1640. mesh = new THREE.LineSegments( geometry, material );
  1641. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  1642. mesh = new THREE.Line( geometry, material );
  1643. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  1644. mesh = new THREE.LineLoop( geometry, material );
  1645. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  1646. mesh = new THREE.Points( geometry, material );
  1647. } else {
  1648. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  1649. }
  1650. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  1651. updateMorphTargets( mesh, meshDef );
  1652. }
  1653. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  1654. if ( geometries.length > 1 ) mesh.name += '_' + i;
  1655. assignExtrasToUserData( mesh, meshDef );
  1656. parser.assignFinalMaterial( mesh );
  1657. meshes.push( mesh );
  1658. }
  1659. if ( meshes.length === 1 ) {
  1660. return meshes[ 0 ];
  1661. }
  1662. var group = new THREE.Group();
  1663. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  1664. group.add( meshes[ i ] );
  1665. }
  1666. return group;
  1667. } );
  1668. } );
  1669. };
  1670. /**
  1671. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  1672. * @param {number} cameraIndex
  1673. * @return {Promise<THREE.Camera>}
  1674. */
  1675. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  1676. var camera;
  1677. var cameraDef = this.json.cameras[ cameraIndex ];
  1678. var params = cameraDef[ cameraDef.type ];
  1679. if ( ! params ) {
  1680. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  1681. return;
  1682. }
  1683. if ( cameraDef.type === 'perspective' ) {
  1684. camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  1685. } else if ( cameraDef.type === 'orthographic' ) {
  1686. camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar );
  1687. }
  1688. if ( cameraDef.name !== undefined ) camera.name = cameraDef.name;
  1689. assignExtrasToUserData( camera, cameraDef );
  1690. return Promise.resolve( camera );
  1691. };
  1692. /**
  1693. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  1694. * @param {number} skinIndex
  1695. * @return {Promise<Object>}
  1696. */
  1697. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  1698. var skinDef = this.json.skins[ skinIndex ];
  1699. var skinEntry = { joints: skinDef.joints };
  1700. if ( skinDef.inverseBindMatrices === undefined ) {
  1701. return Promise.resolve( skinEntry );
  1702. }
  1703. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  1704. skinEntry.inverseBindMatrices = accessor;
  1705. return skinEntry;
  1706. } );
  1707. };
  1708. /**
  1709. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  1710. * @param {number} animationIndex
  1711. * @return {Promise<THREE.AnimationClip>}
  1712. */
  1713. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  1714. var json = this.json;
  1715. var animationDef = json.animations[ animationIndex ];
  1716. var pendingNodes = [];
  1717. var pendingInputAccessors = [];
  1718. var pendingOutputAccessors = [];
  1719. var pendingSamplers = [];
  1720. var pendingTargets = [];
  1721. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  1722. var channel = animationDef.channels[ i ];
  1723. var sampler = animationDef.samplers[ channel.sampler ];
  1724. var target = channel.target;
  1725. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  1726. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  1727. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  1728. pendingNodes.push( this.getDependency( 'node', name ) );
  1729. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  1730. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  1731. pendingSamplers.push( sampler );
  1732. pendingTargets.push( target );
  1733. }
  1734. return Promise.all( [
  1735. Promise.all( pendingNodes ),
  1736. Promise.all( pendingInputAccessors ),
  1737. Promise.all( pendingOutputAccessors ),
  1738. Promise.all( pendingSamplers ),
  1739. Promise.all( pendingTargets )
  1740. ] ).then( function ( dependencies ) {
  1741. var nodes = dependencies[ 0 ];
  1742. var inputAccessors = dependencies[ 1 ];
  1743. var outputAccessors = dependencies[ 2 ];
  1744. var samplers = dependencies[ 3 ];
  1745. var targets = dependencies[ 4 ];
  1746. var tracks = [];
  1747. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  1748. var node = nodes[ i ];
  1749. var inputAccessor = inputAccessors[ i ];
  1750. var outputAccessor = outputAccessors[ i ];
  1751. var sampler = samplers[ i ];
  1752. var target = targets[ i ];
  1753. if ( node === undefined ) continue;
  1754. node.updateMatrix();
  1755. node.matrixAutoUpdate = true;
  1756. var TypedKeyframeTrack;
  1757. switch ( PATH_PROPERTIES[ target.path ] ) {
  1758. case PATH_PROPERTIES.weights:
  1759. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  1760. break;
  1761. case PATH_PROPERTIES.rotation:
  1762. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  1763. break;
  1764. case PATH_PROPERTIES.position:
  1765. case PATH_PROPERTIES.scale:
  1766. default:
  1767. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  1768. break;
  1769. }
  1770. var targetName = node.name ? node.name : node.uuid;
  1771. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  1772. var targetNames = [];
  1773. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  1774. // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh.
  1775. node.traverse( function ( object ) {
  1776. if ( object.isMesh === true && object.morphTargetInfluences ) {
  1777. targetNames.push( object.name ? object.name : object.uuid );
  1778. }
  1779. } );
  1780. } else {
  1781. targetNames.push( targetName );
  1782. }
  1783. var outputArray = outputAccessor.array;
  1784. if ( outputAccessor.normalized ) {
  1785. var scale;
  1786. if ( outputArray.constructor === Int8Array ) {
  1787. scale = 1 / 127;
  1788. } else if ( outputArray.constructor === Uint8Array ) {
  1789. scale = 1 / 255;
  1790. } else if ( outputArray.constructor == Int16Array ) {
  1791. scale = 1 / 32767;
  1792. } else if ( outputArray.constructor === Uint16Array ) {
  1793. scale = 1 / 65535;
  1794. } else {
  1795. throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' );
  1796. }
  1797. var scaled = new Float32Array( outputArray.length );
  1798. for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) {
  1799. scaled[ j ] = outputArray[ j ] * scale;
  1800. }
  1801. outputArray = scaled;
  1802. }
  1803. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  1804. var track = new TypedKeyframeTrack(
  1805. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  1806. inputAccessor.array,
  1807. outputArray,
  1808. interpolation
  1809. );
  1810. // Override interpolation with custom factory method.
  1811. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  1812. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  1813. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  1814. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  1815. // must be divided by three to get the interpolant's sampleSize argument.
  1816. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  1817. };
  1818. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  1819. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  1820. }
  1821. tracks.push( track );
  1822. }
  1823. }
  1824. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  1825. return new THREE.AnimationClip( name, undefined, tracks );
  1826. } );
  1827. };
  1828. /**
  1829. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  1830. * @param {number} nodeIndex
  1831. * @return {Promise<THREE.Object3D>}
  1832. */
  1833. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  1834. var json = this.json;
  1835. var extensions = this.extensions;
  1836. var parser = this;
  1837. var meshReferences = json.meshReferences;
  1838. var meshUses = json.meshUses;
  1839. var nodeDef = json.nodes[ nodeIndex ];
  1840. return ( function () {
  1841. var pending = [];
  1842. if ( nodeDef.mesh !== undefined ) {
  1843. pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  1844. var node;
  1845. if ( meshReferences[ nodeDef.mesh ] > 1 ) {
  1846. var instanceNum = meshUses[ nodeDef.mesh ] ++;
  1847. node = mesh.clone();
  1848. node.name += '_instance_' + instanceNum;
  1849. // onBeforeRender copy for Specular-Glossiness
  1850. node.onBeforeRender = mesh.onBeforeRender;
  1851. for ( var i = 0, il = node.children.length; i < il; i ++ ) {
  1852. node.children[ i ].name += '_instance_' + instanceNum;
  1853. node.children[ i ].onBeforeRender = mesh.children[ i ].onBeforeRender;
  1854. }
  1855. } else {
  1856. node = mesh;
  1857. }
  1858. // if weights are provided on the node, override weights on the mesh.
  1859. if ( nodeDef.weights !== undefined ) {
  1860. node.traverse( function ( o ) {
  1861. if ( ! o.isMesh ) return;
  1862. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  1863. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  1864. }
  1865. } );
  1866. }
  1867. return node;
  1868. } ) );
  1869. }
  1870. if ( nodeDef.camera !== undefined ) {
  1871. pending.push( parser.getDependency( 'camera', nodeDef.camera ) );
  1872. }
  1873. if ( nodeDef.extensions
  1874. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ]
  1875. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light !== undefined ) {
  1876. pending.push( parser.getDependency( 'light', nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light ) );
  1877. }
  1878. return Promise.all( pending );
  1879. }() ).then( function ( objects ) {
  1880. var node;
  1881. // .isBone isn't in glTF spec. See .markDefs
  1882. if ( nodeDef.isBone === true ) {
  1883. node = new THREE.Bone();
  1884. } else if ( objects.length > 1 ) {
  1885. node = new THREE.Group();
  1886. } else if ( objects.length === 1 ) {
  1887. node = objects[ 0 ];
  1888. } else {
  1889. node = new THREE.Object3D();
  1890. }
  1891. if ( node !== objects[ 0 ] ) {
  1892. for ( var i = 0, il = objects.length; i < il; i ++ ) {
  1893. node.add( objects[ i ] );
  1894. }
  1895. }
  1896. if ( nodeDef.name !== undefined ) {
  1897. node.userData.name = nodeDef.name;
  1898. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  1899. }
  1900. assignExtrasToUserData( node, nodeDef );
  1901. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  1902. if ( nodeDef.matrix !== undefined ) {
  1903. var matrix = new THREE.Matrix4();
  1904. matrix.fromArray( nodeDef.matrix );
  1905. node.applyMatrix( matrix );
  1906. } else {
  1907. if ( nodeDef.translation !== undefined ) {
  1908. node.position.fromArray( nodeDef.translation );
  1909. }
  1910. if ( nodeDef.rotation !== undefined ) {
  1911. node.quaternion.fromArray( nodeDef.rotation );
  1912. }
  1913. if ( nodeDef.scale !== undefined ) {
  1914. node.scale.fromArray( nodeDef.scale );
  1915. }
  1916. }
  1917. return node;
  1918. } );
  1919. };
  1920. /**
  1921. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  1922. * @param {number} sceneIndex
  1923. * @return {Promise<THREE.Scene>}
  1924. */
  1925. GLTFParser.prototype.loadScene = function () {
  1926. // scene node hierachy builder
  1927. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  1928. var nodeDef = json.nodes[ nodeId ];
  1929. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  1930. if ( nodeDef.skin === undefined ) return node;
  1931. // build skeleton here as well
  1932. var skinEntry;
  1933. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  1934. skinEntry = skin;
  1935. var pendingJoints = [];
  1936. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  1937. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  1938. }
  1939. return Promise.all( pendingJoints );
  1940. } ).then( function ( jointNodes ) {
  1941. node.traverse( function ( mesh ) {
  1942. if ( ! mesh.isMesh ) return;
  1943. var bones = [];
  1944. var boneInverses = [];
  1945. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  1946. var jointNode = jointNodes[ j ];
  1947. if ( jointNode ) {
  1948. bones.push( jointNode );
  1949. var mat = new THREE.Matrix4();
  1950. if ( skinEntry.inverseBindMatrices !== undefined ) {
  1951. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  1952. }
  1953. boneInverses.push( mat );
  1954. } else {
  1955. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  1956. }
  1957. }
  1958. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  1959. } );
  1960. return node;
  1961. } );
  1962. } ).then( function ( node ) {
  1963. // build node hierachy
  1964. parentObject.add( node );
  1965. var pending = [];
  1966. if ( nodeDef.children ) {
  1967. var children = nodeDef.children;
  1968. for ( var i = 0, il = children.length; i < il; i ++ ) {
  1969. var child = children[ i ];
  1970. pending.push( buildNodeHierachy( child, node, json, parser ) );
  1971. }
  1972. }
  1973. return Promise.all( pending );
  1974. } );
  1975. }
  1976. return function loadScene( sceneIndex ) {
  1977. var json = this.json;
  1978. var extensions = this.extensions;
  1979. var sceneDef = this.json.scenes[ sceneIndex ];
  1980. var parser = this;
  1981. var scene = new THREE.Scene();
  1982. if ( sceneDef.name !== undefined ) scene.name = sceneDef.name;
  1983. assignExtrasToUserData( scene, sceneDef );
  1984. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  1985. var nodeIds = sceneDef.nodes || [];
  1986. var pending = [];
  1987. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  1988. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  1989. }
  1990. return Promise.all( pending ).then( function () {
  1991. return scene;
  1992. } );
  1993. };
  1994. }();
  1995. return GLTFLoader;
  1996. } )();