1 /****************************************************************************
  2  Copyright (c) 2010-2012 cocos2d-x.org
  3  Copyright (c) 2008-2010 Ricardo Quesada
  4  Copyright (c) 2011      Zynga 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  Orthogonal orientation
 29  * @constant
 30  * @type Number
 31  */
 32 cc.TMX_ORIENTATION_ORTHO = 0;
 33 
 34 /**
 35  * Hexagonal orientation
 36  * @constant
 37  * @type Number
 38  */
 39 
 40 cc.TMX_ORIENTATION_HEX = 1;
 41 
 42 /**
 43  * Isometric orientation
 44  * @constant
 45  * @type Number
 46  */
 47 cc.TMX_ORIENTATION_ISO = 2;
 48 
 49 /**
 50  * <p>cc.TMXTiledMap knows how to parse and render a TMX map.</p>
 51  *
 52  * <p>It adds support for the TMX tiled map format used by http://www.mapeditor.org <br />
 53  * It supports isometric, hexagonal and orthogonal tiles.<br />
 54  * It also supports object groups, objects, and properties.</p>
 55  *
 56  * <p>Features: <br />
 57  * - Each tile will be treated as an cc.Sprite<br />
 58  * - The sprites are created on demand. They will be created only when you call "layer.getTileAt(position)" <br />
 59  * - Each tile can be rotated / moved / scaled / tinted / "opacitied", since each tile is a cc.Sprite<br />
 60  * - Tiles can be added/removed in runtime<br />
 61  * - The z-order of the tiles can be modified in runtime<br />
 62  * - Each tile has an anchorPoint of (0,0) <br />
 63  * - The anchorPoint of the TMXTileMap is (0,0) <br />
 64  * - The TMX layers will be added as a child <br />
 65  * - The TMX layers will be aliased by default <br />
 66  * - The tileset image will be loaded using the cc.TextureCache <br />
 67  * - Each tile will have a unique tag<br />
 68  * - Each tile will have a unique z value. top-left: z=1, bottom-right: z=max z<br />
 69  * - Each object group will be treated as an cc.MutableArray <br />
 70  * - Object class which will contain all the properties in a dictionary<br />
 71  * - Properties can be assigned to the Map, Layer, Object Group, and Object</p>
 72  *
 73  * <p>Limitations: <br />
 74  * - It only supports one tileset per layer. <br />
 75  * - Embeded images are not supported <br />
 76  * - It only supports the XML format (the JSON format is not supported)</p>
 77  *
 78  * <p>Technical description: <br />
 79  * Each layer is created using an cc.TMXLayer (subclass of cc.SpriteBatchNode). If you have 5 layers, then 5 cc.TMXLayer will be created, <br />
 80  * unless the layer visibility is off. In that case, the layer won't be created at all. <br />
 81  * You can obtain the layers (cc.TMXLayer objects) at runtime by: <br />
 82  * - map.getChildByTag(tag_number);  // 0=1st layer, 1=2nd layer, 2=3rd layer, etc...<br />
 83  * - map.getLayer(name_of_the_layer); </p>
 84  *
 85  * <p>Each object group is created using a cc.TMXObjectGroup which is a subclass of cc.MutableArray.<br />
 86  * You can obtain the object groups at runtime by: <br />
 87  * - map.getObjectGroup(name_of_the_object_group); </p>
 88  *
 89  * <p>Each object is a cc.TMXObject.</p>
 90  *
 91  * <p>Each property is stored as a key-value pair in an cc.MutableDictionary.<br />
 92  * You can obtain the properties at runtime by: </p>
 93  *
 94  * <p>map.getProperty(name_of_the_property); <br />
 95  * layer.getProperty(name_of_the_property); <br />
 96  * objectGroup.getProperty(name_of_the_property); <br />
 97  * object.getProperty(name_of_the_property);</p>
 98  * @class
 99  * @extends cc.Node
100  *
101  * @property {Array}    properties      - Properties from the map. They can be added using tilemap editors
102  * @property {Number}   mapOrientation  - Map orientation
103  * @property {Array}    objectGroups    - Object groups of the map
104  * @property {Number}   mapWidth        - Width of the map
105  * @property {Number}   mapHeight       - Height of the map
106  * @property {Number}   tileWidth       - Width of a tile
107  * @property {Number}   tileHeight      - Height of a tile
108  */
109 cc.TMXTiledMap = cc.NodeRGBA.extend(/** @lends cc.TMXTiledMap# */{
110 	properties: null,
111 	mapOrientation: null,
112 	objectGroups: null,
113 
114     //the map's size property measured in tiles
115     _mapSize: null,
116     _tileSize: null,
117     //tile properties
118     _tileProperties: null,
119     _className: "TMXTiledMap",
120 
121     ctor:function(){
122         cc.Node.prototype.ctor.call(this);
123         this._mapSize = cc.size(0, 0);
124         this._tileSize = cc.size(0, 0);
125     },
126 
127     /**
128      * @return {cc.Size}
129      */
130     getMapSize:function () {
131         return cc.size(this._mapSize.width, this._mapSize.height);
132     },
133 
134     /**
135      * @param {cc.Size} Var
136      */
137     setMapSize:function (Var) {
138         this._mapSize.width = Var.width;
139         this._mapSize.height = Var.height;
140     },
141 
142 	_getMapWidth: function () {
143 		return this._mapSize.width;
144 	},
145 	_setMapWidth: function (width) {
146 		this._mapSize.width = width;
147 	},
148 	_getMapHeight: function () {
149 		return this._mapSize.height;
150 	},
151 	_setMapHeight: function (height) {
152 		this._mapSize.height = height;
153 	},
154 
155     /**
156      * @return {cc.Size}
157      */
158     getTileSize:function () {
159         return cc.size(this._tileSize.width, this._tileSize.height);
160     },
161 
162     /**
163      * @param {cc.Size} Var
164      */
165     setTileSize:function (Var) {
166         this._tileSize.width = Var.width;
167         this._tileSize.height = Var.height;
168     },
169 
170 	_getTileWidth: function () {
171 		return this._tileSize.width;
172 	},
173 	_setTileWidth: function (width) {
174 		this._tileSize.width = width;
175 	},
176 	_getTileHeight: function () {
177 		return this._tileSize.height;
178 	},
179 	_setTileHeight: function (height) {
180 		this._tileSize.height = height;
181 	},
182 
183     /**
184      * map orientation
185      * @return {Number}
186      */
187     getMapOrientation:function () {
188         return this.mapOrientation;
189     },
190 
191     /**
192      * @param {Number} Var
193      */
194     setMapOrientation:function (Var) {
195         this.mapOrientation = Var;
196     },
197 
198     /**
199      * object groups
200      * @return {Array}
201      */
202     getObjectGroups:function () {
203         return this.objectGroups;
204     },
205 
206     /**
207      * @param {Array} Var
208      */
209     setObjectGroups:function (Var) {
210         this.objectGroups = Var;
211     },
212 
213     /**
214      * properties
215      * @return {object}
216      */
217     getProperties:function () {
218         return this.properties;
219     },
220 
221     /**
222      * @param {object} Var
223      */
224     setProperties:function (Var) {
225         this.properties = Var;
226     },
227 
228     /**
229      * @param {String} tmxFile
230      * @return {Boolean}
231      * @example
232      * //example
233      * var map = new cc.TMXTiledMap()
234      * map.initWithTMXFile("hello.tmx");
235      */
236     initWithTMXFile:function (tmxFile) {
237         if(!tmxFile || tmxFile.length == 0)
238             throw "cc.TMXTiledMap.initWithTMXFile(): tmxFile should be non-null or non-empty string.";
239 	    this.width = 0;
240 	    this.height = 0;
241         var mapInfo = cc.TMXMapInfo.create(tmxFile);
242         if (!mapInfo)
243             return false;
244 
245         var locTilesets = mapInfo.getTilesets();
246         if(!locTilesets || locTilesets.length === 0)
247             cc.log("cc.TMXTiledMap.initWithTMXFile(): Map not found. Please check the filename.");
248         this._buildWithMapInfo(mapInfo);
249         return true;
250     },
251 
252     initWithXML:function(tmxString, resourcePath){
253         this.width = 0;
254 	    this.height = 0;
255 
256         var mapInfo = cc.TMXMapInfo.create(tmxString, resourcePath);
257         var locTilesets = mapInfo.getTilesets();
258         if(!locTilesets || locTilesets.length === 0)
259             cc.log("cc.TMXTiledMap.initWithXML(): Map not found. Please check the filename.");
260         this._buildWithMapInfo(mapInfo);
261         return true;
262     },
263 
264     _buildWithMapInfo:function (mapInfo) {
265         this._mapSize = mapInfo.getMapSize();
266         this._tileSize = mapInfo.getTileSize();
267         this.mapOrientation = mapInfo.orientation;
268         this.objectGroups = mapInfo.getObjectGroups();
269         this.properties = mapInfo.properties;
270         this._tileProperties = mapInfo.getTileProperties();
271 
272         var idx = 0;
273         var layers = mapInfo.getLayers();
274         if (layers) {
275             var layerInfo = null;
276             for (var i = 0, len = layers.length; i < len; i++) {
277                 layerInfo = layers[i];
278                 if (layerInfo && layerInfo.visible) {
279                     var child = this._parseLayer(layerInfo, mapInfo);
280                     this.addChild(child, idx, idx);
281                     // update content size with the max size
282 	                this.width = Math.max(this.width, child.width);
283 	                this.height = Math.max(this.height, child.height);
284                     idx++;
285                 }
286             }
287         }
288     },
289 
290     allLayers: function () {
291         var retArr = [], locChildren = this._children;
292         for(var i = 0, len = locChildren.length;i< len;i++){
293             var layer = locChildren[i];
294             if(layer && layer instanceof cc.TMXLayer)
295                 retArr.push(layer);
296         }
297         return retArr;
298     },
299 
300     /**
301      * return the TMXLayer for the specific layer
302      * @param {String} layerName
303      * @return {cc.TMXLayer}
304      */
305     getLayer:function (layerName) {
306         if(!layerName || layerName.length === 0)
307             throw "cc.TMXTiledMap.getLayer(): layerName should be non-null or non-empty string.";
308         var locChildren = this._children;
309         for (var i = 0; i < locChildren.length; i++) {
310             var layer = locChildren[i];
311             if (layer && layer.layerName == layerName)
312                 return layer;
313         }
314         // layer not found
315         return null;
316     },
317 
318     /**
319      * Return the TMXObjectGroup for the specific group
320      * @param {String} groupName
321      * @return {cc.TMXObjectGroup}
322      */
323     getObjectGroup:function (groupName) {
324         if(!groupName || groupName.length === 0)
325             throw "cc.TMXTiledMap.getObjectGroup(): groupName should be non-null or non-empty string.";
326         if (this.objectGroups) {
327             for (var i = 0; i < this.objectGroups.length; i++) {
328                 var objectGroup = this.objectGroups[i];
329                 if (objectGroup && objectGroup.groupName == groupName) {
330                     return objectGroup;
331                 }
332             }
333         }
334         // objectGroup not found
335         return null;
336     },
337 
338     /**
339      * Return the value for the specific property name
340      * @param {String} propertyName
341      * @return {String}
342      */
343     getProperty:function (propertyName) {
344         return this.properties[propertyName.toString()];
345     },
346 
347     /**
348      * Return properties dictionary for tile GID
349      * @param {Number} GID
350      * @return {object}
351      */
352     propertiesForGID:function (GID) {
353         return this._tileProperties[GID];
354     },
355 
356     _parseLayer:function (layerInfo, mapInfo) {
357         var tileset = this._tilesetForLayer(layerInfo, mapInfo);
358         var layer = cc.TMXLayer.create(tileset, layerInfo, mapInfo);
359         // tell the layerinfo to release the ownership of the tiles map.
360         layerInfo.ownTiles = false;
361         layer.setupTiles();
362         return layer;
363     },
364 
365     _tilesetForLayer:function (layerInfo, mapInfo) {
366         var size = layerInfo._layerSize;
367         var tilesets = mapInfo.getTilesets();
368         if (tilesets) {
369             for (var i = tilesets.length - 1; i >= 0; i--) {
370                 var tileset = tilesets[i];
371                 if (tileset) {
372                     for (var y = 0; y < size.height; y++) {
373                         for (var x = 0; x < size.width; x++) {
374                             var pos = x + size.width * y;
375                             var gid = layerInfo._tiles[pos];
376                             if (gid != 0) {
377                                 // Optimization: quick return
378                                 // if the layer is invalid (more than 1 tileset per layer) an cc.assert will be thrown later
379                                 if (((gid & cc.TMX_TILE_FLIPPED_MASK)>>>0) >= tileset.firstGid) {
380                                     return tileset;
381                                 }
382                             }
383 
384                         }
385                     }
386                 }
387             }
388         }
389 
390         // If all the tiles are 0, return empty tileset
391         cc.log("cocos2d: Warning: TMX Layer " + layerInfo.name + " has no tiles");
392         return null;
393     }
394 });
395 
396 window._p = cc.TMXTiledMap.prototype;
397 
398 // Extended properties
399 /** @expose */
400 _p.mapWidth;
401 cc.defineGetterSetter(_p, "mapWidth", _p._getMapWidth, _p._setMapWidth);
402 /** @expose */
403 _p.mapHeight;
404 cc.defineGetterSetter(_p, "mapHeight", _p._getMapHeight, _p._setMapHeight);
405 /** @expose */
406 _p.tileWidth;
407 cc.defineGetterSetter(_p, "tileWidth", _p._getTileWidth, _p._setTileWidth);
408 /** @expose */
409 _p.tileHeight;
410 cc.defineGetterSetter(_p, "tileHeight", _p._getTileHeight, _p._setTileHeight);
411 
412 delete window._p;
413 
414 /**
415  * Creates a TMX Tiled Map with a TMX file  or content string.
416  * Implementation cc.TMXTiledMap
417  * @param {String} tmxFile tmxFile fileName or content string
418  * @param {String} resourcePath   If tmxFile is a file name ,it is not required.If tmxFile is content string ,it is must required.
419  * @return {cc.TMXTiledMap|undefined}
420  * @example
421  * //example
422  * 1.
423  * //create a TMXTiledMap with file name
424  * var tmxTiledMap = cc.TMXTiledMap.create("res/orthogonal-test1.tmx");
425  * 2.
426  * //create a TMXTiledMap with content string and resource path
427  * var resources = "res/TileMaps";
428  * var filePath = "res/TileMaps/orthogonal-test1.tmx";
429  * var xmlStr = cc.loader.getRes(filePath);
430  * var tmxTiledMap = cc.TMXTiledMap.create(xmlStr, resources);
431  */
432 cc.TMXTiledMap.create = function (tmxFile,resourcePath) {
433     var tileMap = new cc.TMXTiledMap();
434     if(resourcePath){
435         if(tileMap.initWithXML(tmxFile,resourcePath))
436             return tileMap;
437     }else{
438         if (tileMap.initWithTMXFile(tmxFile)) {
439             return tileMap;
440         }
441     }
442     return null;
443 };
444