Skip to content

Instantly share code, notes, and snippets.

@DigiTec
Created December 5, 2016 01:09
Show Gist options
  • Save DigiTec/bbb5f7991a853e5cc3e96dc90713cff2 to your computer and use it in GitHub Desktop.
Save DigiTec/bbb5f7991a853e5cc3e96dc90713cff2 to your computer and use it in GitHub Desktop.
Super simple texture cache for THREE.js to avoid multiple network downloads and potentially GPU uploads
let textureLoader = {
webLoader: new THREE.TextureLoader(),
cache: {},
useCache: true,
getTexture: function (url) {
let cache = this.cache;
let webLoader = this.webLoader;
if (!cache[url]) {
cache[url] = new Promise(function (resolve, reject) {
webLoader.setCrossOrigin('Access-Control-Allow-Origin');
webLoader.load(url, function (texture) {
// When the texture is ready, simply supply it.
resolve(texture);
}, function (xhr) {
// No progress indications
}, function (xhr) {
// Failed to load the texture for some reason.
reject()
});
});
}
// Have a way to turn off the caching.
let cachedTexture = cache[url];
if (!this.useCache) {
delete cache[url];
}
return cachedTexture;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment