CCTextureCache.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. /****************************************************************************
  2. Copyright (c) 2010-2012 cocos2d-x.org
  3. Copyright (c) 2008-2010 Ricardo Quesada
  4. Copyright (c) 2011 Zynga Inc.
  5. http://www.cocos2d-x.org
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. THE SOFTWARE.
  21. ****************************************************************************/
  22. /**
  23. * TextureCache - Alloc, Init & Dealloc
  24. * @type object
  25. */
  26. cc.g_sharedTextureCache = null;
  27. /**
  28. * Load the images to the cache
  29. * @param {String} imageUrl
  30. */
  31. cc.loadImage = function (imageUrl) {
  32. // compute image type
  33. var imageType = cc.computeImageFormatType(imageUrl);
  34. if (imageType == cc.FMT_UNKNOWN) {
  35. cc.log("unsupported format:" + imageUrl);
  36. return;
  37. }
  38. var image = new Image();
  39. image.src = imageUrl;
  40. image.addEventListener('load', cc.loadImage.handler, false);
  41. };
  42. cc.loadImage.handler = function(){
  43. cc.TextureCache.getInstance().cacheImage(this.src, this);
  44. this.removeEventListener('load', cc.loadImage.handler, false);
  45. };
  46. /**
  47. * Support image format type
  48. * @param {String} filename
  49. * @return {Number}
  50. */
  51. cc.computeImageFormatType = function (filename) {
  52. if (filename.toLowerCase().indexOf('.jpg') > 0 || filename.toLowerCase().indexOf('.jpeg') > 0) {
  53. return cc.FMT_JPG;
  54. } else if (filename.toLowerCase().indexOf('.png') > 0) {
  55. return cc.FMT_PNG;
  56. } else if (filename.toLowerCase().indexOf('.webp') > 0) {
  57. return cc.FMT_WEBP;
  58. }
  59. return cc.FMT_UNKNOWN;
  60. };
  61. /**
  62. * Implementation TextureCache
  63. * @class
  64. * @extends cc.Class
  65. */
  66. cc.TextureCache = cc.Class.extend(/** @lends cc.TextureCache# */{
  67. _textures:null,
  68. _textureColorsCache:null,
  69. _textureKeySeq:null,
  70. _rendererInitialized:false,
  71. _loadedTexturesBefore:null,
  72. _loadingTexturesBefore:null,
  73. /**
  74. * Constructor
  75. */
  76. ctor: function () {
  77. if(cc.g_sharedTextureCache)
  78. throw "Attempted to allocate a second instance of a singleton.";
  79. this._textureKeySeq += (0 | Math.random() * 1000);
  80. this._textures = {};
  81. this._textureColorsCache = {};
  82. if(cc.renderContextType === cc.WEBGL){
  83. this._loadedTexturesBefore = {};
  84. this._loadingTexturesBefore = {};
  85. }
  86. },
  87. _addImageAsyncCallBack:function (target, selector) {
  88. cc.doCallback(selector, target);
  89. },
  90. _initializingRenderer : function(){
  91. this._rendererInitialized = true;
  92. var selPath;
  93. //init texture from _loadedTexturesBefore
  94. var locLoadedTexturesBefore = this._loadedTexturesBefore, locTextures = this._textures;
  95. for(selPath in locLoadedTexturesBefore){
  96. var htmlImage = locLoadedTexturesBefore[selPath];
  97. var texture2d = new cc.Texture2D();
  98. texture2d.initWithElement(htmlImage);
  99. texture2d.handleLoadedTexture();
  100. locTextures[selPath] = texture2d;
  101. }
  102. this._loadedTexturesBefore = {};
  103. },
  104. /**
  105. * <p>
  106. * Returns a Texture2D object given an PVR filename <br/>
  107. * If the file image was not previously loaded, it will create a new CCTexture2D <br/>
  108. * object and it will return it. Otherwise it will return a reference of a previously loaded image <br/>
  109. * note: AddPVRTCImage does not support on HTML5
  110. * </p>
  111. * @param {String} filename
  112. * @return {cc.Texture2D}
  113. */
  114. addPVRTCImage:function (filename) {
  115. cc.log("TextureCache:addPVRTCImage does not support on HTML5");
  116. },
  117. /**
  118. * <p>
  119. * Returns a Texture2D object given an ETC filename <br/>
  120. * If the file image was not previously loaded, it will create a new CCTexture2D <br/>
  121. * object and it will return it. Otherwise it will return a reference of a previously loaded image <br/>
  122. * note:addETCImage does not support on HTML5
  123. * </p>
  124. * @param {String} filename
  125. * @return {cc.Texture2D}
  126. */
  127. addETCImage:function (filename) {
  128. cc.log("TextureCache:addPVRTCImage does not support on HTML5");
  129. },
  130. /**
  131. * Description
  132. * @return {String}
  133. */
  134. description:function () {
  135. return "<TextureCache | Number of textures = " + this._textures.length + ">";
  136. },
  137. /**
  138. * Returns an already created texture. Returns null if the texture doesn't exist.
  139. * @param {String} textureKeyName
  140. * @return {cc.Texture2D|Null}
  141. * @example
  142. * //example
  143. * var key = cc.TextureCache.getInstance().textureForKey("hello.png");
  144. */
  145. textureForKey:function (textureKeyName) {
  146. var fullPath = cc.FileUtils.getInstance().fullPathForFilename(textureKeyName);
  147. if (this._textures[fullPath])
  148. return this._textures[fullPath];
  149. return null;
  150. },
  151. /**
  152. * @param {Image} texture
  153. * @return {String|Null}
  154. * @example
  155. * //example
  156. * var key = cc.TextureCache.getInstance().getKeyByTexture(texture);
  157. */
  158. getKeyByTexture:function (texture) {
  159. for (var key in this._textures) {
  160. if (this._textures[key] == texture) {
  161. return key;
  162. }
  163. }
  164. return null;
  165. },
  166. _generalTextureKey:function () {
  167. this._textureKeySeq++;
  168. return "_textureKey_" + this._textureKeySeq;
  169. },
  170. /**
  171. * @param {Image} texture
  172. * @return {Array}
  173. * @example
  174. * //example
  175. * var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(texture);
  176. */
  177. getTextureColors:function (texture) {
  178. var key = this.getKeyByTexture(texture);
  179. if (!key) {
  180. if (texture instanceof HTMLImageElement)
  181. key = texture.src;
  182. else
  183. key = this._generalTextureKey();
  184. }
  185. if (!this._textureColorsCache[key])
  186. this._textureColorsCache[key] = cc.generateTextureCacheForColor(texture);
  187. return this._textureColorsCache[key];
  188. },
  189. /**
  190. * <p>Returns a Texture2D object given an PVR filename<br />
  191. * If the file image was not previously loaded, it will create a new Texture2D<br />
  192. * object and it will return it. Otherwise it will return a reference of a previously loaded image </p>
  193. * @param {String} path
  194. * @return {cc.Texture2D}
  195. */
  196. addPVRImage:function (path) {
  197. if(!path)
  198. throw "cc.TextureCache.addPVRImage(): path should be non-null";
  199. path = cc.FileUtils.getInstance().fullPathForFilename(path);
  200. var key = path;
  201. if (this._textures[key] != null)
  202. return this._textures[key];
  203. // Split up directory and filename
  204. var tex = new cc.Texture2D();
  205. if (tex.initWithPVRFile(key)) {
  206. this._textures[key] = tex;
  207. } else {
  208. cc.log("cocos2d: Couldn't add PVRImage:" + key + " in TextureCache");
  209. }
  210. return tex;
  211. },
  212. /**
  213. * <p>Purges the dictionary of loaded textures. <br />
  214. * Call this method if you receive the "Memory Warning" <br />
  215. * In the short term: it will free some resources preventing your app from being killed <br />
  216. * In the medium term: it will allocate more resources <br />
  217. * In the long term: it will be the same</p>
  218. * @example
  219. * //example
  220. * cc.TextureCache.getInstance().removeAllTextures();
  221. */
  222. removeAllTextures:function () {
  223. var locTextures = this._textures;
  224. for (var selKey in locTextures) {
  225. if(locTextures[selKey])
  226. locTextures[selKey].releaseTexture();
  227. }
  228. this._textures = {};
  229. },
  230. /**
  231. * Deletes a texture from the cache given a texture
  232. * @param {Image} texture
  233. * @example
  234. * //example
  235. * cc.TextureCache.getInstance().removeTexture(texture);
  236. */
  237. removeTexture:function (texture) {
  238. if (!texture)
  239. return;
  240. var locTextures = this._textures;
  241. for (var selKey in locTextures) {
  242. if (locTextures[selKey] == texture) {
  243. locTextures[selKey].releaseTexture();
  244. delete(locTextures[selKey]);
  245. }
  246. }
  247. },
  248. /**
  249. * Deletes a texture from the cache given a its key name
  250. * @param {String} textureKeyName
  251. * @example
  252. * //example
  253. * cc.TextureCache.getInstance().removeTexture("hello.png");
  254. */
  255. removeTextureForKey:function (textureKeyName) {
  256. if (textureKeyName == null)
  257. return;
  258. var fullPath = cc.FileUtils.getInstance().fullPathForFilename(textureKeyName);
  259. if (this._textures[fullPath])
  260. delete(this._textures[fullPath]);
  261. },
  262. // Use same function for all load image error event callback
  263. _loadErrorHandler: function(path, textureCache, removeFrom) {
  264. //remove from cache
  265. if (removeFrom[path])
  266. delete removeFrom[path];
  267. this.removeEventListener('error', textureCache._loadErrorHandler, false);
  268. },
  269. // Use same function for addImage image load event (with callback)
  270. _clientLoadHandler: function (texture, textureCache, callback, target) {
  271. if(texture instanceof cc.Texture2D)
  272. texture.handleLoadedTexture();
  273. else if(textureCache._textures[texture])
  274. textureCache._textures[texture].handleLoadedTexture();
  275. textureCache._addImageAsyncCallBack(target, callback);
  276. this.removeEventListener('load', textureCache._addAsyncLoadHandler, false);
  277. },
  278. _preloadHandler: function (texture, textureCache) {
  279. if(texture instanceof cc.Texture2D)
  280. texture.handleLoadedTexture();
  281. else if(textureCache._textures[texture])
  282. textureCache._textures[texture].handleLoadedTexture();
  283. this.removeEventListener('load', textureCache._addAsyncLoadHandler, false);
  284. },
  285. _beforeRendererLoadHandler: function (path, textureCache) {
  286. var loading = textureCache._loadingTexturesBefore;
  287. if(loading[path]) {
  288. textureCache._loadedTexturesBefore[path] = loading[path];
  289. delete loading[path];
  290. }
  291. this.removeEventListener('load', textureCache._beforeRendererLoadHandler, false);
  292. },
  293. /**
  294. * Loading the images asynchronously
  295. * @param {String} path
  296. * @param {Function} selector
  297. * @param {Object} target
  298. * @return {cc.Texture2D}
  299. * @example
  300. * //example
  301. * cc.TextureCache.getInstance().addImageAsync("hello.png", this, this.loadingCallBack);
  302. */
  303. addImageAsync:function (path, selector, target) {
  304. if(!path)
  305. throw "cc.TextureCache.addImageAsync(): path should be non-null";
  306. path = cc.FileUtils.getInstance().fullPathForFilename(path);
  307. var texture = this._textures[path];
  308. var image,that;
  309. if (texture) {
  310. if(texture.isLoaded()){
  311. this._addImageAsyncCallBack(target, selector);
  312. }else{
  313. image = texture.getHtmlElementObj();
  314. image.addEventListener("load", this._clientLoadHandler.bind(image, texture, this, selector, target));
  315. }
  316. } else {
  317. image = new Image();
  318. image.crossOrigin = "Anonymous";
  319. image.addEventListener("load", this._clientLoadHandler.bind(image, path, this, selector, target));
  320. image.addEventListener("error", this._loadErrorHandler.bind(image, path, this, this._textures));
  321. image.src = path;
  322. var texture2d = new cc.Texture2D();
  323. texture2d.initWithElement(image);
  324. this._textures[path] = texture2d;
  325. }
  326. return this._textures[path];
  327. },
  328. _addImageBeforeRenderer:function(path){
  329. var texture = new Image();
  330. texture.crossOrigin = "Anonymous";
  331. texture.addEventListener("load", this._beforeRendererLoadHandler.bind(texture, path, this));
  332. texture.addEventListener("error", this._loadErrorHandler.bind(texture, path, this, this._loadingTexturesBefore));
  333. texture.src = path;
  334. this._loadingTexturesBefore[path] = texture;
  335. },
  336. /**
  337. * <p>Returns a Texture2D object given an file image <br />
  338. * If the file image was not previously loaded, it will create a new Texture2D <br />
  339. * object and it will return it. It will use the filename as a key.<br />
  340. * Otherwise it will return a reference of a previously loaded image. <br />
  341. * Supported image extensions: .png, .jpg, .gif</p>
  342. * @param {String} path
  343. * @return {cc.Texture2D}
  344. * @example
  345. * //example
  346. * cc.TextureCache.getInstance().addImage("hello.png");
  347. */
  348. addImage:function (path) {
  349. if(!path)
  350. throw "cc.Texture.addImage(): path should be non-null";
  351. if(cc.renderContextType === cc.WEBGL){
  352. if (!this._rendererInitialized)
  353. return this._addImageBeforeRenderer(path);
  354. }
  355. path = cc.FileUtils.getInstance().fullPathForFilename(path);
  356. var texture = this._textures[path];
  357. var image;
  358. if (texture) {
  359. if (!texture.isLoaded()) {
  360. image = texture.getHtmlElementObj();
  361. image.addEventListener("load", this._preloadHandler.bind(image, texture, this));
  362. }
  363. } else {
  364. image = new Image();
  365. image.crossOrigin = "Anonymous";
  366. image.addEventListener("load", this._preloadHandler.bind(image, path, this));
  367. image.addEventListener("error", this._loadErrorHandler.bind(image, path, this, this._textures));
  368. image.src = path;
  369. var texture2d = new cc.Texture2D();
  370. texture2d.initWithElement(image);
  371. this._textures[path] = texture2d;
  372. }
  373. return this._textures[path];
  374. },
  375. /**
  376. * Cache the image data
  377. * @param {String} path
  378. * @param {Image|HTMLImageElement|HTMLCanvasElement} texture
  379. */
  380. cacheImage:function (path, texture) {
  381. if(texture instanceof cc.Texture2D){
  382. this._textures[path] = texture;
  383. return ;
  384. }
  385. var texture2d = new cc.Texture2D();
  386. texture2d.initWithElement(texture);
  387. texture2d.handleLoadedTexture();
  388. this._textures[path] = texture2d;
  389. },
  390. /**
  391. * <p>Returns a Texture2D object given an UIImage image<br />
  392. * If the image was not previously loaded, it will create a new Texture2D object and it will return it.<br />
  393. * Otherwise it will return a reference of a previously loaded image<br />
  394. * The "key" parameter will be used as the "key" for the cache.<br />
  395. * If "key" is null, then a new texture will be created each time.</p>
  396. * @param {HTMLImageElement|HTMLCanvasElement} image
  397. * @param {String} key
  398. * @return {cc.Texture2D}
  399. */
  400. addUIImage:function (image, key) {
  401. if(!image)
  402. throw "cc.Texture.addUIImage(): image should be non-null";
  403. if (key) {
  404. if (this._textures[key])
  405. return this._textures[key];
  406. }
  407. // prevents overloading the autorelease pool
  408. var texture = new cc.Texture2D();
  409. texture.initWithImage(image);
  410. if ((key != null) && (texture != null))
  411. this._textures[key] = texture;
  412. else
  413. cc.log("cocos2d: Couldn't add UIImage in TextureCache");
  414. return texture;
  415. },
  416. /**
  417. * <p>Output to cc.log the current contents of this TextureCache <br />
  418. * This will attempt to calculate the size of each texture, and the total texture memory in use. </p>
  419. */
  420. dumpCachedTextureInfo:function () {
  421. var count = 0;
  422. var totalBytes = 0, locTextures = this._textures;
  423. for (var key in locTextures) {
  424. var selTexture = locTextures[key];
  425. count++;
  426. if (selTexture.getHtmlElementObj() instanceof HTMLImageElement)
  427. cc.log("cocos2d: '" + key + "' id=" + selTexture.getHtmlElementObj().src + " " + selTexture.getPixelsWide() + " x " + selTexture.getPixelsHigh());
  428. else {
  429. cc.log("cocos2d: '" + key + "' id= HTMLCanvasElement " + selTexture.getPixelsWide() + " x " + selTexture.getPixelsHigh());
  430. }
  431. totalBytes += selTexture.getPixelsWide() * selTexture.getPixelsHigh() * 4;
  432. }
  433. var locTextureColorsCache = this._textureColorsCache;
  434. for (key in locTextureColorsCache) {
  435. var selCanvasColorsArr = locTextureColorsCache[key];
  436. for (var selCanvasKey in selCanvasColorsArr){
  437. var selCanvas = selCanvasColorsArr[selCanvasKey];
  438. count++;
  439. cc.log("cocos2d: '" + key + "' id= HTMLCanvasElement " + selCanvas.width + " x " + selCanvas.height);
  440. totalBytes += selCanvas.width * selCanvas.height * 4;
  441. }
  442. }
  443. cc.log("cocos2d: TextureCache dumpDebugInfo: " + count + " textures, HTMLCanvasElement for "
  444. + (totalBytes / 1024) + " KB (" + (totalBytes / (1024.0 * 1024.0)).toFixed(2) + " MB)");
  445. }
  446. });
  447. /**
  448. * Return ths shared instance of the cache
  449. * @return {cc.TextureCache}
  450. */
  451. cc.TextureCache.getInstance = function () {
  452. if (!cc.g_sharedTextureCache)
  453. cc.g_sharedTextureCache = new cc.TextureCache();
  454. return cc.g_sharedTextureCache;
  455. };
  456. /**
  457. * Purges the cache. It releases the retained instance.
  458. */
  459. cc.TextureCache.purgeSharedTextureCache = function () {
  460. cc.g_sharedTextureCache = null;
  461. };