1 /****************************************************************************
  2  Copyright (c) 2008-2010 Ricardo Quesada
  3  Copyright (c) 2011-2012 cocos2d-x.org
  4  Copyright (c) 2013-2014 Chukong Technologies Inc.
  5 
  6  http://www.cocos2d-x.org
  7 
  8  Permission is hereby granted, free of charge, to any person obtaining a copy
  9  of this software and associated documentation files (the "Software"), to deal
 10  in the Software without restriction, including without limitation the rights
 11  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 12  copies of the Software, and to permit persons to whom the Software is
 13  furnished to do so, subject to the following conditions:
 14 
 15  The above copyright notice and this permission notice shall be included in
 16  all copies or substantial portions of the Software.
 17 
 18  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 19  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 20  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 21  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 22  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 23  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 24  THE SOFTWARE.
 25  ****************************************************************************/
 26 
 27 /**
 28  * <p>
 29  * cc.spriteFrameCache is a singleton that handles the loading of the sprite frames. It saves in a cache the sprite frames.<br/>
 30  * <br/>
 31  * example<br/>
 32  * // add SpriteFrames to spriteFrameCache With File<br/>
 33  * cc.spriteFrameCache.addSpriteFrames(s_grossiniPlist);<br/>
 34  * </p>
 35  * @class
 36  * @name cc.spriteFrameCache
 37  */
 38 cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
 39     _CCNS_REG1 : /^\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*$/,
 40     _CCNS_REG2 : /^\s*\{\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*,\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*\}\s*$/,
 41 
 42     _spriteFrames: {},
 43     _spriteFramesAliases: {},
 44     _frameConfigCache : {},
 45 
 46     _rectFromString :  function (content) {
 47         var result = this._CCNS_REG2.exec(content);
 48         if(!result) return cc.rect(0, 0, 0, 0);
 49         return cc.rect(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]), parseFloat(result[4]));
 50     },
 51 
 52     _pointFromString : function (content) {
 53         var result = this._CCNS_REG1.exec(content);
 54         if(!result) return cc.p(0,0);
 55         return cc.p(parseFloat(result[1]), parseFloat(result[2]));
 56     },
 57 
 58     _sizeFromString : function (content) {
 59         var result = this._CCNS_REG1.exec(content);
 60         if(!result) return cc.size(0, 0);
 61         return cc.size(parseFloat(result[1]), parseFloat(result[2]));
 62     },
 63 
 64     _getFrameConfig : function(url){
 65         var dict = cc.loader.getRes(url);
 66 
 67         cc.assert(dict, cc._LogInfos.spriteFrameCache__getFrameConfig_2, url);
 68 
 69         cc.loader.release(url);//release it in loader
 70         if(dict._inited){
 71             this._frameConfigCache[url] = dict;
 72             return dict;
 73         }
 74         this._frameConfigCache[url] = this._parseFrameConfig(dict);
 75         return this._frameConfigCache[url];
 76     },
 77 
 78     _getFrameConfigByJsonObject: function(url, jsonObject) {
 79         cc.assert(jsonObject, cc._LogInfos.spriteFrameCache__getFrameConfig_2, url);
 80         this._frameConfigCache[url] = this._parseFrameConfig(jsonObject);
 81         return this._frameConfigCache[url];
 82     },
 83 
 84     _parseFrameConfig: function(dict) {
 85         var tempFrames = dict["frames"], tempMeta = dict["metadata"] || dict["meta"];
 86         var frames = {}, meta = {};
 87         var format = 0;
 88         if(tempMeta){//init meta
 89             var tmpFormat = tempMeta["format"];
 90             format = (tmpFormat.length <= 1) ? parseInt(tmpFormat) : tmpFormat;
 91             meta.image = tempMeta["textureFileName"] || tempMeta["textureFileName"] || tempMeta["image"];
 92         }
 93         for (var key in tempFrames) {
 94             var frameDict = tempFrames[key];
 95             if(!frameDict) continue;
 96             var tempFrame = {};
 97 
 98             if (format == 0) {
 99                 tempFrame.rect = cc.rect(frameDict["x"], frameDict["y"], frameDict["width"], frameDict["height"]);
100                 tempFrame.rotated = false;
101                 tempFrame.offset = cc.p(frameDict["offsetX"], frameDict["offsetY"]);
102                 var ow = frameDict["originalWidth"];
103                 var oh = frameDict["originalHeight"];
104                 // check ow/oh
105                 if (!ow || !oh) {
106                     cc.log(cc._LogInfos.spriteFrameCache__getFrameConfig);
107                 }
108                 // Math.abs ow/oh
109                 ow = Math.abs(ow);
110                 oh = Math.abs(oh);
111                 tempFrame.size = cc.size(ow, oh);
112             } else if (format == 1 || format == 2) {
113                 tempFrame.rect = this._rectFromString(frameDict["frame"]);
114                 tempFrame.rotated = frameDict["rotated"] || false;
115                 tempFrame.offset = this._pointFromString(frameDict["offset"]);
116                 tempFrame.size = this._sizeFromString(frameDict["sourceSize"]);
117             } else if (format == 3) {
118                 // get values
119                 var spriteSize = this._sizeFromString(frameDict["spriteSize"]);
120                 var textureRect = this._rectFromString(frameDict["textureRect"]);
121                 if (spriteSize) {
122                     textureRect = cc.rect(textureRect.x, textureRect.y, spriteSize.width, spriteSize.height);
123                 }
124                 tempFrame.rect = textureRect;
125                 tempFrame.rotated = frameDict["textureRotated"] || false; // == "true";
126                 tempFrame.offset = this._pointFromString(frameDict["spriteOffset"]);
127                 tempFrame.size = this._sizeFromString(frameDict["spriteSourceSize"]);
128                 tempFrame.aliases = frameDict["aliases"];
129             } else {
130                 var tmpFrame = frameDict["frame"], tmpSourceSize = frameDict["sourceSize"];
131                 key = frameDict["filename"] || key;
132                 tempFrame.rect = cc.rect(tmpFrame["x"], tmpFrame["y"], tmpFrame["w"], tmpFrame["h"]);
133                 tempFrame.rotated = frameDict["rotated"] || false;
134                 tempFrame.offset = cc.p(0, 0);
135                 tempFrame.size = cc.size(tmpSourceSize["w"], tmpSourceSize["h"]);
136             }
137             frames[key] = tempFrame;
138         }
139         return {_inited: true, frames: frames, meta: meta};
140     },
141 
142     // Adds multiple Sprite Frames from a json object. it uses for local web view app.
143     _addSpriteFramesByObject: function(url, jsonObject, texture) {
144         cc.assert(url, cc._LogInfos.spriteFrameCache_addSpriteFrames_2);
145         if(!jsonObject || !jsonObject["frames"])
146             return;
147 
148         var frameConfig = this._frameConfigCache[url] || this._getFrameConfigByJsonObject(url, jsonObject);
149         //this._checkConflict(frameConfig);                             //TODO
150         this._createSpriteFrames(url, frameConfig, texture);
151     },
152 
153     _createSpriteFrames: function(url, frameConfig, texture) {
154         var frames = frameConfig.frames, meta = frameConfig.meta;
155         if(!texture){
156             var texturePath = cc.path.changeBasename(url, meta.image || ".png");
157             texture = cc.textureCache.addImage(texturePath);
158         }else if(texture instanceof cc.Texture2D){
159             //do nothing
160         }else if(cc.isString(texture)){//string
161             texture = cc.textureCache.addImage(texture);
162         }else{
163             cc.assert(0, cc._LogInfos.spriteFrameCache_addSpriteFrames_3);
164         }
165 
166         //create sprite frames
167         var spAliases = this._spriteFramesAliases, spriteFrames = this._spriteFrames;
168         for (var key in frames) {
169             var frame = frames[key];
170             var spriteFrame = spriteFrames[key];
171             if (!spriteFrame) {
172                 spriteFrame = new cc.SpriteFrame(texture, frame.rect, frame.rotated, frame.offset, frame.size);
173                 var aliases = frame.aliases;
174                 if(aliases){//set aliases
175                     for(var i = 0, li = aliases.length; i < li; i++){
176                         var alias = aliases[i];
177                         if (spAliases[alias])
178                             cc.log(cc._LogInfos.spriteFrameCache_addSpriteFrames, alias);
179                         spAliases[alias] = key;
180                     }
181                 }
182 
183                 if (cc._renderType === cc._RENDER_TYPE_CANVAS && spriteFrame.isRotated()) {
184                     //clip to canvas
185                     var locTexture = spriteFrame.getTexture();
186                     if (locTexture.isLoaded()) {
187                         var tempElement = spriteFrame.getTexture().getHtmlElementObj();
188                         tempElement = cc.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, spriteFrame.getRectInPixels());
189                         var tempTexture = new cc.Texture2D();
190                         tempTexture.initWithElement(tempElement);
191                         tempTexture.handleLoadedTexture();
192                         spriteFrame.setTexture(tempTexture);
193 
194                         var rect = spriteFrame._rect;
195                         spriteFrame.setRect(cc.rect(0, 0, rect.width, rect.height));
196                     }
197                 }
198                 spriteFrames[key] = spriteFrame;
199             }
200         }
201     },
202 
203     /**
204      * <p>
205      *   Adds multiple Sprite Frames from a plist or json file.<br/>
206      *   A texture will be loaded automatically. The texture name will composed by replacing the .plist or .json suffix with .png<br/>
207      *   If you want to use another texture, you should use the addSpriteFrames:texture method.<br/>
208      * </p>
209      * @param {String} url file path
210      * @param {HTMLImageElement|cc.Texture2D|string} texture
211      * @example
212      * // add SpriteFrames to SpriteFrameCache With File
213      * cc.spriteFrameCache.addSpriteFrames(s_grossiniPlist);
214      * cc.spriteFrameCache.addSpriteFrames(s_grossiniJson);
215      */
216     addSpriteFrames: function (url, texture) {
217         cc.assert(url, cc._LogInfos.spriteFrameCache_addSpriteFrames_2);
218 
219         //Is it a SpriteFrame plist?
220         var dict = this._frameConfigCache[url] || cc.loader.getRes(url);
221         if(!dict || !dict["frames"])
222             return;
223 
224         var frameConfig = this._frameConfigCache[url] || this._getFrameConfig(url);
225         //this._checkConflict(frameConfig);                             //TODO
226         this._createSpriteFrames(url, frameConfig, texture);
227     },
228 
229     // Function to check if frames to add exists already, if so there may be name conflit that must be solved
230     _checkConflict: function (dictionary) {
231         var framesDict = dictionary["frames"];
232 
233         for (var key in framesDict) {
234             if (this._spriteFrames[key]) {
235                 cc.log(cc._LogInfos.spriteFrameCache__checkConflict, key);
236             }
237         }
238     },
239 
240     /**
241      * <p>
242      *  Adds an sprite frame with a given name.<br/>
243      *  If the name already exists, then the contents of the old name will be replaced with the new one.
244      * </p>
245      * @param {cc.SpriteFrame} frame
246      * @param {String} frameName
247      */
248     addSpriteFrame: function (frame, frameName) {
249         this._spriteFrames[frameName] = frame;
250     },
251 
252     /**
253      * <p>
254      *   Purges the dictionary of loaded sprite frames.<br/>
255      *   Call this method if you receive the "Memory Warning".<br/>
256      *   In the short term: it will free some resources preventing your app from being killed.<br/>
257      *   In the medium term: it will allocate more resources.<br/>
258      *   In the long term: it will be the same.<br/>
259      * </p>
260      */
261     removeSpriteFrames: function () {
262         this._spriteFrames = {};
263         this._spriteFramesAliases = {};
264     },
265 
266     /**
267      * Deletes an sprite frame from the sprite frame cache.
268      * @param {String} name
269      */
270     removeSpriteFrameByName: function (name) {
271         // explicit nil handling
272         if (!name) {
273             return;
274         }
275 
276         // Is this an alias ?
277         if (this._spriteFramesAliases[name]) {
278             delete(this._spriteFramesAliases[name]);
279         }
280         if (this._spriteFrames[name]) {
281             delete(this._spriteFrames[name]);
282         }
283         // XXX. Since we don't know the .plist file that originated the frame, we must remove all .plist from the cache
284     },
285 
286     /**
287      * <p>
288      *     Removes multiple Sprite Frames from a plist file.<br/>
289      *     Sprite Frames stored in this file will be removed.<br/>
290      *     It is convinient to call this method when a specific texture needs to be removed.<br/>
291      * </p>
292      * @param {String} url Plist filename
293      */
294     removeSpriteFramesFromFile: function (url) {
295         var self = this, spriteFrames = self._spriteFrames,
296             aliases = self._spriteFramesAliases, cfg = self._frameConfigCache[url];
297         if(!cfg) return;
298         var frames = cfg.frames;
299         for (var key in frames) {
300             if (spriteFrames[key]) {
301                 delete(spriteFrames[key]);
302                 for (var alias in aliases) {//remove alias
303                     if(aliases[alias] === key) delete aliases[alias];
304                 }
305             }
306         }
307     },
308 
309     /**
310      * <p>
311      *    Removes all Sprite Frames associated with the specified textures.<br/>
312      *    It is convenient to call this method when a specific texture needs to be removed.
313      * </p>
314      * @param {HTMLImageElement|HTMLCanvasElement|cc.Texture2D} texture
315      */
316     removeSpriteFramesFromTexture: function (texture) {
317         var self = this, spriteFrames = self._spriteFrames, aliases = self._spriteFramesAliases;
318         for (var key in spriteFrames) {
319             var frame = spriteFrames[key];
320             if (frame && (frame.getTexture() === texture)) {
321                 delete(spriteFrames[key]);
322                 for (var alias in aliases) {//remove alias
323                     if(aliases[alias] === key) delete aliases[alias];
324                 }
325             }
326         }
327     },
328 
329     /**
330      * <p>
331      *   Returns an Sprite Frame that was previously added.<br/>
332      *   If the name is not found it will return nil.<br/>
333      *   You should retain the returned copy if you are going to use it.<br/>
334      * </p>
335      * @param {String} name name of SpriteFrame
336      * @return {cc.SpriteFrame}
337      * @example
338      * //get a SpriteFrame by name
339      * var frame = cc.spriteFrameCache.getSpriteFrame("grossini_dance_01.png");
340      */
341     getSpriteFrame: function (name) {
342         var self = this, frame = self._spriteFrames[name];
343         if (!frame) {
344             // try alias dictionary
345             var key = self._spriteFramesAliases[name];
346             if (key) {
347                 frame = self._spriteFrames[key.toString()];
348                 if(!frame) delete self._spriteFramesAliases[name];
349             }
350         }
351         return frame;
352     },
353 
354 	_clear: function () {
355 		this._spriteFrames = {};
356 		this._spriteFramesAliases = {};
357 		this._frameConfigCache = {};
358 	}
359 };
360