-
Notifications
You must be signed in to change notification settings - Fork 35
/
export_to_godot_tilemap.mjs
627 lines (558 loc) · 22.4 KB
/
export_to_godot_tilemap.mjs
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
import { getResPath, stringifyKeyValue, stringifyNode, splitCommaSeparated, getTilesetColumns } from './utils.mjs';
/*global tiled, TextFile */
class GodotTilemapExporter {
// noinspection DuplicatedCode
/**
* Constructs a new instance of the tilemap exporter
* @param {TileMap} map the tilemap to export
* @param {string} fileName path of the file the tilemap should be exported to
*/
constructor(map, fileName) {
this.map = map;
this.fileName = fileName;
this.tileOffset = 65536;
this.tileMapsString = "";
this.tilesetsString = "";
this.subResourcesString = "";
this.extResourceId = 0;
this.subResourceId = 0;
/**
* Tiled doesn't have tileset ID so we create a map
* Tileset name to generated tilesetId.
*/
this.tilesetsIndex = new Map();
/**
* Godot Tilemap has only one Tileset.
* Each layer is Tilemap and is mapped to a single Tileset.
* !!! Important !!
* Do not add tiles from different tilesets in single layer.
*/
this.layersToTilesetIndex = new Map();
};
write() {
this.setTilesetsString();
this.setTileMapsString();
this.writeToFile();
tiled.log(`Tilemap exported successfully to ${this.fileName}`);
}
/**
* Adds a new subresource to the genrated file
*
* @param {string} type the type of subresource
* @param {object} contentProperties key:value map of properties
* @returns {int} the created sub resource id
*/
addSubResource(type, contentProperties) {
const id = this.subResourceId++;
this.subResourcesString += `
[sub_resource type="${type}" id=${id}]
`;
for (const [key, value] of Object.entries(contentProperties)) {
if (value !== undefined) {
this.subResourcesString += stringifyKeyValue(key, value, false, false, true) + '\n';
}
}
return id;
}
/**
* Generate a string with all tilesets in the map.
* Godot supports several image textures per tileset but Tiled Editor doesn't.
* Tiled editor supports only one tile sprite image per tileset.
*/
setTilesetsString() {
// noinspection JSUnresolvedVariable
for (let index = 0; index < this.map.tilesets.length; ++index) {
// noinspection JSUnresolvedVariable
const tileset = this.map.tilesets[index];
this.extResourceId = index + 1;
this.tilesetsIndex.set(tileset.name, this.extResourceId);
// noinspection JSUnresolvedFunction
let tilesetPath = getResPath(this.map.property("projectRoot"), this.map.property("relativePath"), tileset.asset.fileName.replace('.tsx', '.tres'));
this.tilesetsString += this.getTilesetResourceTemplate(this.extResourceId, tilesetPath, "TileSet");
}
}
/**
* Creates the Tilemap nodes. One Tilemap per one layer from Tiled.
*/
setTileMapsString() {
const mode = this.map.orientation === TileMap.Isometric ? 1 : undefined
// noinspection JSUnresolvedVariable
for (let i = 0; i < this.map.layerCount; ++i) {
// noinspection JSUnresolvedFunction
let layer = this.map.layerAt(i);
this.handleLayer(layer, mode, ".");
}
}
/**
* Handle exporting a single layer
* @param {Layer} layer the target layer
* @param {number} mode the layer mode
* @param {string} layer_parent path of the parent of the layer
*/
handleLayer(layer, mode, layer_parent) {
// noinspection JSUnresolvedVariable
if (layer.isTileLayer) {
const layerData = this.getLayerData(layer);
for (let idx = 0; idx < layerData.length; idx++) {
const ld = layerData[idx];
if (!ld.isEmpty) {
let layerName = layer.name || "TileMap " + layer.id
let tilesetName = ld.tileset.name || "TileSet " + ld.tilesetID;
const tileMapName = layerName + " - " + tilesetName;
this.mapLayerToTileset(layer.name, ld.tilesetID);
this.tileMapsString += this.getTileMapTemplate(tileMapName, mode, ld.tilesetID, ld.poolIntArrayString, layer, layer_parent);
}
}
} else if (layer.isObjectLayer) {
// create layer
this.tileMapsString += stringifyNode({
name: layer.name,
type: "Node2D",
parent: layer_parent,
groups: splitCommaSeparated(layer.property("groups"))
});
// add entities
for (const object of layer.objects) {
const groups = splitCommaSeparated(object.property("groups"));
if (object.tile) {
let tilesetsIndexKey = object.tile.tileset.name + "_Image";
let textureResourceId = 0;
if (!this.tilesetsIndex.get(tilesetsIndexKey)) {
this.extResourceId = this.extResourceId + 1;
textureResourceId = this.extResourceId;
this.tilesetsIndex.set(tilesetsIndexKey, this.extResourceId);
// noinspection JSUnresolvedFunction
let tilesetPath = getResPath(this.map.property("projectRoot"), this.map.property("relativePath"), object.tile.tileset.image);
this.tilesetsString += this.getTilesetResourceTemplate(this.extResourceId, tilesetPath, "Texture");
} else {
textureResourceId = this.tilesetsIndex.get(tilesetsIndexKey);
}
let tileOffset = this.getTileOffset(object.tile.tileset, object.tile.id);
// Account for anchoring in Godot (corner vs. middle):
let objectPositionX = object.x + (object.tile.width / 2);
let objectPositionY = object.y - (object.tile.height / 2);
this.tileMapsString += stringifyNode(
{
name: object.name,
type: "Sprite",
parent: layer_parent + "/" + layer.name
},
this.merge_properties(
object.properties(),
{
position: `Vector2( ${objectPositionX}, ${objectPositionY} )`,
texture: `ExtResource( ${textureResourceId} )`,
region_enabled: true,
region_rect: `Rect2( ${tileOffset.x}, ${tileOffset.y}, ${object.tile.width}, ${object.tile.height} )`
}
),
this.meta_properties(layer.properties())
);
} else if (object.type == "Area2D" && object.width && object.height) {
// Creates an Area2D node with a rectangle shape inside
// Does not support rotation
const width = object.width / 2;
const height = object.height / 2;
const objectPositionX = object.x + width;
const objectPositionY = object.y + height;
this.tileMapsString += stringifyNode(
{
name: object.name,
type: "Area2D",
parent: layer_parent + "/" + layer.name,
groups: groups
},
this.merge_properties(
object.properties(),
{
collision_layer: object.property("collision_layer"),
collision_mask: object.property("collision_mask")
}
),
this.meta_properties(object.properties())
);
const shapeId = this.addSubResource("RectangleShape2D", {
extents: `Vector2( ${width}, ${height} )`
});
this.tileMapsString += stringifyNode(
{
name: "CollisionShape2D",
type: "CollisionShape2D",
parent: `${layer_parent}/${layer.name}/${object.name}`
},
this.merge_properties(
object.properties(),
{
shape: `SubResource( ${shapeId} )`,
position: `Vector2( ${objectPositionX}, ${objectPositionY} )`,
}
),
{}
);
} else if (object.type == "Node2D") {
this.tileMapsString += stringifyNode(
{
name: object.name,
type: "Node2D",
parent: layer_parent + "/" + layer.name,
groups: groups
},
this.merge_properties(
object.properties(),
{
position: `Vector2( ${object.x}, ${object.y} )`
}
),
this.meta_properties(object.properties())
);
}
}
} else if (layer.isGroupLayer) {
var node_type = layer.property("godot:type") || "Node2D";
this.tileMapsString += stringifyNode(
{
name: layer.name,
type: node_type,
parent: layer_parent,
groups: splitCommaSeparated(layer.property("groups"))
},
this.merge_properties(
layer.properties(),
{
}
),
this.meta_properties(layer.properties())
);
for(var i = 0; i < layer.layerCount; ++i) {
this.handleLayer(layer.layers[i], mode, layer_parent + "/" + layer.name);
}
}
}
/**
* Prepare properties for a Godot node
* @param {TiledObjectProperties} object_props Properties from the layer
* @param {TiledObjectProperties} set_props The base properties for the node
* @returns {TiledObjectProperties} the merged property set for the node
*/
merge_properties(object_props, set_props){
for (const [key, value] of Object.entries(object_props)) {
if(key.startsWith("godot:node:")){
set_props[key.substring(11)] = value;
}
}
return set_props;
}
/**
* Prepare the meta properties for a Godot node
* @param {TiledObjectProperties} object_props
* @returns {object} the meta properties
*/
meta_properties(object_props){
let results = {};
for (const [key, value] of Object.entries(object_props)) {
if(key.startsWith("godot:meta:")){
results[key.substring(11)] = value;
}
}
return results;
}
writeToFile() {
// noinspection JSUnresolvedVariable
let file = new TextFile(this.fileName, TextFile.WriteOnly);
let tileMapTemplate = this.getSceneTemplate();
file.write(tileMapTemplate);
file.commit();
}
/**
* @typedef {{
* tileset: Tileset,
* tilesetID: number?,
* tilesetColumns: number,
* layer: Layer,
* isEmpty: boolean,
* poolIntArrayString: string,
* parent: string
* }} LayerData
*/
/**
* Creates all the tiles coordinates for a layer.
* Each element in the retuned array corresponds to the tile coordinates for each of
* the tilesets used in the layer.
* @param {TileLayer} layer the target layer
* @returns {LayerData[]} the data about the tilesets used in the target layer
*/
getLayerData(layer) {
// noinspection JSUnresolvedVariable
let boundingRect = layer.region().boundingRect;
const tilesetList = [];
for (let y = boundingRect.top; y <= boundingRect.bottom; ++y) {
for (let x = boundingRect.left; x <= boundingRect.right; ++x) {
// noinspection JSUnresolvedVariable,JSUnresolvedFunction
let cell = layer.cellAt(x, y);
let tileId = cell.tileId;
let tileGodotID = tileId;
/** Check and don't export blank tiles **/
if (tileId !== -1) {
/**
* Find the tileset on the list, if not found, add
*/
const tile = layer.tileAt(x, y);
let tileset = tilesetList.find(item => item.tileset === tile.tileset);
if (!tileset) {
tileset = {
tileset: tile.tileset,
tilesetID: null,
tilesetColumns: getTilesetColumns(tile.tileset),
layer: layer,
isEmpty: tile.tileset === null,
poolIntArrayString: "",
parent: tilesetList.length === 0 ? "." : layer.name
};
tilesetList.push(tileset);
}
const tilesetColumns = tileset.tilesetColumns;
/** Handle Godot strange offset by rows in the tileset image **/
if (tileId >= tilesetColumns) {
let tileY = Math.floor(tileId / tilesetColumns);
let tileX = (tileId % tilesetColumns);
tileGodotID = tileX + (tileY * this.tileOffset);
}
/**
* Godot coordinates use an offset of 65536
* Check the README.md: Godot Tilemap Encoding & Limits
*/
let yValue = y;
let xValue = x;
if (xValue < 0) {
yValue = y + 1;
}
let firstParam = xValue + (yValue * this.tileOffset);
/**
* This is texture image form the tileset in godot
* Tiled doesn't support more than one image in tileset
* Also this is used to encode the rotation of a tile... as it seems. :P
*/
let secondParam = this.getSecondParam(cell);
tileset.poolIntArrayString += firstParam + ", " + secondParam + ", " + tileGodotID + ", ";
}
}
}
// Remove trailing commas and blank
tilesetList.forEach(i => {
i.poolIntArrayString = i.poolIntArrayString.replace(/,\s*$/, "");
});
for (let idx = 0; idx < tilesetList.length; idx++) {
const current = tilesetList[idx];
if (current.tileset !== null && current.poolIntArrayString !== "") {
current.tilesetID = this.getTilesetIDByTileset(current.tileset);
} else {
tiled.log(`Error: The layer ${layer.name} is empty and has been skipped!`);
}
}
return tilesetList;
}
/**
* Find the id of a tileset by its name
* @param {Tileset} tileset The tileset to find the id of
* @returns {string|undefined} the id of the tileset if found, undefined otherwise
*/
getTilesetIDByTileset(tileset) {
return this.tilesetsIndex.get(tileset.name);
}
/**
* Calculate the second parameter for the given cell
* @param {cell} cell the target cell
* @returns {number} the second parameter
*/
getSecondParam(cell) {
/**
* no rotation or flips
* cell.cell.flippedHorizontally is false and
* cell.cell.flippedVertically is false
* cell.cell.flippedAntiDiagonally is false
*/
let secondParam = 0;
/**
* rotated 1x left or
* rotated 3x right
*/
if (
cell.flippedHorizontally === false &&
cell.flippedVertically === true &&
cell.flippedAntiDiagonally === true
) {
secondParam = -1073741824;
}
/**
* rotated 2x left or 2x right or
* vertical and horizontal flip
*/
if (
cell.flippedHorizontally === true &&
cell.flippedVertically === true &&
cell.flippedAntiDiagonally === false
) {
secondParam = 1610612736;
}
/**
* rotated 3x left or
* rotated 1x right
*/
if (
cell.flippedHorizontally === true &&
cell.flippedVertically === false &&
cell.flippedAntiDiagonally === true
) {
secondParam = -1610612736;
}
/**
* flipped horizontal or
* flipped vertical and 2x times rotated left/right
*/
if (
cell.flippedHorizontally === true &&
cell.flippedVertically === false &&
cell.flippedAntiDiagonally === false
) {
secondParam = 536870912;
}
/**
* flipped horizontal and 1x rotated left or
* flipped vertical and 1x time rotated right
*/
if (
cell.flippedHorizontally === false &&
cell.flippedVertically === false &&
cell.flippedAntiDiagonally === true
) {
secondParam = -2147483648;
}
/**
* flipped horizontal and 2x times rotated left/right or
* flipped vertically
*/
if (
cell.flippedHorizontally === false &&
cell.flippedVertically === true &&
cell.flippedAntiDiagonally === false
) {
secondParam = 1073741824;
}
/**
* flipped horizontal and 3x rotated left or
* flipped vertically and 1x rotated left or
* flipped horizontal and 1x rotated right or
* flipped vertically and 3x rotated right
*/
if (
cell.flippedHorizontally === true &&
cell.flippedVertically === true &&
cell.flippedAntiDiagonally === true
) {
secondParam = -536870912;
}
return secondParam;
}
/**
* Calculate the X and Y offset (in pixels) for the specified tile
* ID within the specified tileset image.
*
* @param {Tileset} tileset - The full Tileset object
* @param {int} tileId - Id for the tile to extract offset for
* @returns {object} - An object with pixel offset in the format {x: int, y: int}
*/
getTileOffset(tileset, tileId) {
let columnCount = getTilesetColumns(tileset);
let row = Math.floor(tileId / columnCount);
let col = tileId % columnCount;
let xOffset = tileset.margin + (tileset.tileSpacing * col);
let yOffset = tileset.margin + (tileset.tileSpacing * row);
return {
x: (col * tileset.tileWidth) + xOffset,
y: (row * tileset.tileHeight) + yOffset
};
}
/**
* Template for a scene
* @returns {string}
*/
getSceneTemplate() {
const loadSteps = 2 + this.subResourceId;
const type = this.map.property("godot:type") || "Node2D";
const name = this.map.property("godot:name") || "Node2D";
return `[gd_scene load_steps=${loadSteps} format=2]
${this.tilesetsString}
${this.subResourcesString}
[node name="${name}" type="${type}"]
${this.tileMapsString}
`;
}
/**
* Template for a tileset resource
* @returns {string}
*/
getTilesetResourceTemplate(id, path, type) {
// Strip leading slashes to prevent invalid triple slashes in Godot res:// path:
path = path.replace(/^\/+/, '');
return `[ext_resource path="res://${path}" type="${type}" id=${id}]
`;
}
/**
* Template for a tilemap node
* @param {string} tileMapName
* @param {number} mode
* @param {number} tilesetID
* @param {string} poolIntArrayString
* @param {Layer} layer
* @param {string} parent
* @returns {string}
*/
getTileMapTemplate(tileMapName, mode, tilesetID, poolIntArrayString, layer, parent = ".") {
const groups = splitCommaSeparated(layer.property("groups"));
const zIndex = parseInt(layer.properties()['z_index'], 10);
return stringifyNode(
{
name: tileMapName,
type: "TileMap",
parent: parent,
groups: groups
},
this.merge_properties(
layer.properties(),
{
visible: layer.visible,
modulate: `Color( 1, 1, 1, ${layer.opacity} )`,
position: `Vector2( ${layer.offset.x}, ${layer.offset.y} )`,
tile_set: `ExtResource( ${tilesetID} )`,
cell_size: `Vector2( ${layer.map.tileWidth}, ${layer.map.tileHeight} )`,
cell_custom_transform: `Transform2D( 16, 0, 0, 16, 0, 0 )`,
format: 1,
mode: mode,
tile_data: `PoolIntArray( ${poolIntArrayString} )`,
z_index: typeof zIndex === 'number' && !isNaN(zIndex) ? zIndex : undefined
}
),
this.meta_properties(layer.properties())
);
}
mapLayerToTileset(layerName, tilesetID) {
this.layersToTilesetIndex[layerName] = tilesetID;
}
}
const customTileMapFormat = {
name: "Godot Tilemap format",
extension: "tscn",
/**
* Map exporter function
* @param {TileMap} map the map to export
* @param {string} fileName path of the file where to export the map
* @returns {undefined}
*/
write: function (map, fileName) {
const exporter = new GodotTilemapExporter(map, fileName);
exporter.write();
return undefined;
}
};
// noinspection JSUnresolvedFunction
tiled.registerMapFormat("Godot", customTileMapFormat);