CCSpriteFrameCache.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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. * Singleton that handles the loading of the sprite frames. It saves in a cache the sprite frames.
  24. * @class
  25. * @extends cc.Class
  26. * @example
  27. * // add SpriteFrames to SpriteFrameCache With File
  28. * cc.SpriteFrameCache.getInstance().addSpriteFrames(s_grossiniPlist);
  29. */
  30. cc.SpriteFrameCache = cc.Class.extend(/** @lends cc.SpriteFrameCache# */{
  31. _spriteFrames: null,
  32. _spriteFramesAliases: null,
  33. _loadedFileNames: null,
  34. /**
  35. * Constructor
  36. */
  37. ctor: function () {
  38. this._spriteFrames = {};
  39. this._spriteFramesAliases = {};
  40. this._loadedFileNames = [];
  41. },
  42. /**
  43. * Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames.
  44. * @param {object} dictionary
  45. * @param {cc.Texture2D} texture
  46. */
  47. _addSpriteFramesWithDictionary: function (dictionary, texture) {
  48. var metadataDict = dictionary["metadata"] || dictionary["meta"];
  49. var framesDict = dictionary["frames"];
  50. var format = 0;
  51. // get the format
  52. if (metadataDict) {
  53. var tmpFormat = metadataDict["format"];
  54. format = (tmpFormat.length <= 1) ? parseInt(tmpFormat) : tmpFormat;
  55. }
  56. // check the format
  57. if (format < 0 || format > 3) {
  58. cc.log("format is not supported for cc.SpriteFrameCache.addSpriteFramesWithDictionary");
  59. return;
  60. }
  61. for (var key in framesDict) {
  62. var frameDict = framesDict[key];
  63. if (frameDict) {
  64. var spriteFrame = this._spriteFrames[key];
  65. if (spriteFrame) {
  66. continue;
  67. }
  68. if (format == 0) {
  69. var x = parseFloat(frameDict["x"]);
  70. var y = parseFloat(frameDict["y"]);
  71. var w = parseFloat(frameDict["width"]);
  72. var h = parseFloat(frameDict["height"]);
  73. var ox = parseFloat(frameDict["offsetX"]);
  74. var oy = parseFloat(frameDict["offsetY"]);
  75. var ow = parseInt(frameDict["originalWidth"]);
  76. var oh = parseInt(frameDict["originalHeight"]);
  77. // check ow/oh
  78. if (!ow || !oh) {
  79. cc.log("cocos2d: WARNING: originalWidth/Height not found on the cc.SpriteFrame. AnchorPoint won't work as expected. Regenrate the .plist");
  80. }
  81. // Math.abs ow/oh
  82. ow = Math.abs(ow);
  83. oh = Math.abs(oh);
  84. // create frame
  85. spriteFrame = cc.SpriteFrame.createWithTexture(texture, cc.rect(x, y, w, h), false, cc.p(ox, oy), cc.size(ow, oh));
  86. }
  87. else if (format == 1 || format == 2) {
  88. var frame = cc.RectFromString(frameDict["frame"]);
  89. var rotated = false;
  90. // rotation
  91. if (format == 2) {
  92. rotated = frameDict["rotated"];// == "true";
  93. }
  94. var offset = cc.PointFromString(frameDict["offset"]);
  95. var sourceSize = cc.SizeFromString(frameDict["sourceSize"]);
  96. // create frame
  97. spriteFrame = cc.SpriteFrame.createWithTexture(texture, frame, rotated, offset, sourceSize);
  98. }
  99. else if (format == 3) {
  100. // get values
  101. var spriteSize, spriteOffset, spriteSourceSize, textureRect, textureRotated;
  102. spriteSize = cc.SizeFromString(frameDict["spriteSize"]);
  103. spriteOffset = cc.PointFromString(frameDict["spriteOffset"]);
  104. spriteSourceSize = cc.SizeFromString(frameDict["spriteSourceSize"]);
  105. textureRect = cc.RectFromString(frameDict["textureRect"]);
  106. textureRotated = frameDict["textureRotated"]; // == "true";
  107. // get aliases
  108. var aliases = frameDict["aliases"];
  109. var frameKey = key.toString();
  110. for (var aliasKey in aliases) {
  111. var alias = aliases[aliasKey];
  112. if (this._spriteFramesAliases[alias]) {
  113. cc.log("cocos2d: WARNING: an alias with name " + aliasKey + " already exists");
  114. }
  115. this._spriteFramesAliases[alias] = frameKey;
  116. }
  117. if (frameDict["spriteSize"] !== undefined) {
  118. textureRect = cc.rect(textureRect.x, textureRect.y, spriteSize.width, spriteSize.height);
  119. }
  120. //create frame
  121. spriteFrame = cc.SpriteFrame.createWithTexture(texture, textureRect, textureRotated, spriteOffset, spriteSourceSize);
  122. }
  123. else {
  124. var filename = frameDict["filename"], tmpFrame = frameDict["frame"], tmpSourceSize = frameDict["sourceSize"];
  125. var jsonFrame = cc.rect(tmpFrame.x, tmpFrame.y, tmpFrame.w, tmpFrame.h);
  126. var jsonRotated = frameDict["rotated"];
  127. var jsonOffset = cc.p(0, 0);
  128. var jsonSourceSize = cc.size(tmpSourceSize.w, tmpSourceSize.h);
  129. // create frame
  130. spriteFrame = cc.SpriteFrame.createWithTexture(texture, jsonFrame, jsonRotated, jsonOffset, jsonSourceSize);
  131. }
  132. if (cc.renderContextType === cc.CANVAS && spriteFrame.isRotated()) {
  133. //clip to canvas
  134. var locTexture = spriteFrame.getTexture();
  135. if (locTexture.isLoaded()) {
  136. var tempElement = spriteFrame.getTexture().getHtmlElementObj();
  137. tempElement = cc.cutRotateImageToCanvas(tempElement, spriteFrame.getRectInPixels());
  138. var tempTexture = new cc.Texture2D();
  139. tempTexture.initWithElement(tempElement);
  140. tempTexture.handleLoadedTexture();
  141. spriteFrame.setTexture(tempTexture);
  142. var rect = spriteFrame._rect;
  143. spriteFrame.setRect(cc.rect(0, 0, rect.width, rect.height));
  144. }
  145. }
  146. // add sprite frame
  147. var keyName = (filename != null) ? filename : key;
  148. this._spriteFrames[keyName] = spriteFrame;
  149. }
  150. }
  151. },
  152. /**
  153. * <p>
  154. * Adds multiple Sprite Frames from a plist or json file.<br/>
  155. * A texture will be loaded automatically. The texture name will composed by replacing the .plist or .json suffix with .png<br/>
  156. * If you want to use another texture, you should use the addSpriteFrames:texture method.<br/>
  157. * </p>
  158. * @param {String} filePath file path
  159. * @param {HTMLImageElement|cc.Texture2D|string} texture
  160. * @example
  161. * // add SpriteFrames to SpriteFrameCache With File
  162. * cc.SpriteFrameCache.getInstance().addSpriteFrames(s_grossiniPlist);
  163. * cc.SpriteFrameCache.getInstance().addSpriteFrames(s_grossiniJson);
  164. */
  165. addSpriteFrames: function (filePath, texture) {
  166. if (!filePath)
  167. throw "cc.SpriteFrameCache.addSpriteFrames(): plist should be non-null";
  168. var fileUtils = cc.FileUtils.getInstance(), dict;
  169. var ext = filePath.substr(filePath.lastIndexOf(".", filePath.length) + 1, filePath.length);
  170. if (ext == "plist") {
  171. var fullPath = fileUtils.fullPathForFilename(filePath);
  172. dict = fileUtils.dictionaryWithContentsOfFileThreadSafe(fullPath);
  173. } else {
  174. dict = JSON.parse(fileUtils.getTextFileData(filePath));
  175. }
  176. switch (arguments.length) {
  177. case 1:
  178. if (!cc.ArrayContainsObject(this._loadedFileNames, filePath)) {
  179. var texturePath = "";
  180. var metadataDict = dict["metadata"] || dict["meta"];
  181. if (metadataDict) {
  182. // try to read texture file name from meta data
  183. texturePath = metadataDict["textureFileName"] || metadataDict["image"];
  184. }
  185. if (texturePath != "") {
  186. // build texture path relative to plist file
  187. texturePath = fileUtils.fullPathFromRelativeFile(texturePath, filePath);
  188. } else {
  189. // build texture path by replacing file extension
  190. texturePath = filePath;
  191. // remove .xxx
  192. var startPos = texturePath.lastIndexOf(".", texturePath.length);
  193. texturePath = texturePath.substr(0, startPos);
  194. // append .png
  195. texturePath = texturePath + ".png";
  196. }
  197. var getTexture = cc.TextureCache.getInstance().addImage(texturePath);
  198. if (getTexture){
  199. this._addSpriteFramesWithDictionary(dict, getTexture);
  200. this._loadedFileNames.push(filePath);
  201. } else
  202. cc.log("cocos2d: cc.SpriteFrameCache: Couldn't load texture");
  203. }
  204. break;
  205. case 2:
  206. if (texture instanceof cc.Texture2D) {
  207. if(this._loadedFileNames.indexOf(filePath) === -1) {
  208. this._checkConflict(dict);
  209. }
  210. /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. */
  211. this._addSpriteFramesWithDictionary(dict, texture);
  212. } else {
  213. /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames.
  214. @since v0.99.5
  215. */
  216. var textureFileName = texture;
  217. if (!textureFileName)
  218. throw "cc.SpriteFrameCache.addSpriteFrames(): texture name should not be null";
  219. var gTexture = cc.TextureCache.getInstance().addImage(textureFileName);
  220. if (gTexture) {
  221. if(this._loadedFileNames.indexOf(filePath) === -1) {
  222. this._checkConflict(dict);
  223. this._loadedFileNames.push(filePath);
  224. }
  225. this._addSpriteFramesWithDictionary(dict, gTexture);
  226. } else {
  227. cc.log("cocos2d: cc.SpriteFrameCache: couldn't load texture file. File not found " + textureFileName);
  228. }
  229. }
  230. break;
  231. default:
  232. throw "Argument must be non-nil ";
  233. }
  234. },
  235. // Function to check if frames to add exists already, if so there may be name conflit that must be solved
  236. _checkConflict: function (dictionary) {
  237. var framesDict = dictionary["frames"];
  238. for (var key in framesDict) {
  239. if (this._spriteFrames[key]) {
  240. cc.log("cocos2d: WARNING: Sprite frame: "+key+" has already been added by another source, please fix name conflit");
  241. }
  242. }
  243. },
  244. /**
  245. * <p>
  246. * Adds an sprite frame with a given name.<br/>
  247. * If the name already exists, then the contents of the old name will be replaced with the new one.
  248. * </p>
  249. * @param {cc.SpriteFrame} frame
  250. * @param {String} frameName
  251. */
  252. addSpriteFrame: function (frame, frameName) {
  253. this._spriteFrames[frameName] = frame;
  254. },
  255. /**
  256. * <p>
  257. * Purges the dictionary of loaded sprite frames.<br/>
  258. * Call this method if you receive the "Memory Warning".<br/>
  259. * In the short term: it will free some resources preventing your app from being killed.<br/>
  260. * In the medium term: it will allocate more resources.<br/>
  261. * In the long term: it will be the same.<br/>
  262. * </p>
  263. */
  264. removeSpriteFrames: function () {
  265. this._spriteFrames = {};
  266. this._spriteFramesAliases = {};
  267. this._loadedFileNames.length = 0;
  268. },
  269. /**
  270. * Deletes an sprite frame from the sprite frame cache.
  271. * @param {String} name
  272. */
  273. removeSpriteFrameByName: function (name) {
  274. // explicit nil handling
  275. if (!name) {
  276. return;
  277. }
  278. // Is this an alias ?
  279. if (this._spriteFramesAliases[name]) {
  280. delete(this._spriteFramesAliases[name]);
  281. }
  282. if (this._spriteFrames[name]) {
  283. delete(this._spriteFrames[name]);
  284. }
  285. // XXX. Since we don't know the .plist file that originated the frame, we must remove all .plist from the cache
  286. this._loadedFileNames.length = 0;
  287. },
  288. /**
  289. * <p>
  290. * Removes multiple Sprite Frames from a plist file.<br/>
  291. * Sprite Frames stored in this file will be removed.<br/>
  292. * It is convinient to call this method when a specific texture needs to be removed.<br/>
  293. * </p>
  294. * @param {String} plist plist filename
  295. */
  296. removeSpriteFramesFromFile: function (plist) {
  297. var fileUtils = cc.FileUtils.getInstance();
  298. var path = fileUtils.fullPathForFilename(plist);
  299. var dict = fileUtils.dictionaryWithContentsOfFileThreadSafe(path);
  300. this._removeSpriteFramesFromDictionary(dict);
  301. //remove it from the cache
  302. if (cc.ArrayContainsObject(this._loadedFileNames, plist)) {
  303. cc.ArrayRemoveObject(this._loadedFileNames, plist);
  304. }
  305. },
  306. /**
  307. * Removes multiple Sprite Frames from Dictionary.
  308. * @param {object} dictionary SpriteFrame of Dictionary
  309. */
  310. _removeSpriteFramesFromDictionary: function (dictionary) {
  311. var framesDict = dictionary["frames"];
  312. for (var key in framesDict) {
  313. if (this._spriteFrames[key]) {
  314. delete(this._spriteFrames[key]);
  315. }
  316. }
  317. },
  318. /**
  319. * <p>
  320. * Removes all Sprite Frames associated with the specified textures.<br/>
  321. * It is convinient to call this method when a specific texture needs to be removed.
  322. * </p>
  323. * @param {HTMLImageElement|HTMLCanvasElement|cc.Texture2D} texture
  324. */
  325. removeSpriteFramesFromTexture: function (texture) {
  326. for (var key in this._spriteFrames) {
  327. var frame = this._spriteFrames[key];
  328. if (frame && (frame.getTexture() == texture)) {
  329. delete(this._spriteFrames[key]);
  330. }
  331. }
  332. },
  333. /**
  334. * <p>
  335. * Returns an Sprite Frame that was previously added.<br/>
  336. * If the name is not found it will return nil.<br/>
  337. * You should retain the returned copy if you are going to use it.<br/>
  338. * </p>
  339. * @param {String} name name of SpriteFrame
  340. * @return {cc.SpriteFrame}
  341. * @example
  342. * //get a SpriteFrame by name
  343. * var frame = cc.SpriteFrameCache.getInstance().getSpriteFrame("grossini_dance_01.png");
  344. */
  345. getSpriteFrame: function (name) {
  346. var frame;
  347. if (this._spriteFrames[name]) {
  348. frame = this._spriteFrames[name];
  349. }
  350. if (!frame) {
  351. // try alias dictionary
  352. var key;
  353. if (this._spriteFramesAliases[name]) {
  354. key = this._spriteFramesAliases[name];
  355. }
  356. if (key) {
  357. var keystr = key.toString();
  358. if (this._spriteFrames[keystr]) {
  359. frame = this._spriteFrames[keystr];
  360. }
  361. if (!frame) {
  362. cc.log("cocos2d: cc.SpriteFrameCahce: Frame " + name + " not found");
  363. }
  364. }
  365. }
  366. return frame;
  367. }
  368. });
  369. cc.s_sharedSpriteFrameCache = null;
  370. /**
  371. * Returns the shared instance of the Sprite Frame cache
  372. * @return {cc.SpriteFrameCache}
  373. */
  374. cc.SpriteFrameCache.getInstance = function () {
  375. if (!cc.s_sharedSpriteFrameCache) {
  376. cc.s_sharedSpriteFrameCache = new cc.SpriteFrameCache();
  377. }
  378. return cc.s_sharedSpriteFrameCache;
  379. };
  380. /**
  381. * Purges the cache. It releases all the Sprite Frames and the retained instance.
  382. */
  383. cc.SpriteFrameCache.purgeSharedSpriteFrameCache = function () {
  384. cc.s_sharedSpriteFrameCache = null;
  385. };