@ohmygame/level-editor 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.ohmygame-plugin/plugin.json +42 -0
- package/LICENSE +201 -0
- package/README.md +43 -2
- package/assets/icon.svg +1 -0
- package/locales/en.json +9 -0
- package/locales/zh-CN.json +9 -0
- package/package.json +27 -4
- package/panel/dom.js +79 -0
- package/panel/i18n.js +225 -0
- package/panel/index.html +15 -0
- package/panel/inspector.js +156 -0
- package/panel/main.js +1697 -0
- package/panel/new-map.js +112 -0
- package/panel/palette.js +196 -0
- package/panel/render.js +321 -0
- package/panel/style.css +137 -0
- package/panel/tmj.js +901 -0
- package/skills/level-maps/SKILL.md +28 -0
package/panel/tmj.js
ADDED
|
@@ -0,0 +1,901 @@
|
|
|
1
|
+
// The level editor's map model: Tiled JSON maps (.tmj) read, changed and
|
|
2
|
+
// written back without losing anything the editor doesn't understand. No DOM:
|
|
3
|
+
// the panel draws it, and the tests run it in Node.
|
|
4
|
+
//
|
|
5
|
+
// A map is kept as the JSON Tiled wrote, parsed in key order. Only the tile
|
|
6
|
+
// layers' data is decoded, into one Uint32Array per layer, and written back
|
|
7
|
+
// on save, in the layer's own encoding. Everything else is changed in place,
|
|
8
|
+
// so a field the editor never touched is written as it was read: the same
|
|
9
|
+
// keys in the same order, and the same number and string spellings.
|
|
10
|
+
|
|
11
|
+
/** GID flag bits (https://doc.mapeditor.org/en/stable/reference/global-tile-ids/). */
|
|
12
|
+
export const FLIP_H = 0x80000000;
|
|
13
|
+
export const FLIP_V = 0x40000000;
|
|
14
|
+
export const FLIP_D = 0x20000000;
|
|
15
|
+
/** Rotates hexagonal tiles by 120°; ignored on orthogonal maps but kept. */
|
|
16
|
+
export const ROTATE_HEX = 0x10000000;
|
|
17
|
+
export const GID_MASK = 0x0fffffff;
|
|
18
|
+
|
|
19
|
+
/** The tile a GID names, without its flip flags. */
|
|
20
|
+
export const tileOf = (gid) => (gid & GID_MASK) >>> 0;
|
|
21
|
+
/** A GID's flag bits only. */
|
|
22
|
+
export const flagsOf = (gid) => (gid & ~GID_MASK) >>> 0;
|
|
23
|
+
|
|
24
|
+
// ---------------------------------------------------------------------------
|
|
25
|
+
// JSON in and out, keeping the file's own layout.
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Each value's text as the file spelled it, where it differs from how
|
|
29
|
+
* JavaScript writes the value: `1.0`, `0.333333333333333`, `"..\/tiles.png"`.
|
|
30
|
+
* Keyed by the object or array holding it, then by key or index.
|
|
31
|
+
*/
|
|
32
|
+
const spellings = new WeakMap();
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Parses JSON, remembering how numbers and strings were spelled so an
|
|
36
|
+
* unchanged value is written back the same way. Uses the source text that
|
|
37
|
+
* `JSON.parse` gives a reviver (Chromium 114+, Node 21+); without it the
|
|
38
|
+
* values are kept and only their spelling may change.
|
|
39
|
+
*/
|
|
40
|
+
export function parseJson(text) {
|
|
41
|
+
return JSON.parse(text, function (key, value, context) {
|
|
42
|
+
const source = context?.source;
|
|
43
|
+
if (typeof source === "string" && (typeof value === "number" || typeof value === "string")) {
|
|
44
|
+
if (source !== (typeof value === "number" ? String(value) : JSON.stringify(value))) {
|
|
45
|
+
let held = spellings.get(this);
|
|
46
|
+
if (!held) spellings.set(this, (held = new Map()));
|
|
47
|
+
held.set(key, { source, value });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return value;
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** How a file lays out its JSON, read from the file itself (see `detectStyle`). */
|
|
55
|
+
export const TILED_STYLE = Object.freeze({
|
|
56
|
+
kind: "tiled",
|
|
57
|
+
indent: " ",
|
|
58
|
+
wrap: 0,
|
|
59
|
+
escapeSlash: true,
|
|
60
|
+
escapeUnicode: true,
|
|
61
|
+
prefix: "",
|
|
62
|
+
suffix: "",
|
|
63
|
+
eol: "\n",
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The layout `text` was written in, so the map is saved the same way. Tiled
|
|
68
|
+
* writes maps with its own JSON writer (`src/plugins/json/qjsonparser`):
|
|
69
|
+
* `"key":value` with no space, one key per line indented by one space past
|
|
70
|
+
* its object, objects in arrays on their own lines, arrays wrapped every map
|
|
71
|
+
* width items, `/` written as `\/` and non-ASCII as `\u` escapes. Other tools
|
|
72
|
+
* write `JSON.stringify(map, null, n)`, some with tile data on one line. The
|
|
73
|
+
* candidates are tried in turn; the first that reproduces the file exactly
|
|
74
|
+
* wins (`exact`), else the closest guess.
|
|
75
|
+
*/
|
|
76
|
+
export function detectStyle(text, doc) {
|
|
77
|
+
let body = text;
|
|
78
|
+
let prefix = "";
|
|
79
|
+
if (body.startsWith("")) {
|
|
80
|
+
prefix = "";
|
|
81
|
+
body = body.slice(1);
|
|
82
|
+
}
|
|
83
|
+
const trimmed = body.replace(/\s+$/, "");
|
|
84
|
+
const suffix = body.slice(trimmed.length);
|
|
85
|
+
const eol = trimmed.includes("\r\n") ? "\r\n" : "\n";
|
|
86
|
+
const normalized = eol === "\r\n" ? trimmed.replaceAll("\r\n", "\n") : trimmed;
|
|
87
|
+
const shared = {
|
|
88
|
+
prefix,
|
|
89
|
+
suffix,
|
|
90
|
+
eol,
|
|
91
|
+
escapeSlash: /\\\//.test(trimmed),
|
|
92
|
+
escapeUnicode: /\\u(?:00[89a-fA-F][0-9a-fA-F]|0[1-9a-fA-F][0-9a-fA-F]{2}|[1-9a-fA-F][0-9a-fA-F]{3})/.test(trimmed),
|
|
93
|
+
};
|
|
94
|
+
const wrap = tiledWrap(doc);
|
|
95
|
+
const indent = /\n([ \t]+)"/.exec(normalized)?.[1] ?? " ";
|
|
96
|
+
const keySep = /"\s*:\s/.test(normalized) ? ": " : ":";
|
|
97
|
+
const tiled = [
|
|
98
|
+
{ ...shared, kind: "tiled", indent: " ", wrap, escapeSlash: true, escapeUnicode: true },
|
|
99
|
+
{ ...shared, kind: "tiled", indent: " ", wrap },
|
|
100
|
+
{ ...shared, kind: "tiled", indent: " ", wrap: 0 },
|
|
101
|
+
];
|
|
102
|
+
const standard = [
|
|
103
|
+
{ ...shared, kind: "standard", indent, keySep, inline: true, itemSep: ", " },
|
|
104
|
+
{ ...shared, kind: "standard", indent, keySep, inline: true, itemSep: "," },
|
|
105
|
+
{ ...shared, kind: "standard", indent, keySep, inline: false, itemSep: ", " },
|
|
106
|
+
];
|
|
107
|
+
const compact = [{ ...shared, kind: "compact" }];
|
|
108
|
+
const looksTiled = normalized.startsWith('{ "') || /\n {8}\{\n/.test(normalized);
|
|
109
|
+
const candidates = !normalized.includes("\n")
|
|
110
|
+
? [...compact, ...tiled, ...standard]
|
|
111
|
+
: looksTiled
|
|
112
|
+
? [...tiled, ...standard, ...compact]
|
|
113
|
+
: [...standard, ...tiled, ...compact];
|
|
114
|
+
for (const style of candidates) {
|
|
115
|
+
if (stringifyJson(doc, style) === normalized) return { ...style, exact: true };
|
|
116
|
+
}
|
|
117
|
+
return { ...candidates[0], exact: false };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** How often Tiled wraps arrays: after each row of a map's tiles. */
|
|
121
|
+
function tiledWrap(doc) {
|
|
122
|
+
if (!doc || typeof doc !== "object") return 0;
|
|
123
|
+
if (doc.infinite) return doc.editorsettings?.chunksize?.width ?? 16;
|
|
124
|
+
return Number.isInteger(doc.width) ? doc.width : 0;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The layout for a new map: Tiled's own. */
|
|
128
|
+
export function newMapStyle(doc) {
|
|
129
|
+
return { ...TILED_STYLE, wrap: tiledWrap(doc), suffix: "\n" };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Writes `value` in `style`, without its prefix, suffix or line endings (see `formatJson`). */
|
|
133
|
+
export function stringifyJson(value, style) {
|
|
134
|
+
const out = [];
|
|
135
|
+
if (style.kind === "tiled") writeTiled(value, 0, out, style, undefined, "");
|
|
136
|
+
else if (style.kind === "compact") writeCompact(value, out, style, undefined, "");
|
|
137
|
+
else writeStandard(value, 0, out, style, undefined, "");
|
|
138
|
+
return out.join("");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The whole file: `stringifyJson` with the file's prefix, suffix and line endings. */
|
|
142
|
+
export function formatJson(value, style) {
|
|
143
|
+
let text = stringifyJson(value, style);
|
|
144
|
+
if (style.eol && style.eol !== "\n") text = text.replaceAll("\n", style.eol);
|
|
145
|
+
return (style.prefix ?? "") + text + (style.suffix ?? "");
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function scalar(value, style, holder, key) {
|
|
149
|
+
if (holder !== undefined) {
|
|
150
|
+
const spelled = spellings.get(holder)?.get(key);
|
|
151
|
+
if (spelled && Object.is(spelled.value, value)) return spelled.source;
|
|
152
|
+
}
|
|
153
|
+
if (typeof value === "string") return quote(value, style);
|
|
154
|
+
if (typeof value === "number") {
|
|
155
|
+
if (!Number.isFinite(value)) return "null";
|
|
156
|
+
if (style.kind === "standard") return String(value);
|
|
157
|
+
// Tiled's 15 digits, unless that would change the value.
|
|
158
|
+
const short = formatG15(value);
|
|
159
|
+
return Number(short) === value ? short : String(value);
|
|
160
|
+
}
|
|
161
|
+
if (value === true || value === false || value === null) return String(value);
|
|
162
|
+
return "null";
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** A number as Qt's `QString::number(d, 'g', 15)` writes it, which is how Tiled writes doubles. */
|
|
166
|
+
export function formatG15(value) {
|
|
167
|
+
if (Number.isInteger(value) && Math.abs(value) < 1e15) return String(value);
|
|
168
|
+
const [mantissa, exponentText] = value.toExponential(14).split("e");
|
|
169
|
+
const exponent = Number(exponentText);
|
|
170
|
+
const trim = (text) => (text.includes(".") ? text.replace(/0+$/, "").replace(/\.$/, "") : text);
|
|
171
|
+
if (exponent < -4 || exponent >= 15) {
|
|
172
|
+
const digits = String(Math.abs(exponent)).padStart(2, "0");
|
|
173
|
+
return `${trim(mantissa)}e${exponent < 0 ? "-" : "+"}${digits}`;
|
|
174
|
+
}
|
|
175
|
+
return trim(value.toPrecision(15));
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function quote(text, style) {
|
|
179
|
+
let quoted = JSON.stringify(text);
|
|
180
|
+
if (style.escapeSlash) quoted = quoted.replaceAll("/", "\\/");
|
|
181
|
+
if (style.escapeUnicode)
|
|
182
|
+
quoted = quoted.replace(/[\u0080-]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
183
|
+
return quoted;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const isContainer = (value) => value !== null && typeof value === "object";
|
|
187
|
+
|
|
188
|
+
function writeTiled(value, depth, out, style, holder, key) {
|
|
189
|
+
if (Array.isArray(value)) {
|
|
190
|
+
const indent = style.indent.repeat(depth);
|
|
191
|
+
out.push("[");
|
|
192
|
+
for (let i = 0; i < value.length; i++) {
|
|
193
|
+
if (i) out.push(style.wrap && i % style.wrap === 0 ? `,\n${indent}` : ", ");
|
|
194
|
+
const item = value[i];
|
|
195
|
+
if (isContainer(item)) writeTiled(item, depth + 1, out, style, value, String(i));
|
|
196
|
+
else out.push(scalar(item, style, value, String(i)));
|
|
197
|
+
}
|
|
198
|
+
out.push("]");
|
|
199
|
+
} else if (isContainer(value)) {
|
|
200
|
+
const indent = style.indent.repeat(depth);
|
|
201
|
+
out.push(depth ? `\n${indent}{\n` : "{");
|
|
202
|
+
let first = true;
|
|
203
|
+
for (const name of Object.keys(value)) {
|
|
204
|
+
if (!first) out.push(",\n");
|
|
205
|
+
first = false;
|
|
206
|
+
out.push(`${indent} ${quote(name, style)}:`);
|
|
207
|
+
const item = value[name];
|
|
208
|
+
if (isContainer(item)) writeTiled(item, depth + 1, out, style, value, name);
|
|
209
|
+
else out.push(scalar(item, style, value, name));
|
|
210
|
+
}
|
|
211
|
+
out.push(`\n${indent}}`);
|
|
212
|
+
} else out.push(scalar(value, style, holder, key));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function writeCompact(value, out, style, holder, key) {
|
|
216
|
+
if (Array.isArray(value)) {
|
|
217
|
+
out.push("[");
|
|
218
|
+
value.forEach((item, i) => {
|
|
219
|
+
if (i) out.push(",");
|
|
220
|
+
writeCompact(item, out, style, value, String(i));
|
|
221
|
+
});
|
|
222
|
+
out.push("]");
|
|
223
|
+
} else if (isContainer(value)) {
|
|
224
|
+
out.push("{");
|
|
225
|
+
Object.keys(value).forEach((name, i) => {
|
|
226
|
+
if (i) out.push(",");
|
|
227
|
+
out.push(`${quote(name, style)}:`);
|
|
228
|
+
writeCompact(value[name], out, style, value, name);
|
|
229
|
+
});
|
|
230
|
+
out.push("}");
|
|
231
|
+
} else out.push(scalar(value, style, holder, key));
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function writeStandard(value, depth, out, style, holder, key) {
|
|
235
|
+
const inner = style.indent.repeat(depth + 1);
|
|
236
|
+
if (Array.isArray(value)) {
|
|
237
|
+
if (!value.length) return void out.push("[]");
|
|
238
|
+
if (style.inline && !value.some(isContainer)) {
|
|
239
|
+
out.push("[", value.map((item, i) => scalar(item, style, value, String(i))).join(style.itemSep), "]");
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
out.push("[\n");
|
|
243
|
+
value.forEach((item, i) => {
|
|
244
|
+
if (i) out.push(",\n");
|
|
245
|
+
out.push(inner);
|
|
246
|
+
writeStandard(item, depth + 1, out, style, value, String(i));
|
|
247
|
+
});
|
|
248
|
+
out.push(`\n${style.indent.repeat(depth)}]`);
|
|
249
|
+
} else if (isContainer(value)) {
|
|
250
|
+
const names = Object.keys(value);
|
|
251
|
+
if (!names.length) return void out.push("{}");
|
|
252
|
+
out.push("{\n");
|
|
253
|
+
names.forEach((name, i) => {
|
|
254
|
+
if (i) out.push(",\n");
|
|
255
|
+
out.push(inner, quote(name, style), style.keySep);
|
|
256
|
+
writeStandard(value[name], depth + 1, out, style, value, name);
|
|
257
|
+
});
|
|
258
|
+
out.push(`\n${style.indent.repeat(depth)}}`);
|
|
259
|
+
} else out.push(scalar(value, style, holder, key));
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Sets `key` on `object`. A new key goes where Tiled would put it, in
|
|
264
|
+
* alphabetical order, when the object's keys already are; otherwise last.
|
|
265
|
+
* The object stays the same object, so references to it hold.
|
|
266
|
+
*/
|
|
267
|
+
export function setKey(object, key, value) {
|
|
268
|
+
if (Object.hasOwn(object, key)) {
|
|
269
|
+
object[key] = value;
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
const names = Object.keys(object);
|
|
273
|
+
const sorted = names.every((name, i) => i === 0 || names[i - 1] <= name);
|
|
274
|
+
if (!sorted || !names.length || names.at(-1) < key) {
|
|
275
|
+
object[key] = value;
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
const entries = Object.entries(object);
|
|
279
|
+
for (const name of names) delete object[name];
|
|
280
|
+
let placed = false;
|
|
281
|
+
for (const [name, item] of entries) {
|
|
282
|
+
if (!placed && key < name) {
|
|
283
|
+
object[key] = value;
|
|
284
|
+
placed = true;
|
|
285
|
+
}
|
|
286
|
+
object[name] = item;
|
|
287
|
+
}
|
|
288
|
+
if (!placed) object[key] = value;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Fields kept by reference in a capture: a layer's contents, which have their own history. */
|
|
292
|
+
const SHARED_FIELDS = ["data", "objects", "layers", "chunks"];
|
|
293
|
+
|
|
294
|
+
const copyField = (name, value) => (SHARED_FIELDS.includes(name) || !isContainer(value) ? value : structuredClone(value));
|
|
295
|
+
|
|
296
|
+
/** An object's fields in order, to put back with `restoreFields`. */
|
|
297
|
+
export function captureFields(object) {
|
|
298
|
+
return Object.entries(object).map(([name, value]) => [name, copyField(name, value)]);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Puts back captured fields in their order, in the same object; the capture stays reusable. */
|
|
302
|
+
export function restoreFields(object, fields) {
|
|
303
|
+
for (const name of Object.keys(object)) delete object[name];
|
|
304
|
+
for (const [name, value] of fields) object[name] = copyField(name, value);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// ---------------------------------------------------------------------------
|
|
308
|
+
// Paths, relative to the project, with forward slashes.
|
|
309
|
+
|
|
310
|
+
export function dirname(path) {
|
|
311
|
+
const at = path.lastIndexOf("/");
|
|
312
|
+
return at < 0 ? "" : path.slice(0, at);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
export function basename(path) {
|
|
316
|
+
return path.slice(path.lastIndexOf("/") + 1);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** `relative` resolved against the folder `file` is in; `undefined` if it leaves the project or is absolute. */
|
|
320
|
+
export function resolvePath(file, relative) {
|
|
321
|
+
if (!relative || /^(?:[a-zA-Z]:)?[\\/]/.test(relative) || /^[a-z][a-z0-9+.-]*:/i.test(relative)) return undefined;
|
|
322
|
+
const parts = dirname(file).split("/").filter(Boolean);
|
|
323
|
+
for (const part of relative.replaceAll("\\", "/").split("/")) {
|
|
324
|
+
if (!part || part === ".") continue;
|
|
325
|
+
if (part === "..") {
|
|
326
|
+
if (!parts.length) return undefined;
|
|
327
|
+
parts.pop();
|
|
328
|
+
} else parts.push(part);
|
|
329
|
+
}
|
|
330
|
+
return parts.join("/");
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** The path from the folder `file` is in to `target`, as Tiled writes image paths. */
|
|
334
|
+
export function relativePath(file, target) {
|
|
335
|
+
const from = dirname(file).split("/").filter(Boolean);
|
|
336
|
+
const to = target.split("/").filter(Boolean);
|
|
337
|
+
let shared = 0;
|
|
338
|
+
while (shared < from.length && shared < to.length - 1 && from[shared] === to[shared]) shared++;
|
|
339
|
+
return [...from.slice(shared).map(() => ".."), ...to.slice(shared)].join("/");
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// ---------------------------------------------------------------------------
|
|
343
|
+
// Tile data.
|
|
344
|
+
|
|
345
|
+
/** Base64 to bytes. */
|
|
346
|
+
export function fromBase64(text) {
|
|
347
|
+
const binary = atob(text.replace(/\s+/g, ""));
|
|
348
|
+
const bytes = new Uint8Array(binary.length);
|
|
349
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
350
|
+
return bytes;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
export function toBase64(bytes) {
|
|
354
|
+
let binary = "";
|
|
355
|
+
for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
356
|
+
return btoa(binary);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const STREAM_FORMAT = { zlib: "deflate", gzip: "gzip" };
|
|
360
|
+
|
|
361
|
+
async function transform(bytes, stream) {
|
|
362
|
+
const response = new Response(new Blob([bytes]).stream().pipeThrough(stream));
|
|
363
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** Whether a layer's data can be read here: plain arrays, or base64 that is plain, gzip or zlib. */
|
|
367
|
+
export function readableEncoding(encoding, compression) {
|
|
368
|
+
if (!encoding || encoding === "csv") return true;
|
|
369
|
+
return encoding === "base64" && (!compression || compression in STREAM_FORMAT);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** A layer's `data` as GIDs (flags included); throws for zstd or anything else it can't read. */
|
|
373
|
+
export async function decodeData(data, encoding, compression, count) {
|
|
374
|
+
if (!encoding || encoding === "csv") {
|
|
375
|
+
if (!Array.isArray(data)) throw new Error("tile data isn't an array");
|
|
376
|
+
const gids = new Uint32Array(count ?? data.length);
|
|
377
|
+
for (let i = 0; i < gids.length && i < data.length; i++) gids[i] = Number(data[i]) >>> 0;
|
|
378
|
+
return gids;
|
|
379
|
+
}
|
|
380
|
+
if (encoding !== "base64") throw new Error(`unknown encoding ${encoding}`);
|
|
381
|
+
let bytes = fromBase64(String(data));
|
|
382
|
+
if (compression) {
|
|
383
|
+
const format = STREAM_FORMAT[compression];
|
|
384
|
+
if (!format) throw new Error(`unsupported compression ${compression}`);
|
|
385
|
+
bytes = await transform(bytes, new DecompressionStream(format));
|
|
386
|
+
}
|
|
387
|
+
const gids = new Uint32Array(count ?? Math.floor(bytes.length / 4));
|
|
388
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
389
|
+
for (let i = 0; i < gids.length && i * 4 + 3 < bytes.length; i++) gids[i] = view.getUint32(i * 4, true);
|
|
390
|
+
return gids;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** GIDs in a layer's encoding: an array, or a base64 string, compressed as before. */
|
|
394
|
+
export async function encodeData(gids, encoding, compression) {
|
|
395
|
+
if (!encoding || encoding === "csv") return Array.from(gids);
|
|
396
|
+
const bytes = new Uint8Array(gids.length * 4);
|
|
397
|
+
const view = new DataView(bytes.buffer);
|
|
398
|
+
gids.forEach((gid, i) => view.setUint32(i * 4, gid, true));
|
|
399
|
+
if (!compression) return toBase64(bytes);
|
|
400
|
+
const format = STREAM_FORMAT[compression];
|
|
401
|
+
if (!format) throw new Error(`unsupported compression ${compression}`);
|
|
402
|
+
return toBase64(await transform(bytes, new CompressionStream(format)));
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// ---------------------------------------------------------------------------
|
|
406
|
+
// Maps.
|
|
407
|
+
|
|
408
|
+
/** Whether parsed JSON is a Tiled map. */
|
|
409
|
+
export function isTiledMap(doc) {
|
|
410
|
+
return (
|
|
411
|
+
isContainer(doc) &&
|
|
412
|
+
!Array.isArray(doc) &&
|
|
413
|
+
(doc.type === "map" || (doc.type === undefined && Array.isArray(doc.layers) && Array.isArray(doc.tilesets) && "tilewidth" in doc))
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** Calls `visit(layer, parentArray, depth)` for each layer, groups before their children. */
|
|
418
|
+
export function walkLayers(layers, visit, depth = 0) {
|
|
419
|
+
for (const layer of layers ?? []) {
|
|
420
|
+
if (visit(layer, layers, depth) === false) continue;
|
|
421
|
+
if (layer.type === "group") walkLayers(layer.layers, visit, depth + 1);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Opens a map's text: the parsed document, its layout, each tile layer's
|
|
427
|
+
* GIDs, and why it can only be read, if it can.
|
|
428
|
+
*/
|
|
429
|
+
export async function openMap(text, path) {
|
|
430
|
+
const doc = parseJson(text.startsWith("") ? text.slice(1) : text);
|
|
431
|
+
if (!isTiledMap(doc)) throw new Error("not a Tiled map");
|
|
432
|
+
const map = {
|
|
433
|
+
path,
|
|
434
|
+
doc,
|
|
435
|
+
style: detectStyle(text, doc),
|
|
436
|
+
/** Tile layer object → `{ gids, original, width, height }`, or `{ chunks }` for infinite maps. */
|
|
437
|
+
tiles: new Map(),
|
|
438
|
+
/** Why the map is read-only: `infinite`, `zstd`, `orientation`, `encoding`. */
|
|
439
|
+
readOnly: [],
|
|
440
|
+
};
|
|
441
|
+
if (doc.infinite) map.readOnly.push("infinite");
|
|
442
|
+
if (doc.orientation && doc.orientation !== "orthogonal") map.readOnly.push("orientation");
|
|
443
|
+
const pending = [];
|
|
444
|
+
walkLayers(doc.layers, (layer) => {
|
|
445
|
+
if (layer.type === "tilelayer") pending.push(loadTileLayer(map, layer));
|
|
446
|
+
});
|
|
447
|
+
await Promise.all(pending);
|
|
448
|
+
return map;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
async function loadTileLayer(map, layer) {
|
|
452
|
+
const { encoding, compression } = layer;
|
|
453
|
+
if (!readableEncoding(encoding, compression)) {
|
|
454
|
+
const reason = compression === "zstd" ? "zstd" : "encoding";
|
|
455
|
+
if (!map.readOnly.includes(reason)) map.readOnly.push(reason);
|
|
456
|
+
map.tiles.set(layer, { unreadable: reason });
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
if (Array.isArray(layer.chunks)) {
|
|
460
|
+
const chunks = await Promise.all(
|
|
461
|
+
layer.chunks.map(async (chunk) => ({
|
|
462
|
+
x: chunk.x,
|
|
463
|
+
y: chunk.y,
|
|
464
|
+
width: chunk.width,
|
|
465
|
+
height: chunk.height,
|
|
466
|
+
gids: await decodeData(chunk.data, encoding, compression, chunk.width * chunk.height),
|
|
467
|
+
})),
|
|
468
|
+
);
|
|
469
|
+
map.tiles.set(layer, { chunks });
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
const width = layer.width ?? map.doc.width;
|
|
473
|
+
const height = layer.height ?? map.doc.height;
|
|
474
|
+
const gids = await decodeData(layer.data ?? [], encoding, compression, width * height);
|
|
475
|
+
map.tiles.set(layer, { gids, original: gids.slice(), originalData: typeof layer.data === "string" ? layer.data : undefined, width, height });
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
export const isEditable = (map) => map.readOnly.length === 0;
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* The map's text to save: tile layers whose tiles changed are encoded again
|
|
482
|
+
* (unchanged ones keep the exact text they had), then the whole map in its
|
|
483
|
+
* own layout. Call `markSaved` once it is written. The tiles are taken as
|
|
484
|
+
* they are when this is called; edits made while it encodes or while the
|
|
485
|
+
* file is written aren't in this text, and stay unsaved.
|
|
486
|
+
*/
|
|
487
|
+
export async function serializeMap(map) {
|
|
488
|
+
if (!isEditable(map)) throw new Error("this map can only be read here");
|
|
489
|
+
// Every layer's tiles at one moment, before anything is awaited.
|
|
490
|
+
const snapshots = [...map.tiles].filter(([, tiles]) => tiles.gids).map(([layer, tiles]) => [layer, tiles, tiles.gids.slice()]);
|
|
491
|
+
const saved = new Map();
|
|
492
|
+
for (const [layer, tiles, gids] of snapshots) {
|
|
493
|
+
if (tiles.original && tiles.originalData !== undefined && sameData(gids, tiles.original)) {
|
|
494
|
+
// Back as it was saved: a base64 layer keeps its exact text, which
|
|
495
|
+
// compressing again might not reproduce.
|
|
496
|
+
setKey(layer, "data", tiles.originalData);
|
|
497
|
+
} else if (Array.isArray(layer.data) && layer.data.length === gids.length && (!layer.encoding || layer.encoding === "csv")) {
|
|
498
|
+
gids.forEach((gid, i) => (layer.data[i] = gid));
|
|
499
|
+
} else setKey(layer, "data", await encodeData(gids, layer.encoding, layer.compression));
|
|
500
|
+
saved.set(tiles, { gids, data: typeof layer.data === "string" ? layer.data : undefined });
|
|
501
|
+
}
|
|
502
|
+
map.serialized = saved;
|
|
503
|
+
return formatJson(map.doc, map.style);
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* After the text from the last `serializeMap` is written: what is on disk
|
|
508
|
+
* now, which is the tiles as they were serialized, not as they are now.
|
|
509
|
+
*/
|
|
510
|
+
export function markSaved(map) {
|
|
511
|
+
for (const [tiles, { gids, data }] of map.serialized ?? []) {
|
|
512
|
+
tiles.original = gids;
|
|
513
|
+
tiles.originalData = data;
|
|
514
|
+
}
|
|
515
|
+
map.serialized = undefined;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
function sameData(a, b) {
|
|
519
|
+
if (a.length !== b.length) return false;
|
|
520
|
+
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
|
521
|
+
return true;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// ---------------------------------------------------------------------------
|
|
525
|
+
// Tilesets.
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* The tileset a GID belongs to and its local tile id. `tilesets` are the
|
|
529
|
+
* resolved tilesets, each with `firstgid`, sorted or not.
|
|
530
|
+
*/
|
|
531
|
+
export function findTileset(tilesets, gid) {
|
|
532
|
+
const tile = tileOf(gid);
|
|
533
|
+
if (!tile) return undefined;
|
|
534
|
+
let found;
|
|
535
|
+
for (const tileset of tilesets) {
|
|
536
|
+
if (tileset.firstgid <= tile && (!found || tileset.firstgid > found.firstgid)) found = tileset;
|
|
537
|
+
}
|
|
538
|
+
return found ? { tileset: found, id: tile - found.firstgid } : undefined;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Where tile `id` is drawn from in a tileset (embedded JSON or the external
|
|
543
|
+
* one it points to, resolved): an image tileset's grid cell, or a
|
|
544
|
+
* collection's own image. `{ image, sx, sy, width, height }` with `image` a
|
|
545
|
+
* path relative to the tileset's file.
|
|
546
|
+
*/
|
|
547
|
+
export function tileSource(tileset, id) {
|
|
548
|
+
if (tileset.image && tileset.columns > 0) {
|
|
549
|
+
if (tileset.tilecount !== undefined && id >= tileset.tilecount) return undefined;
|
|
550
|
+
const margin = tileset.margin ?? 0;
|
|
551
|
+
const spacing = tileset.spacing ?? 0;
|
|
552
|
+
const column = id % tileset.columns;
|
|
553
|
+
const row = Math.floor(id / tileset.columns);
|
|
554
|
+
return {
|
|
555
|
+
image: tileset.image,
|
|
556
|
+
sx: margin + column * (tileset.tilewidth + spacing),
|
|
557
|
+
sy: margin + row * (tileset.tileheight + spacing),
|
|
558
|
+
width: tileset.tilewidth,
|
|
559
|
+
height: tileset.tileheight,
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
const tile = tilesOf(tileset).find((entry) => entry.id === id);
|
|
563
|
+
if (!tile?.image) return undefined;
|
|
564
|
+
return {
|
|
565
|
+
image: tile.image,
|
|
566
|
+
sx: tile.x ?? 0,
|
|
567
|
+
sy: tile.y ?? 0,
|
|
568
|
+
width: tile.width ?? tile.imagewidth,
|
|
569
|
+
height: tile.height ?? tile.imageheight,
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/** The local ids of a tileset's tiles, in palette order. */
|
|
574
|
+
export function tileIds(tileset) {
|
|
575
|
+
if (tileset.image && tileset.columns > 0) {
|
|
576
|
+
const count = tileset.tilecount ?? tileset.columns * Math.floor((tileset.imageheight ?? 0) / tileset.tileheight);
|
|
577
|
+
return Array.from({ length: count }, (_, i) => i);
|
|
578
|
+
}
|
|
579
|
+
return tilesOf(tileset).filter((tile) => tile.image).map((tile) => tile.id).sort((a, b) => a - b);
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* A tileset's `tiles` as a list of `{ id, … }`. Tiled before 1.2 wrote them
|
|
584
|
+
* as an object keyed by tile id; that is read here and never rewritten.
|
|
585
|
+
*/
|
|
586
|
+
export function tilesOf(tileset) {
|
|
587
|
+
const tiles = tileset?.tiles;
|
|
588
|
+
if (Array.isArray(tiles)) return tiles.filter(isContainer);
|
|
589
|
+
if (!isContainer(tiles)) return [];
|
|
590
|
+
return Object.entries(tiles)
|
|
591
|
+
.filter(([key, tile]) => isContainer(tile) && /^\d+$/.test(key))
|
|
592
|
+
.map(([key, tile]) => ({ ...tile, id: Number(key) }));
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/** Columns and tile count of an image cut into `tilewidth` × `tileheight` tiles. */
|
|
596
|
+
export function gridOf(imagewidth, imageheight, tilewidth, tileheight, margin = 0, spacing = 0) {
|
|
597
|
+
const columns = Math.max(0, Math.floor((imagewidth - 2 * margin + spacing) / (tilewidth + spacing)));
|
|
598
|
+
const rows = Math.max(0, Math.floor((imageheight - 2 * margin + spacing) / (tileheight + spacing)));
|
|
599
|
+
return { columns, tilecount: columns * rows };
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* An external tileset in Tiled's XML format (.tsx), as the JSON fields this
|
|
604
|
+
* editor reads. `root` is the parsed `<tileset>` element; any DOM-like
|
|
605
|
+
* object with `getAttribute`, `children` and `tagName` works.
|
|
606
|
+
*/
|
|
607
|
+
export function tilesetFromXml(root) {
|
|
608
|
+
const number = (element, name, fallback) => {
|
|
609
|
+
const value = element.getAttribute(name);
|
|
610
|
+
return value === null || value === "" ? fallback : Number(value);
|
|
611
|
+
};
|
|
612
|
+
const children = (element, tag) => [...element.children].filter((child) => child.tagName === tag);
|
|
613
|
+
const tileset = {
|
|
614
|
+
name: root.getAttribute("name") ?? "",
|
|
615
|
+
tilewidth: number(root, "tilewidth", 0),
|
|
616
|
+
tileheight: number(root, "tileheight", 0),
|
|
617
|
+
tilecount: number(root, "tilecount", undefined),
|
|
618
|
+
columns: number(root, "columns", 0),
|
|
619
|
+
margin: number(root, "margin", 0),
|
|
620
|
+
spacing: number(root, "spacing", 0),
|
|
621
|
+
};
|
|
622
|
+
const offset = children(root, "tileoffset")[0];
|
|
623
|
+
if (offset) tileset.tileoffset = { x: number(offset, "x", 0), y: number(offset, "y", 0) };
|
|
624
|
+
const renderSize = root.getAttribute("tilerendersize");
|
|
625
|
+
if (renderSize) tileset.tilerendersize = renderSize;
|
|
626
|
+
const image = children(root, "image")[0];
|
|
627
|
+
if (image) {
|
|
628
|
+
tileset.image = image.getAttribute("source") ?? "";
|
|
629
|
+
tileset.imagewidth = number(image, "width", undefined);
|
|
630
|
+
tileset.imageheight = number(image, "height", undefined);
|
|
631
|
+
}
|
|
632
|
+
const tiles = children(root, "tile")
|
|
633
|
+
.map((tile) => {
|
|
634
|
+
const own = children(tile, "image")[0];
|
|
635
|
+
if (!own) return undefined;
|
|
636
|
+
return {
|
|
637
|
+
id: number(tile, "id", 0),
|
|
638
|
+
image: own.getAttribute("source") ?? "",
|
|
639
|
+
imagewidth: number(own, "width", undefined),
|
|
640
|
+
imageheight: number(own, "height", undefined),
|
|
641
|
+
x: number(tile, "x", undefined),
|
|
642
|
+
y: number(tile, "y", undefined),
|
|
643
|
+
width: number(tile, "width", undefined),
|
|
644
|
+
height: number(tile, "height", undefined),
|
|
645
|
+
};
|
|
646
|
+
})
|
|
647
|
+
.filter(Boolean);
|
|
648
|
+
if (tiles.length) tileset.tiles = tiles;
|
|
649
|
+
return tileset;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// ---------------------------------------------------------------------------
|
|
653
|
+
// Editing tiles. Changes are `[index, before, after]`, applied and reverted
|
|
654
|
+
// by `applyChanges`, so the panel's history can undo them.
|
|
655
|
+
|
|
656
|
+
/** A rectangle of GIDs; 0 cells are left alone when painted. */
|
|
657
|
+
export function stampOf(width, height, gids) {
|
|
658
|
+
return { width, height, gids: Uint32Array.from(gids) };
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
function record(changes, gids, index, gid) {
|
|
662
|
+
if (gids[index] === gid) return;
|
|
663
|
+
const previous = changes.get(index);
|
|
664
|
+
changes.set(index, [index, previous ? previous[1] : gids[index], gid]);
|
|
665
|
+
gids[index] = gid;
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/**
|
|
669
|
+
* Paints `stamp` with its top-left at cell (x, y), into `changes` (a Map
|
|
670
|
+
* kept across one stroke). Cells outside the layer are skipped.
|
|
671
|
+
*/
|
|
672
|
+
export function paintStamp(tiles, x, y, stamp, changes = new Map()) {
|
|
673
|
+
for (let row = 0; row < stamp.height; row++) {
|
|
674
|
+
for (let column = 0; column < stamp.width; column++) {
|
|
675
|
+
const gid = stamp.gids[row * stamp.width + column];
|
|
676
|
+
const cx = x + column;
|
|
677
|
+
const cy = y + row;
|
|
678
|
+
if (!gid || cx < 0 || cy < 0 || cx >= tiles.width || cy >= tiles.height) continue;
|
|
679
|
+
record(changes, tiles.gids, cy * tiles.width + cx, gid);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
return changes;
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/** Clears the cells under a `width` × `height` rectangle at (x, y). */
|
|
686
|
+
export function erase(tiles, x, y, width = 1, height = 1, changes = new Map()) {
|
|
687
|
+
for (let cy = Math.max(0, y); cy < Math.min(tiles.height, y + height); cy++) {
|
|
688
|
+
for (let cx = Math.max(0, x); cx < Math.min(tiles.width, x + width); cx++) record(changes, tiles.gids, cy * tiles.width + cx, 0);
|
|
689
|
+
}
|
|
690
|
+
return changes;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/**
|
|
694
|
+
* Fills the 4-connected area of cells equal to (x, y)'s GID (flags
|
|
695
|
+
* included) with `stamp`, repeated from (x, y).
|
|
696
|
+
*/
|
|
697
|
+
export function floodFill(tiles, x, y, stamp, changes = new Map()) {
|
|
698
|
+
const { width, height, gids } = tiles;
|
|
699
|
+
if (x < 0 || y < 0 || x >= width || y >= height) return changes;
|
|
700
|
+
const target = gids[y * width + x];
|
|
701
|
+
const seen = new Uint8Array(width * height);
|
|
702
|
+
const stack = [y * width + x];
|
|
703
|
+
seen[stack[0]] = 1;
|
|
704
|
+
const modulo = (value, size) => ((value % size) + size) % size;
|
|
705
|
+
while (stack.length) {
|
|
706
|
+
const index = stack.pop();
|
|
707
|
+
const cx = index % width;
|
|
708
|
+
const cy = (index - cx) / width;
|
|
709
|
+
const gid = stamp.gids[modulo(cy - y, stamp.height) * stamp.width + modulo(cx - x, stamp.width)];
|
|
710
|
+
record(changes, gids, index, gid);
|
|
711
|
+
for (const [nx, ny] of [[cx + 1, cy], [cx - 1, cy], [cx, cy + 1], [cx, cy - 1]]) {
|
|
712
|
+
if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue;
|
|
713
|
+
const next = ny * width + nx;
|
|
714
|
+
if (seen[next] || gids[next] !== target) continue;
|
|
715
|
+
seen[next] = 1;
|
|
716
|
+
stack.push(next);
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
return changes;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/** Applies a list of changes, or takes them back with `undo`. */
|
|
723
|
+
export function applyChanges(gids, changes, undo = false) {
|
|
724
|
+
for (const [index, before, after] of changes) gids[index] = undo ? before : after;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
// ---------------------------------------------------------------------------
|
|
728
|
+
// Objects, layers and their ids.
|
|
729
|
+
|
|
730
|
+
/** The next object id, bumping `nextobjectid` past it (and past any id already used). */
|
|
731
|
+
export function takeObjectId(doc) {
|
|
732
|
+
let highest = 0;
|
|
733
|
+
walkLayers(doc.layers, (layer) => {
|
|
734
|
+
for (const object of layer.objects ?? []) highest = Math.max(highest, object.id ?? 0);
|
|
735
|
+
});
|
|
736
|
+
const id = Math.max(Number(doc.nextobjectid) || 1, highest + 1);
|
|
737
|
+
setKey(doc, "nextobjectid", id + 1);
|
|
738
|
+
return id;
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/** The next layer id, bumping `nextlayerid`. */
|
|
742
|
+
export function takeLayerId(doc) {
|
|
743
|
+
let highest = 0;
|
|
744
|
+
walkLayers(doc.layers, (layer) => void (highest = Math.max(highest, layer.id ?? 0)));
|
|
745
|
+
const id = Math.max(Number(doc.nextlayerid) || 1, highest + 1);
|
|
746
|
+
setKey(doc, "nextlayerid", id + 1);
|
|
747
|
+
return id;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/**
|
|
751
|
+
* Where an object's class goes: `type` (Tiled 1.8 and earlier, and 1.10 on),
|
|
752
|
+
* or `class`, which only Tiled 1.9 wrote. An object that has one keeps it.
|
|
753
|
+
*/
|
|
754
|
+
export function classKey(doc, object) {
|
|
755
|
+
if (object && Object.hasOwn(object, "type")) return "type";
|
|
756
|
+
if (object && Object.hasOwn(object, "class")) return "class";
|
|
757
|
+
return String(doc.version) === "1.9" ? "class" : "type";
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/**
|
|
761
|
+
* A new object in `layer`, with its keys as Tiled writes them. `shape` is
|
|
762
|
+
* `rectangle` or `point`.
|
|
763
|
+
*/
|
|
764
|
+
export function createObject(doc, layer, { shape, x, y, width = 0, height = 0, name = "", className = "" }) {
|
|
765
|
+
const object = {};
|
|
766
|
+
const kind = classKey(doc);
|
|
767
|
+
const fields = {
|
|
768
|
+
height: shape === "point" ? 0 : height,
|
|
769
|
+
id: takeObjectId(doc),
|
|
770
|
+
name,
|
|
771
|
+
...(shape === "point" ? { point: true } : {}),
|
|
772
|
+
rotation: 0,
|
|
773
|
+
[kind]: className,
|
|
774
|
+
visible: true,
|
|
775
|
+
width: shape === "point" ? 0 : width,
|
|
776
|
+
x,
|
|
777
|
+
y,
|
|
778
|
+
};
|
|
779
|
+
for (const key of Object.keys(fields).sort()) object[key] = fields[key];
|
|
780
|
+
if (!Array.isArray(layer.objects)) setKey(layer, "objects", []);
|
|
781
|
+
return object;
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
/** A new layer, as Tiled writes one; a tile layer takes `encoding`/`compression` from `like`. */
|
|
785
|
+
export function createLayer(doc, kind, name, like) {
|
|
786
|
+
const id = takeLayerId(doc);
|
|
787
|
+
if (kind === "tilelayer") {
|
|
788
|
+
const fields = {
|
|
789
|
+
...(like?.compression ? { compression: like.compression } : {}),
|
|
790
|
+
data: Array(doc.width * doc.height).fill(0),
|
|
791
|
+
...(like?.encoding ? { encoding: like.encoding } : {}),
|
|
792
|
+
height: doc.height,
|
|
793
|
+
id,
|
|
794
|
+
name,
|
|
795
|
+
opacity: 1,
|
|
796
|
+
type: "tilelayer",
|
|
797
|
+
visible: true,
|
|
798
|
+
width: doc.width,
|
|
799
|
+
x: 0,
|
|
800
|
+
y: 0,
|
|
801
|
+
};
|
|
802
|
+
return fields;
|
|
803
|
+
}
|
|
804
|
+
return { draworder: "topdown", id, name, objects: [], opacity: 1, type: "objectgroup", visible: true, x: 0, y: 0 };
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
/** A tile layer's editing state for a layer made by `createLayer`; its data is encoded on save. */
|
|
808
|
+
export function tilesFor(doc) {
|
|
809
|
+
const gids = new Uint32Array(doc.width * doc.height);
|
|
810
|
+
return { gids, original: undefined, width: doc.width, height: doc.height };
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/**
|
|
814
|
+
* A new map: `width` × `height` tiles of `tilewidth` × `tileheight`, with a
|
|
815
|
+
* `Ground` tile layer and an `Objects` layer, and an embedded image tileset
|
|
816
|
+
* when one is given (`{ name, image, imagewidth, imageheight }`, the image
|
|
817
|
+
* path relative to the map).
|
|
818
|
+
*/
|
|
819
|
+
export function createMap({ width, height, tilewidth, tileheight, tileset }) {
|
|
820
|
+
const doc = {
|
|
821
|
+
compressionlevel: -1,
|
|
822
|
+
height,
|
|
823
|
+
infinite: false,
|
|
824
|
+
layers: [],
|
|
825
|
+
nextlayerid: 1,
|
|
826
|
+
nextobjectid: 1,
|
|
827
|
+
orientation: "orthogonal",
|
|
828
|
+
renderorder: "right-down",
|
|
829
|
+
tileheight,
|
|
830
|
+
tilesets: [],
|
|
831
|
+
tilewidth,
|
|
832
|
+
type: "map",
|
|
833
|
+
version: "1.10",
|
|
834
|
+
width,
|
|
835
|
+
};
|
|
836
|
+
doc.layers.push(createLayer(doc, "tilelayer", "Ground"), createLayer(doc, "objectgroup", "Objects"));
|
|
837
|
+
if (tileset) {
|
|
838
|
+
const { columns, tilecount } = gridOf(tileset.imagewidth, tileset.imageheight, tilewidth, tileheight);
|
|
839
|
+
doc.tilesets.push({
|
|
840
|
+
columns,
|
|
841
|
+
firstgid: 1,
|
|
842
|
+
image: tileset.image,
|
|
843
|
+
imageheight: tileset.imageheight,
|
|
844
|
+
imagewidth: tileset.imagewidth,
|
|
845
|
+
margin: 0,
|
|
846
|
+
name: tileset.name,
|
|
847
|
+
spacing: 0,
|
|
848
|
+
tilecount,
|
|
849
|
+
tileheight,
|
|
850
|
+
tilewidth,
|
|
851
|
+
});
|
|
852
|
+
}
|
|
853
|
+
return doc;
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
// ---------------------------------------------------------------------------
|
|
857
|
+
// Custom properties, kept in Tiled's `[{ name, type, value }]` shape.
|
|
858
|
+
|
|
859
|
+
export const PROPERTY_TYPES = ["string", "int", "float", "bool"];
|
|
860
|
+
|
|
861
|
+
/** A property's value converted for its type, as the inspector edits it. */
|
|
862
|
+
export function propertyValue(type, text) {
|
|
863
|
+
if (type === "bool") return text === true || text === "true";
|
|
864
|
+
if (type === "int") {
|
|
865
|
+
const value = Number.parseInt(String(text), 10);
|
|
866
|
+
return Number.isFinite(value) ? value : 0;
|
|
867
|
+
}
|
|
868
|
+
if (type === "float") {
|
|
869
|
+
const value = Number.parseFloat(String(text));
|
|
870
|
+
return Number.isFinite(value) ? value : 0;
|
|
871
|
+
}
|
|
872
|
+
return String(text ?? "");
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
/**
|
|
876
|
+
* Sets one property (by name), adding it if new; `undefined` removes it.
|
|
877
|
+
* Other properties, and any fields of theirs such as `propertytype`, stay.
|
|
878
|
+
*/
|
|
879
|
+
export function setProperty(object, name, type, value) {
|
|
880
|
+
const list = Array.isArray(object.properties) ? object.properties : [];
|
|
881
|
+
const at = list.findIndex((property) => property.name === name);
|
|
882
|
+
if (value === undefined) {
|
|
883
|
+
if (at >= 0) list.splice(at, 1);
|
|
884
|
+
} else if (at >= 0) {
|
|
885
|
+
if (list[at].type !== type) list[at].type = type;
|
|
886
|
+
list[at].value = value;
|
|
887
|
+
} else list.push({ name, type, value });
|
|
888
|
+
if (list.length && !Array.isArray(object.properties)) setKey(object, "properties", list);
|
|
889
|
+
if (!list.length && Object.hasOwn(object, "properties")) delete object.properties;
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
/** The property called `name`, as the object has it now (an undo may have replaced it). */
|
|
893
|
+
export function propertyNamed(object, name) {
|
|
894
|
+
return Array.isArray(object.properties) ? object.properties.find((property) => property.name === name) : undefined;
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
/** Renames a property, keeping its place, type and value. */
|
|
898
|
+
export function renameProperty(object, from, to) {
|
|
899
|
+
const property = object.properties?.find((entry) => entry.name === from);
|
|
900
|
+
if (property && !object.properties.some((entry) => entry.name === to)) property.name = to;
|
|
901
|
+
}
|