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 cc.TMXTiledMap = cc.Node.extend(/** @lends cc.TMXTiledMap# */{
102     //the map's size property measured in tiles
103     _mapSize:null,
104     _tileSize:null,
105     _properties:null,
106     _objectGroups:null,
107     _mapOrientation:null,
108     //tile properties
109     //todo delete
110     _TMXLayers:null,
111     _tileProperties:null,
112 
113     ctor:function(){
114         cc.Node.prototype.ctor.call(this);
115         this._mapSize = cc.SizeZero();
116         this._tileSize = cc.SizeZero();
117         this._properties = null;
118         this._objectGroups = null;
119         this._mapOrientation = null;
120         this._TMXLayers = null;
121 
122         this._tileProperties = [];
123     },
124 
125     /**
126      * @return {cc.Size}
127      */
128     getMapSize:function () {
129         return this._mapSize;
130     },
131 
132     /**
133      * @param {cc.Size} Var
134      */
135     setMapSize:function (Var) {
136         this._mapSize = Var;
137     },
138 
139     /**
140      * @return {cc.Size}
141      */
142     getTileSize:function () {
143         return this._tileSize;
144     },
145 
146     /**
147      * @param {cc.Size} Var
148      */
149     setTileSize:function (Var) {
150         this._tileSize = Var;
151     },
152 
153     /**
154      * map orientation
155      * @return {Number}
156      */
157     getMapOrientation:function () {
158         return this._mapOrientation;
159     },
160 
161     /**
162      * @param {Number} Var
163      */
164     setMapOrientation:function (Var) {
165         this._mapOrientation = Var;
166     },
167 
168     /**
169      * object groups
170      * @return {Array}
171      */
172     getObjectGroups:function () {
173         return this._objectGroups;
174     },
175 
176     /**
177      * @param {Array} Var
178      */
179     setObjectGroups:function (Var) {
180         this._objectGroups = Var;
181     },
182 
183     /**
184      * properties
185      * @return {object}
186      */
187     getProperties:function () {
188         return this._properties;
189     },
190 
191     /**
192      * @param {object} Var
193      */
194     setProperties:function (Var) {
195         this._properties = Var;
196     },
197 
198     /**
199      * @param {String} tmxFile
200      * @return {Boolean}
201      * @example
202      * //example
203      * var map = new cc.TMXTiledMap()
204      * map.initWithTMXFile("hello.tmx");
205      */
206     initWithTMXFile:function (tmxFile,resourcePath) {
207         cc.Assert(tmxFile != null && tmxFile.length > 0, "TMXTiledMap: tmx file should not be nil");
208         this.setContentSize(cc.SizeZero());
209         var mapInfo = cc.TMXMapInfo.create(tmxFile,resourcePath);
210         if (!mapInfo)
211             return false;
212 
213         cc.Assert(mapInfo.getTilesets().length != 0, "TMXTiledMap: Map not found. Please check the filename.");
214         this._buildWithMapInfo(mapInfo);
215         return true;
216     },
217 
218     initWithXML:function(tmxString, resourcePath){
219         this.setContentSize(cc.SizeZero());
220 
221         var mapInfo = cc.TMXMapInfo.createWithXML(tmxString, resourcePath);
222 
223         cc.Assert( mapInfo.getTilesets().length != 0, "TMXTiledMap: Map not found. Please check the filename.");
224         this._buildWithMapInfo(mapInfo);
225         return true;
226     },
227 
228     _buildWithMapInfo:function (mapInfo) {
229         this._mapSize = mapInfo.getMapSize();
230         this._tileSize = mapInfo.getTileSize();
231         this._mapOrientation = mapInfo.getOrientation();
232         this._objectGroups = mapInfo.getObjectGroups();
233         this._properties = mapInfo.getProperties();
234         this._tileProperties = mapInfo.getTileProperties();
235 
236         var idx = 0;
237         var layers = mapInfo.getLayers();
238         if (layers) {
239             var layerInfo = null;
240             for (var i = 0, len = layers.length; i < len; i++) {
241                 layerInfo = layers[i];
242                 if (layerInfo && layerInfo.visible) {
243                     var child = this._parseLayer(layerInfo, mapInfo);
244                     this.addChild(child, idx, idx);
245 
246                     // update content size with the max size
247                     var childSize = child.getContentSize();
248                     var currentSize = this.getContentSize();
249                     currentSize.width = Math.max(currentSize.width, childSize.width);
250                     currentSize.height = Math.max(currentSize.height, childSize.height);
251                     this.setContentSize(currentSize);
252                     idx++;
253                 }
254             }
255         }
256     },
257     /** return the TMXLayer for the specific layer
258      * @param {String} layerName
259      * @return {cc.TMXLayer}
260      */
261     getLayer:function (layerName) {
262         cc.Assert(layerName != null && layerName.length > 0, "Invalid layer name!");
263 
264         for (var i = 0; i < this._children.length; i++) {
265             var layer = this._children[i];
266             if (layer) {
267                 if (layer.getLayerName() == layerName) {
268                     return layer;
269                 }
270             }
271         }
272 
273         // layer not found
274         return null;
275     },
276 
277     /**
278      * Return the TMXObjectGroup for the secific group
279      * @param {String} groupName
280      * @return {cc.TMXObjectGroup}
281      */
282     getObjectGroup:function (groupName) {
283         cc.Assert(groupName != null && groupName.length > 0, "Invalid group name!");
284         if (this._objectGroups) {
285             for (var i = 0; i < this._objectGroups.length; i++) {
286                 var objectGroup = this._objectGroups[i];
287                 if (objectGroup && objectGroup.getGroupName() == groupName) {
288                     return objectGroup;
289                 }
290             }
291         }
292         // objectGroup not found
293         return null;
294     },
295 
296     /**
297      * Return the value for the specific property name
298      * @param {String} propertyName
299      * @return {String}
300      */
301     getProperty:function (propertyName) {
302         return this._properties[propertyName.toString()];
303     },
304 
305     /**
306      * Return properties dictionary for tile GID
307      * @param {Number} GID
308      * @return {object}
309      */
310     propertiesForGID:function (GID) {
311         return this._tileProperties[GID];
312     },
313 
314     _parseLayer:function (layerInfo, mapInfo) {
315         var tileset = this._tilesetForLayer(layerInfo, mapInfo);
316         var layer = cc.TMXLayer.create(tileset, layerInfo, mapInfo);
317         // tell the layerinfo to release the ownership of the tiles map.
318         layerInfo.ownTiles = false;
319         layer.setupTiles();
320         return layer;
321     },
322 
323     _tilesetForLayer:function (layerInfo, mapInfo) {
324         var size = layerInfo._layerSize;
325         var tilesets = mapInfo.getTilesets();
326         if (tilesets) {
327             for (var i = tilesets.length - 1; i >= 0; i--) {
328                 var tileset = tilesets[i];
329                 if (tileset) {
330                     for (var y = 0; y < size.height; y++) {
331                         for (var x = 0; x < size.width; x++) {
332                             var pos = x + size.width * y;
333                             var gid = layerInfo._tiles[pos];
334                             if (gid != 0) {
335                                 // Optimization: quick return
336                                 // if the layer is invalid (more than 1 tileset per layer) an cc.Assert will be thrown later
337                                 if (((gid & cc.TMX_TILE_FLIPPED_MASK)>>>0) >= tileset.firstGid) {
338                                     return tileset;
339                                 }
340                             }
341 
342                         }
343                     }
344                 }
345             }
346         }
347 
348         // If all the tiles are 0, return empty tileset
349         cc.log("cocos2d: Warning: TMX Layer " + layerInfo.name + " has no tiles");
350         return null;
351     }
352 });
353 
354 /**
355  * Creates a TMX Tiled Map with a TMX file.
356  * Implementation cc.TMXTiledMap
357  * @param {String} tmxFile
358  * @param {String} resourcePath
359  * @return {cc.TMXTiledMap|undefined}
360  * @example
361  * //example
362  * var map = cc.TMXTiledMap.create("hello.tmx");
363  */
364 cc.TMXTiledMap.create = function (tmxFile, resourcePath) {
365     var ret = new cc.TMXTiledMap();
366     if (ret.initWithTMXFile(tmxFile,resourcePath)) {
367         return ret;
368     }
369     return null;
370 };
371 
372 /**
373  * initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources
374  * @param {String} tmxString
375  * @param {String} resourcePath
376  * @return {cc.TMXTiledMap|undefined}
377  */
378 cc.TMXTiledMap.createWithXML = function(tmxString, resourcePath){
379     var tileMap = new cc.TMXTiledMap();
380     if(tileMap.initWithXML(tmxString,resourcePath))
381         return tileMap;
382     return null;
383 };
384