-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtiledmapbuilder.js
381 lines (337 loc) · 10.9 KB
/
tiledmapbuilder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/**@
* #TiledMapBuilder
* @category Graphics
* A Tiled map (http://mapeditor.org) importer for Crafty.js ( http://craftyjs.com)
* It creates a tiled world or view on the basis of exported JSON file from Tiled Map Editor.
* It also provides methods to access to tiles, layers, tilesets, rendering views of map, lazy loading,...
*
* @see http://www.mapeditor.org/ - Tiled Map Editor
* @author Tomas Jurman ([email protected])
*/
Crafty.c("TiledMapBuilder", {
tileMapBuilderSetting: {
USE_WEB_WORKERS :false,
PATH_TO_WORKER_SCRIPT :'../../modules/create_mocks_module.js',
RENDER_METHOD_CANVAS :'Canvas',
RENDER_METHOD_DOM :'DOM',
},
_renderMethod: null,
_isometric:null,
_layers: null,
_callback:null,
init: function() {
this._renderMethod = this.has(this.tileMapBuilderSetting.RENDER_METHOD_CANVAS) ?
this.tileMapBuilderSetting.RENDER_METHOD_CANVAS :
this.tileMapBuilderSetting.RENDER_METHOD_DOM;
return this;
},
/**@
* #TiledMapBuilder.setMapDataSource
* Set a data source for tiled map.
*
* @param {Object} source - object from JSON file exported by Tiled Map Editor
* @throws {Error} - when source is not valid
* @return {Object} this
*
* @see http://www.mapeditor.org/ - Tiled Map Editor, export to JSON
*/
setMapDataSource:function( source ){
if(!this.isValid(source)){
throw new Error("Source is not valid.");
}
this._source = source;
if( this.isIsometric() ){
this.setIsometric( source );
}
this.createTiles( source );
return this;
},
/**@
* #TiledMapBuilder.createWorld
* Renders a tiled world based on the source file.
*
* @param {Function} callback - callback function call when world is done
* @return {Object} this
*/
createWorld: function( callback ) {
return this.createView( 0, 0, this._source.width, this._source.height, callback );
},
/**@
* #TiledMapBuilder.createView
* Renders a tiled view based on the source file.
*
* @param {Integer} startRow - start row, start from 0 to N
* @param {Integer} startColumn - start column, start from 0 to N
* @param {Integer} viewWidth - view width in tiles
* @param {Integer} viewHeight - view height in tiles
* @param {Function} callback - callback function call when world is done
* @return {Object} this
*/
createView: function( startRow, startColumn, viewWidth, viewHeight, callback ){
this._callback = callback;
if( this.tileMapBuilderSetting.USE_WEB_WORKERS && typeof(Worker)!=="undefined"){
this.doInBackground({startRow:startRow, startColumn:startColumn, viewWidth:viewWidth, viewHeight:viewHeight, renderMethod:this._renderMethod, source:this._source});
}else{
// Do not forget attach module: <script src="path/to/create_mocks_module.js"></script>
MockModule.init( startRow, startColumn, viewWidth, viewHeight, this._renderMethod, this._source );
this._layers = this.createEntitiesFromMock( MockModule.createMockEntities() );
this.fireCallback();
}
return this;
},
/**@
* #TiledMapBuilder.lazyLoadingForEntity
* Is rendering a lazy tiled views based on the player entity.
*
* @param {Object} entity, Crafty.e
* @return {Object} this
*/
lazyLoadingForEntity: function( entity ){
new Error("NotSupportedException");
},
/**@
* #TiledMapBuilder.getLayer
* Contains all tiles as Crafty.entity in layer
*
* @param {String} layerName - name of layer, The name will be defined in the Tiled Map Editor
* @return {Array} entities
*
* @see http://www.mapeditor.org/ - Tiled Map Editor
*/
getEntitiesInLayer:function( layerName ){
if(!this.isLayer( layerName )){
return null;
}
var entities = [];
for( var idx = 0; idx < this._layers[layerName].length; idx++){
if( this._layers[layerName][idx] != 0 ){
entities.push( this._layers[layerName][idx] );
};
}
return entities;
},
/**@
* #TiledMapBuilder.getTile
*
* @param String layerName - number of layer
* @param Integer row - number of row from tiled matrix, range: 0-n
* @param Integer column - number of column from tiled matrix, range: 0-n
* @return Object<Crafty.e> tile
*/
getTile: function( row, column, layerName ){
if(!this.isLayer( layerName )){
return null;
}
return this._layers[layerName][MockModule.getTileIndex( row, column, this.getLayerFromSource(layerName))];
},
/**@
* #TiledMapBuilder.getLayers
* Object with layerNames as key and Array of loaded Entities as value
* Key - layerName
* Value - Array<Etities>
*
* @return {Object} layers
*/
getLayers: function(){
return this._layers;
},
/**@
* #TiledMapBuilder.getRenderMethod
*
* @example
* RenderMethod depends on parent Entity:
* ~~~
* Crafty.e("2D, Canvas, TiledMapBuilder")
* return -> Canvas
*
* Crafty.e("2D, DOM, TiledMapBuilder")
* return -> DOM
* ~~~
*
* @return String renderMethod - DOM or Canvas
*/
getRenderMethod: function(){
return this._renderMethod;
},
/**@
* #TiledMapBuilder.getSource
*
* @return Object source
* @see TiledMap.load
*/
getSource: function(){
return this._source;
},
/**@
* #TiledMapBuilder.getIsometric
*
* @return Object Crafty.isometric or null if map is not isometric
*
* @see http://craftyjs.com/api/Crafty-isometric.html
*/
getIsometric:function(){
return this._isometric;
},
/**@
* #TiledMapBuilder.isIsometric
*
* @return boolean true or false
*/
isIsometric:function(){
return this._source.orientation == MockModule.settings.ISOMETRIC_DIAMOND ||
this._source.orientation == MockModule.settings.ISOMETRIC_STAGGERED;
},
/**@
* #TiledMapBuilder.getOrientation
* Map orientation.
*
* @return {String} (orthogonal || isometric || staggered)
*/
getOrientation:function(){
return this._source.orientation;
},
/*
* Validate source object
*
* @param {Object} source - object from JSON file exported by Tiled Map Editor
* @return {boolean} true or false
*/
isValid: function( source ){
var isValid = true;
if(!source || // is not undefined
!(source.width && source.height) || // has width and height property
!(source.layers && source.layers.length >=1) || // has no empty layer property
!(source.tilesets && source.tilesets.length >=1)){ // has no empty tilesets property
isValid = false;
}
return isValid;
},
/*
* Create Crafty.sprite() for each source image
*
* @param {Object} source - object from JSON file exported by Tiled Map Editor
* @return {Object} this
*/
createTiles: function( source ){
for(var idx = 0; idx < source.tilesets.length; idx++ ){
this.createSprite( source.tilesets[idx] );
};
},
/*
* Create Crafty.sprite() from tileset
*
* @param {Object} tileset
* @return {Object} Crafty.sprite()
*
* @see http://craftyjs.com/api/Crafty-sprite.html - Crafty.sprite() documentation
*/
createSprite:function( tileset ){
return Crafty.sprite(tileset.tilewidth, tileset.tileheight, tileset.image, this.arrangeTiles( tileset ), tileset.margin, tileset.margin);
},
/*
* Create tiles map from tileset
* Every tile´s name is: 'Tile' + index
*
* @param {Object} tileset
* @return {Object} map - {tile1:[posX, posY], tile2:[posX, posY], ...}
*/
arrangeTiles:function(tileset){
var numberOfColumns = Math.round(tileset.imagewidth / (tileset.tilewidth+tileset.margin));
var numberOfRows = Math.round(tileset.imageheight / (tileset.tileheight+tileset.margin));
var tilesMap = {};
for(var row = 0; row < numberOfRows; row++ ){
for( var column = 0; column < numberOfColumns; column++ ){
var name = "Tile" + ((parseInt(tileset.firstgid) + column) + (numberOfColumns * row ));
tilesMap[name] = [column, row];
};
}
return tilesMap;
},
/*
* #TiledMapBuilder.setIsometric
* Create Crafty.isometric object and set it as private field.
*
* @param {Object} source - object from JSON file exported by Tiled Map Editor
*/
setIsometric:function( source ){
this._isometric = Crafty.isometric.size(source.tilewidth, source.tileheight);
},
/*
* Create Crafty.entities from mock
*
* @param {Object} mockEntities, keys are layerName, contains MockObject or 0
* @return {Object} entities, {layer1Name:entities, layer2Name: entities, ...}
*/
createEntitiesFromMock:function( mockEntities ){ //TODO - refactor method
var layers = {};
var isIsometric = this.isIsometric();
var isometric = this.getIsometric();
for (var layer in mockEntities) {
layers[layer] = [];
for(var idx = 0; idx < mockEntities[layer].length; idx++ ){
var mockEntity = mockEntities[layer][idx];
if( mockEntity == 0 ){
layers[layer].push(0);
}else{
var entity = Crafty.e( mockEntity.head ).attr({ x:mockEntity.x, y:mockEntity.y });
if( isIsometric ){
isometric.place( entity.x, entity.y, 0, entity);
}
layers[layer].push( entity );
}
}
}
return layers;
},
/*
* Determine if layer with layerName exists
*
* @param String layerName
* @return boolean
*/
isLayer: function( layerName){
return this._layers[layerName] ? true : false;
},
/*
* Get Layer object from source object
* Source object is object from JSON file exported by Tiled Map Editor
*
* @param {String} layerName
* @return {Object} layer
*/
getLayerFromSource:function(layerName){
for(var idx = 0; idx < this._source.layers.length; idx++){
if(this._source.layers[idx].name == layerName){
return this._source.layers[idx];
break;
}
}
return null;
},
/*
* Do task in background thread
*
* @param {Object} data, {startRow:startRow, startColumn:startColumn, viewWidth:viewWidth, viewHeight:viewHeight, renderMethod:renderMethod, source:source}
* @param {Function} callback - callback function call when world is done
*/
doInBackground:function( data ){
var self = this;
var worker = new Worker(this.tileMapBuilderSetting.PATH_TO_WORKER_SCRIPT);
worker.postMessage(data);
worker.onmessage = function (e) {
self._layers = self.createEntitiesFromMock( e.data );
self.fireCallback();
};
worker.onerror = function(error) {
throw error;
};
},
/*
* It fires defined callback function
*/
fireCallback: function(){
if(typeof this._callback != 'undefined'){
this._callback.call(this, this);
}
},
});