GLTFLoader.js 91 KB

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