TextureCache.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import defined from "../Core/defined.js";
  2. import destroyObject from "../Core/destroyObject.js";
  3. /**
  4. * @private
  5. */
  6. function TextureCache() {
  7. this._textures = {};
  8. this._numberOfTextures = 0;
  9. this._texturesToRelease = {};
  10. }
  11. Object.defineProperties(TextureCache.prototype, {
  12. numberOfTextures: {
  13. get: function () {
  14. return this._numberOfTextures;
  15. },
  16. },
  17. });
  18. TextureCache.prototype.getTexture = function (keyword) {
  19. const cachedTexture = this._textures[keyword];
  20. if (!defined(cachedTexture)) {
  21. return undefined;
  22. }
  23. // No longer want to release this if it was previously released.
  24. delete this._texturesToRelease[keyword];
  25. ++cachedTexture.count;
  26. return cachedTexture.texture;
  27. };
  28. TextureCache.prototype.addTexture = function (keyword, texture) {
  29. const cachedTexture = {
  30. texture: texture,
  31. count: 1,
  32. };
  33. texture.finalDestroy = texture.destroy;
  34. const that = this;
  35. texture.destroy = function () {
  36. if (--cachedTexture.count === 0) {
  37. that._texturesToRelease[keyword] = cachedTexture;
  38. }
  39. };
  40. this._textures[keyword] = cachedTexture;
  41. ++this._numberOfTextures;
  42. };
  43. TextureCache.prototype.destroyReleasedTextures = function () {
  44. const texturesToRelease = this._texturesToRelease;
  45. for (const keyword in texturesToRelease) {
  46. if (texturesToRelease.hasOwnProperty(keyword)) {
  47. const cachedTexture = texturesToRelease[keyword];
  48. delete this._textures[keyword];
  49. cachedTexture.texture.finalDestroy();
  50. --this._numberOfTextures;
  51. }
  52. }
  53. this._texturesToRelease = {};
  54. };
  55. TextureCache.prototype.isDestroyed = function () {
  56. return false;
  57. };
  58. TextureCache.prototype.destroy = function () {
  59. const textures = this._textures;
  60. for (const keyword in textures) {
  61. if (textures.hasOwnProperty(keyword)) {
  62. textures[keyword].texture.finalDestroy();
  63. }
  64. }
  65. return destroyObject(this);
  66. };
  67. export default TextureCache;