@margoengine/tilemap 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.
@@ -0,0 +1,602 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const e=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
5
+ import { hexColor as t } from "@margoengine/math";
6
+ //#region ../shared/errors.js
7
+ var n = (e, t) => Object.assign(Error(t), {
8
+ name: "MargoError",
9
+ code: e
10
+ }), r = (e, t) => `${e}; see https://margoengine.com/errors#${t}`, i = (e, t, i = e) => n(e, r(t, i)), a = (e, t) => TypeError(r(e, t)), o = (e, t) => RangeError(r(e, t));
11
+ //#endregion
12
+ //#region ../shared/borrowed.js
13
+ function s(e, t, n) {
14
+ return e.value = t, e.device = typeof t == "function" ? void 0 : n, e.made = void 0, e.told = !1, e;
15
+ }
16
+ function c(e, t) {
17
+ typeof e.value != "function" && (e.device ??= t);
18
+ }
19
+ var l = (e, t, n, r) => s({
20
+ name: t,
21
+ setter: n
22
+ }, e, r);
23
+ function u(e, t, n) {
24
+ let { value: r } = e;
25
+ if (typeof r == "function") return e.device !== t && (e.made = r(e.device = t)), e.made;
26
+ if (r != null) {
27
+ if (e.device ??= t, e.device === t) return r;
28
+ e.told || (e.told = !0, n?.onError(i("state", `${e.name} lost with the device; pass a function or call ${e.setter}`, "borrowed-lost")));
29
+ }
30
+ }
31
+ //#endregion
32
+ //#region ../shared/atlas-texture.js
33
+ function d(e, t, n) {
34
+ if (typeof t == "function") return {
35
+ texture: t(e),
36
+ owned: !1
37
+ };
38
+ if ("createView" in t) return {
39
+ texture: t,
40
+ owned: !1
41
+ };
42
+ let { width: r, height: i } = t, a = "data" in t ? t : void 0;
43
+ if (a && (!(r > 0) || !(i > 0) || a.data.length !== r * i * 4)) throw n();
44
+ let o = e.createTexture({
45
+ size: [r, i],
46
+ format: "rgba8unorm",
47
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT
48
+ });
49
+ return a ? e.queue.writeTexture({ texture: o }, a.data, { bytesPerRow: r * 4 }, [r, i]) : e.queue.copyExternalImageToTexture({ source: t }, { texture: o }, [r, i]), {
50
+ texture: o,
51
+ owned: !0
52
+ };
53
+ }
54
+ function f(e, t, n, r) {
55
+ let i = e.value;
56
+ if (typeof i != "function" && !("createView" in i)) return d(t, i, r);
57
+ let a = u(e, t, n);
58
+ return a && {
59
+ texture: a,
60
+ owned: !1
61
+ };
62
+ }
63
+ //#endregion
64
+ //#region ../shared/view-rect.js
65
+ function p(e) {
66
+ return e?.view?.viewport;
67
+ }
68
+ function m(e, t) {
69
+ let n = p(t);
70
+ if (!n) return;
71
+ e.setViewport(n[0], n[1], n[2], n[3], 0, 1);
72
+ let r = t.view.scissor ?? n;
73
+ e.setScissorRect(r[0], r[1], r[2], r[3]);
74
+ }
75
+ function h(e) {
76
+ return e?.view?.id ?? 0;
77
+ }
78
+ function g(e, t) {
79
+ if (!Number.isInteger(e) || e < 0 || e > 4294967295) throw RangeError(`${t} ${e} is not a 32-bit layer mask; pass an integer from 0 to 0xffffffff`);
80
+ return e >>> 0;
81
+ }
82
+ var _ = class {
83
+ constructor(e, t = () => {}) {
84
+ this.create = e, this.release = t, this.states = /* @__PURE__ */ new Map(), this.frame = 0;
85
+ }
86
+ get(e) {
87
+ let t = h(e), n = this.states.get(t);
88
+ return n || this.states.set(t, n = {
89
+ state: this.create(e),
90
+ frame: 0
91
+ }), n.frame = this.frame, n.state;
92
+ }
93
+ find(e) {
94
+ return this.states.get(e)?.state;
95
+ }
96
+ *values() {
97
+ for (let e of this.states.values()) yield e.state;
98
+ }
99
+ *drawn() {
100
+ for (let e of this.states.values()) e.frame === this.frame && (yield e.state);
101
+ }
102
+ prune() {
103
+ for (let [e, t] of this.states) t.frame < this.frame && (this.states.delete(e), this.release(t.state));
104
+ this.frame++;
105
+ }
106
+ clear() {
107
+ for (let e of this.states.values()) this.release(e.state);
108
+ this.states.clear();
109
+ }
110
+ }, v = 64, y = 4096;
111
+ function b(e, t) {
112
+ return {
113
+ chunksWide: Math.ceil(e / 64),
114
+ chunksHigh: Math.ceil(t / 64)
115
+ };
116
+ }
117
+ function x(e, t, n, r) {
118
+ let i = t * 64, a = n * 64, o = Math.max(0, Math.min(64, e.width - i)), s = Math.max(0, Math.min(64, e.height - a));
119
+ r.fill(0);
120
+ for (let t = 0; t < s; t++) {
121
+ let n = (a + t) * e.width + i;
122
+ r.set(e.data.subarray(n, n + o), t * 64);
123
+ }
124
+ }
125
+ function S(e, t, n, r) {
126
+ n.fill(0, r, r + t.length);
127
+ let i = 0;
128
+ for (let a = 0; a < e.length; a++) {
129
+ let o = e[a] & L;
130
+ if (!o) continue;
131
+ let s = t[i];
132
+ if (!s || o < s.firstGid || o >= s.firstGid + s.tileCount) {
133
+ if (i = t.findIndex((e) => o >= e.firstGid && o < e.firstGid + e.tileCount), i < 0) {
134
+ i = 0;
135
+ continue;
136
+ }
137
+ s = t[i];
138
+ }
139
+ n[r + i]++;
140
+ }
141
+ }
142
+ function C(e, t, n) {
143
+ let r = 0, i = 0, a = 0, o = 0;
144
+ for (let s of e) {
145
+ let e = Math.max(s.tileWidth, s.tileHeight), c = s.tileOffset?.[0] ?? 0, l = s.tileOffset?.[1] ?? 0;
146
+ r = Math.max(r, -c), i = Math.max(i, e - n - l), a = Math.max(a, e - t + c), o = Math.max(o, l);
147
+ }
148
+ return {
149
+ left: r,
150
+ top: i,
151
+ right: a,
152
+ bottom: o
153
+ };
154
+ }
155
+ function w(e, t, n, r, i, a, o, s, c, l, u = {
156
+ firstX: 0,
157
+ firstY: 0,
158
+ lastX: -1,
159
+ lastY: -1
160
+ }) {
161
+ let d = a * 64 * n, f = o * 64 * n;
162
+ return u.firstX = Math.max(0, Math.floor((-e - l.right * n) / d)), u.firstY = Math.max(0, Math.floor((-t - l.bottom * n) / f)), u.lastX = Math.min(s - 1, Math.ceil((r - e + l.left * n) / d) - 1), u.lastY = Math.min(c - 1, Math.ceil((i - t + l.top * n) / f) - 1), u;
163
+ }
164
+ function T(e, t) {
165
+ let n = 0;
166
+ for (let t of e) n += t.duration;
167
+ if (!(n > 0)) return -1;
168
+ let r = (t % n + n) % n;
169
+ for (let t of e) {
170
+ if (r < t.duration) return t.tileId;
171
+ r -= t.duration;
172
+ }
173
+ return e[e.length - 1].tileId;
174
+ }
175
+ function E(e) {
176
+ if (e) return t(e.length === 9 ? `#${e.slice(3)}${e.slice(1, 3)}` : e);
177
+ }
178
+ //#endregion
179
+ //#region src/renderer.ts
180
+ var D = "\nstruct Layer{size:vec2f,origin:vec2f,cell:vec2f,zoom:f32,opacity:f32,tint:vec4f,chunks:u32}\nstruct Sheet{first:u32,count:u32,columns:u32,margin:u32,tile:vec2f,step:vec2f,offset:vec2f}\n@group(0) @binding(0) var<uniform> layer:Layer;\n@group(1) @binding(0) var<storage,read> cells:array<u32>;\n@group(2) @binding(0) var<uniform> sheet:Sheet;\n@group(2) @binding(1) var<storage,read> frames:array<u32>;\n@group(2) @binding(2) var atlas:texture_2d<f32>;\nstruct Varying{\n @builtin(position) position:vec4f,\n @location(0) texel:vec2f,\n @location(1) @interpolate(flat) low:vec2f,\n @location(2) @interpolate(flat) high:vec2f,\n}\n@vertex fn vertexMain(@builtin(vertex_index) corner:u32,@builtin(instance_index) index:u32)->Varying{\n var v:Varying;\n let value=cells[index];\n let gid=value&0x0fffffffu;\n if(gid<sheet.first||gid>=sheet.first+sheet.count){v.position=vec4f(2,2,2,1);return v;}\n let id=frames[gid-sheet.first];\n let chunk=index/4096u;\n let inner=index%4096u;\n let tile=vec2u(chunk%layer.chunks,chunk/layer.chunks)*64u+vec2u(inner%64u,inner/64u);\n let c=vec2f(f32(corner&1u),f32(corner>>1u));\n let diagonal=(value&0x20000000u)!=0u;\n let drawn=select(sheet.tile,sheet.tile.yx,diagonal);\n let place=vec2f(tile)*layer.cell+vec2f(0,layer.cell.y-drawn.y)+sheet.offset;\n let p=layer.origin+(place+c*drawn)*layer.zoom;\n v.position=vec4f(p/layer.size*vec2f(2,-2)+vec2f(-1,1),0,1);\n\n var s=c;\n if((value&0x80000000u)!=0u){s.x=1-s.x;}\n if((value&0x40000000u)!=0u){s.y=1-s.y;}\n if(diagonal){s=s.yx;}\n let corner0=vec2f(f32(sheet.margin))+vec2f(f32(id%sheet.columns),f32(id/sheet.columns))*sheet.step;\n v.texel=corner0+s*sheet.tile;\n v.low=corner0;\n v.high=corner0+sheet.tile-1;\n return v;\n}\n@fragment fn fragmentMain(v:Varying)->@location(0) vec4f{\n var color=textureLoad(atlas,vec2i(clamp(floor(v.texel),v.low,v.high)),0)*layer.tint;\n color.a*=layer.opacity;\n if(color.a==0){discard;}\n return color;\n}", O = 256, k = 64, A = 40, j = 0, M = class t {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
181
+ constructor(e) {
182
+ if (this.time = 0, this.visible = !0, this.stats = {
183
+ draws: 0,
184
+ uploadedBytes: 0
185
+ }, this.slots = /* @__PURE__ */ new Map(), this.sets = [], this.runs = [], this.pipelines = /* @__PURE__ */ new Map(), this.chunk = new Uint32Array(y), this.range = {
186
+ firstX: 0,
187
+ firstY: 0,
188
+ lastX: -1,
189
+ lastY: -1
190
+ }, this.offsets = /* @__PURE__ */ new Uint32Array(1), this.next = new Float32Array(k / 4), this.words = new Uint32Array(this.next.buffer), this.animatedAt = NaN, this.disposed = !1, this.states = new _(() => ({ values: /* @__PURE__ */ new Float32Array() }), (e) => e.buffer?.destroy()), this.attachments = [{
191
+ view: void 0,
192
+ loadOp: "load",
193
+ storeOp: "store"
194
+ }], this.pass = { colorAttachments: this.attachments }, !e?.map) throw a("TileMap needs a map", "tilemap-options");
195
+ if (!e.atlases) throw a("TileMap needs atlases", "tilemap-options");
196
+ let t = e.order ?? 10;
197
+ if (!Number.isFinite(t)) throw o("Invalid tile map order", "tilemap-options");
198
+ if (e.clear && (e.clear.length !== 4 || !e.clear.every(Number.isFinite))) throw o("Invalid tile map clear", "tilemap-options");
199
+ this.atlases = { ...e.atlases }, this.names = e.mapLayers, this.camera = e.camera ?? {
200
+ x: 0,
201
+ y: 0,
202
+ zoom: 1
203
+ }, this.snap = e.snap ?? !0, this.parallax = e.parallax ?? !0, this.setTarget(e.target), this.clear = e.clear, this.order = t, this.layerMask = g(e.layers ?? 1, "TileMap layers"), this.name = e.name ?? `tilemap-${++j}`, this.setMap(e.map);
204
+ }
205
+ static attach(n, r) {__margoAssertCore(n,__margoCoreRequirement("0.1.0",import.meta.url));
206
+ let i = new t(r);
207
+ return e(n).use(i), i;
208
+ }
209
+ get map() {
210
+ return this.data;
211
+ }
212
+ setMap(e) {
213
+ if (this.disposed) throw i("disposed", "TileMap disposed", "disposed");
214
+ if (!e) throw a("TileMap needs a map", "tilemap-options");
215
+ if ((e.orientation ?? "orthogonal") !== "orthogonal") throw o("TileMap draws orthogonal maps; draw this one with GridTileMap", "tilemap-options");
216
+ let t = e.layers.filter((e) => e.type === "tile");
217
+ for (let e of this.names ?? []) if (!t.some((t) => t.name === e)) throw o("Unknown tile layer", "tilemap-options");
218
+ this.releaseMap(), this.data = e;
219
+ let n = [...e.tilesets].sort((e, t) => e.firstGid - t.firstGid);
220
+ this.sets = n.map((e) => {
221
+ let t = new Uint32Array(Math.max(1, e.tileCount));
222
+ for (let e = 0; e < t.length; e++) t[e] = e;
223
+ return {
224
+ set: e,
225
+ frames: t,
226
+ animated: (e.tiles ?? []).flatMap((e) => e.animation?.length ? [{
227
+ id: e.id,
228
+ steps: e.animation
229
+ }] : [])
230
+ };
231
+ }), this.reach = C(n, e.tileWidth, e.tileHeight), this.runs = t.filter((e) => !this.names || this.names.includes(e.name)).map((e) => {
232
+ let { chunksWide: t, chunksHigh: r } = b(e.width, e.height), i = t * r, a = /* @__PURE__ */ new Set();
233
+ for (let e = 0; e < i; e++) a.add(e);
234
+ return {
235
+ layer: e,
236
+ chunksWide: t,
237
+ chunksHigh: r,
238
+ counts: new Uint32Array(i * n.length),
239
+ used: new Uint8Array(n.length),
240
+ dirty: a
241
+ };
242
+ }), this.animatedAt = NaN;
243
+ }
244
+ setTarget(e) {
245
+ this.target = e, this.targetSlot = l(typeof e == "function" ? void 0 : e, "TileMap target", "setTarget", this.engine?.gpu);
246
+ }
247
+ setAtlas(e, t) {
248
+ if (!t) throw a("TileMap needs atlases", "tilemap-options");
249
+ this.atlases[e] = t, this.slots.set(e, l(t, "TileMap atlas", "setAtlas", this.engine?.gpu));
250
+ for (let t of this.sets) t.set.name === e && (t.atlas?.owned && t.atlas.texture.destroy(), t.atlas = t.group = void 0);
251
+ }
252
+ setTile(e, t, n, r) {
253
+ let i = this.runFor(e);
254
+ if (!Number.isInteger(t) || !Number.isInteger(n) || t < 0 || n < 0 || t >= i.layer.width || n >= i.layer.height) throw o("Tile outside the layer", "tilemap-options");
255
+ i.layer.data[n * i.layer.width + t] = r, i.dirty.add((n >> 6) * i.chunksWide + (t >> 6));
256
+ }
257
+ invalidate(e) {
258
+ for (let t of e === void 0 ? this.runs : [this.runFor(e)]) for (let e = 0; e < t.chunksWide * t.chunksHigh; e++) t.dirty.add(e);
259
+ }
260
+ setup(e) {
261
+ if (this.disposed || e.backend !== "webgpu") throw i(this.disposed ? "disposed" : "unsupported", this.disposed ? "TileMap disposed" : "TileMap needs WebGPU", this.disposed ? "disposed" : "webgpu");
262
+ this.engine = e, c(this.targetSlot, e.gpu);
263
+ for (let t of this.slots.values()) c(t, e.gpu);
264
+ e.frameGraph.add({
265
+ name: this.name,
266
+ order: this.order,
267
+ execute: (e) => {
268
+ e.backend === "webgpu" && this.draw(e);
269
+ }
270
+ });
271
+ }
272
+ advanceTime(e) {
273
+ e > 0 && (this.time += e * 1e3);
274
+ }
275
+ onPreUpdate(e) {
276
+ e > 0 && this.states.prune(), this.advanceTime(e), this.stats.draws = this.stats.uploadedBytes = 0;
277
+ }
278
+ onDeviceRestored() {
279
+ this.releaseDevice();
280
+ }
281
+ dispose() {
282
+ this.disposed || (this.disposed = !0, this.engine?.sceneOf(this)?.removePlugin(this.name), this.engine = void 0, this.releaseDevice());
283
+ }
284
+ [Symbol.dispose ?? Symbol()]() {
285
+ this.dispose();
286
+ }
287
+ runFor(e) {
288
+ let t = this.runs.find((t) => t.layer === e || t.layer.name === e);
289
+ if (!t) throw o("Unknown tile layer", "tilemap-options");
290
+ return t;
291
+ }
292
+ releaseMap() {
293
+ for (let e of this.sets) e.atlas?.owned && e.atlas.texture.destroy(), e.framesBuffer?.destroy(), e.uniform?.destroy();
294
+ for (let e of this.runs) e.buffer?.destroy();
295
+ }
296
+ releaseDevice() {
297
+ this.states.clear(), this.releaseMap();
298
+ for (let e of this.sets) e.atlas = e.framesBuffer = e.uniform = e.group = void 0;
299
+ for (let e of this.runs) {
300
+ e.buffer = e.group = void 0;
301
+ for (let t = 0; t < e.chunksWide * e.chunksHigh; t++) e.dirty.add(t);
302
+ }
303
+ this.module = this.layerLayout = this.cellsLayout = this.setLayout = this.pipelineLayout = this.device = void 0, this.targetTexture = void 0, this.targetView = void 0, this.pipelines.clear(), this.animatedAt = NaN;
304
+ }
305
+ prepare(e) {
306
+ this.device !== e && (this.device && this.releaseDevice(), this.device = e), !this.module && (this.layerLayout = e.createBindGroupLayout({ entries: [{
307
+ binding: 0,
308
+ visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
309
+ buffer: {
310
+ type: "uniform",
311
+ hasDynamicOffset: !0,
312
+ minBindingSize: k
313
+ }
314
+ }] }), this.cellsLayout = e.createBindGroupLayout({ entries: [{
315
+ binding: 0,
316
+ visibility: GPUShaderStage.VERTEX,
317
+ buffer: { type: "read-only-storage" }
318
+ }] }), this.setLayout = e.createBindGroupLayout({ entries: [
319
+ {
320
+ binding: 0,
321
+ visibility: GPUShaderStage.VERTEX,
322
+ buffer: { type: "uniform" }
323
+ },
324
+ {
325
+ binding: 1,
326
+ visibility: GPUShaderStage.VERTEX,
327
+ buffer: { type: "read-only-storage" }
328
+ },
329
+ {
330
+ binding: 2,
331
+ visibility: GPUShaderStage.FRAGMENT,
332
+ texture: { sampleType: "unfilterable-float" }
333
+ }
334
+ ] }), this.pipelineLayout = e.createPipelineLayout({ bindGroupLayouts: [
335
+ this.layerLayout,
336
+ this.cellsLayout,
337
+ this.setLayout
338
+ ] }), this.module = e.createShaderModule({
339
+ label: "tilemap",
340
+ code: D
341
+ }));
342
+ }
343
+ pipeline(e, t, n) {
344
+ let r = `${t}/${n}`, i = this.pipelines.get(r);
345
+ return i || (i = e.createRenderPipeline({
346
+ label: "tilemap",
347
+ layout: this.pipelineLayout,
348
+ vertex: {
349
+ module: this.module,
350
+ entryPoint: "vertexMain"
351
+ },
352
+ fragment: {
353
+ module: this.module,
354
+ entryPoint: "fragmentMain",
355
+ targets: [{
356
+ format: t,
357
+ blend: {
358
+ color: {
359
+ srcFactor: "src-alpha",
360
+ dstFactor: "one-minus-src-alpha"
361
+ },
362
+ alpha: {
363
+ srcFactor: "one",
364
+ dstFactor: "one-minus-src-alpha"
365
+ }
366
+ }
367
+ }]
368
+ },
369
+ primitive: { topology: "triangle-strip" },
370
+ multisample: { count: n }
371
+ }), this.pipelines.set(r, i)), i;
372
+ }
373
+ flush(e) {
374
+ let t = this.sets.length, n = this.sets.map((e) => e.set);
375
+ for (let r of this.runs) {
376
+ let { layer: i, chunksWide: a } = r;
377
+ if (!r.buffer && a) {
378
+ let t = r.chunksWide * r.chunksHigh * y * 4;
379
+ if (t > e.limits.maxStorageBufferBindingSize) throw o("Tile layer too large for the device", "tilemap-options");
380
+ r.buffer = e.createBuffer({
381
+ label: "tilemap cells",
382
+ size: t,
383
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
384
+ }), r.group = e.createBindGroup({
385
+ layout: this.cellsLayout,
386
+ entries: [{
387
+ binding: 0,
388
+ resource: { buffer: r.buffer }
389
+ }]
390
+ });
391
+ }
392
+ for (let o of r.dirty) x(i, o % a, Math.floor(o / a), this.chunk), S(this.chunk, n, r.counts, o * t), e.queue.writeBuffer(r.buffer, o * y * 4, this.chunk), this.stats.uploadedBytes += y * 4;
393
+ if (r.dirty.size) {
394
+ r.used.fill(0);
395
+ for (let e = 0; e < r.counts.length; e++) r.counts[e] && (r.used[e % t] = 1);
396
+ }
397
+ r.dirty.clear();
398
+ }
399
+ }
400
+ slot(e) {
401
+ let t = this.slots.get(e);
402
+ return t || (t = l(this.atlases[e], "TileMap atlas", "setAtlas", this.engine?.gpu), this.slots.set(e, t)), t;
403
+ }
404
+ setGroup(e, t) {
405
+ if (t.group) return t.group;
406
+ let { set: n } = t, r = n.spacing ?? 0, s = n.margin ?? 0;
407
+ if (!n.columns) throw i("unsupported", "Image collection tilesets are not drawn", "tilemap-state");
408
+ if (!this.atlases[n.name]) throw a("Tileset has no atlas", "tilemap-options");
409
+ if (t.atlas ??= f(this.slot(n.name), e, this.engine, () => o("Invalid tile atlas pixels", "tilemap-options")), !t.atlas) return;
410
+ let c = t.atlas.texture, l = Math.ceil(n.tileCount / n.columns);
411
+ if (s + n.columns * (n.tileWidth + r) - r > c.width || s + l * (n.tileHeight + r) - r > c.height) throw o("Tileset larger than its atlas", "tilemap-options");
412
+ if (!t.uniform) {
413
+ let i = /* @__PURE__ */ new ArrayBuffer(A), a = new Uint32Array(i), o = new Float32Array(i);
414
+ a[0] = n.firstGid, a[1] = n.tileCount, a[2] = n.columns, a[3] = s, o[4] = n.tileWidth, o[5] = n.tileHeight, o[6] = n.tileWidth + r, o[7] = n.tileHeight + r, o[8] = n.tileOffset?.[0] ?? 0, o[9] = n.tileOffset?.[1] ?? 0, t.uniform = e.createBuffer({
415
+ label: "tilemap set",
416
+ size: A,
417
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
418
+ }), e.queue.writeBuffer(t.uniform, 0, i), t.framesBuffer = e.createBuffer({
419
+ label: "tilemap frames",
420
+ size: t.frames.byteLength,
421
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
422
+ }), e.queue.writeBuffer(t.framesBuffer, 0, t.frames);
423
+ }
424
+ return t.group = e.createBindGroup({
425
+ layout: this.setLayout,
426
+ entries: [
427
+ {
428
+ binding: 0,
429
+ resource: { buffer: t.uniform }
430
+ },
431
+ {
432
+ binding: 1,
433
+ resource: { buffer: t.framesBuffer }
434
+ },
435
+ {
436
+ binding: 2,
437
+ resource: c.createView()
438
+ }
439
+ ]
440
+ }), t.group;
441
+ }
442
+ animate(e) {
443
+ if (this.animatedAt !== this.time) {
444
+ this.animatedAt = this.time;
445
+ for (let t of this.sets) for (let { id: n, steps: r } of t.animated) {
446
+ let i = T(r, this.time);
447
+ i >= 0 && t.frames[n] !== i && (t.frames[n] = i, t.framesBuffer && e.queue.writeBuffer(t.framesBuffer, n * 4, t.frames, n, 1));
448
+ }
449
+ }
450
+ }
451
+ origin(e, t, n) {
452
+ let { layer: r } = e, i = ((r.offset?.[n] ?? 0) - (n ? t.y : t.x) * (this.parallax ? r.parallax?.[n] ?? 1 : 1)) * t.zoom;
453
+ return this.snap ? Math.round(i) : i;
454
+ }
455
+ draw(e) {
456
+ if (!this.visible) return;
457
+ let t = e.view;
458
+ if (t?.layers !== void 0 && !(t.layers & this.layerMask)) return;
459
+ let n = this.target, r = typeof n == "function" ? n() : n && u(this.targetSlot, e.device, this.engine);
460
+ if (n && typeof n != "function" && !r || r && t?.index) return;
461
+ let i = e.device, a = this.camera;
462
+ if (!(a.zoom > 0) || !Number.isFinite(a.x + a.y + a.zoom)) throw o("Invalid tile map camera", "tilemap-options");
463
+ this.prepare(i), this.flush(i), this.animate(i);
464
+ let s = r ? r.width : t ? t.viewport[2] : e.width, c = r ? r.height : t ? t.viewport[3] : e.height, l = r ? r.format : e.format, d = r ? r.sampleCount : e.descriptor.multisample?.count ?? 1, f = this.attachments[0];
465
+ if (f.view = e.color, f.loadOp = "load", r && (r !== this.targetTexture && (this.targetTexture = r, this.targetView = r.createView()), f.view = this.targetView, this.clear !== !1)) {
466
+ let e = this.clear ?? E(this.data.backgroundColor) ?? [
467
+ 0,
468
+ 0,
469
+ 0,
470
+ 0
471
+ ], t = e[3];
472
+ f.loadOp = "clear", f.clearValue = this.clear ? [...e] : [
473
+ e[0] * t,
474
+ e[1] * t,
475
+ e[2] * t,
476
+ t
477
+ ];
478
+ }
479
+ let p = this.states.get(e), h = this.runs, g = h.length * (O / 4);
480
+ g && p.values.length < g && (p.values = new Float32Array(g), p.buffer?.destroy(), p.buffer = i.createBuffer({
481
+ label: "tilemap layers",
482
+ size: p.values.byteLength,
483
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
484
+ }), p.group = i.createBindGroup({
485
+ layout: this.layerLayout,
486
+ entries: [{
487
+ binding: 0,
488
+ resource: {
489
+ buffer: p.buffer,
490
+ size: k
491
+ }
492
+ }]
493
+ }));
494
+ for (let e of h) if (e.layer.visible !== !1 && e.layer.opacity !== 0) for (let t = 0; t < this.sets.length; t++) e.used[t] && this.setGroup(i, this.sets[t]);
495
+ let _ = e.encoder.beginRenderPass(this.pass);
496
+ r || m(_, e), _.setPipeline(this.pipeline(i, l, d));
497
+ let v = this.sets, b = this.data, x = this.next, S = this.range;
498
+ for (let e = 0; e < h.length; e++) {
499
+ let t = h[e], { layer: n, chunksWide: r, chunksHigh: o } = t, l = n.opacity ?? 1;
500
+ if (n.visible === !1 || !l || !r) continue;
501
+ let u = this.origin(t, a, 0), d = this.origin(t, a, 1), f = E(n.tint) ?? [
502
+ 1,
503
+ 1,
504
+ 1,
505
+ 1
506
+ ];
507
+ x[0] = s, x[1] = c, x[2] = u, x[3] = d, x[4] = b.tileWidth, x[5] = b.tileHeight, x[6] = a.zoom, x[7] = l, x.set(f, 8), this.words[12] = r;
508
+ let m = O / 4 * e, g = !1;
509
+ for (let e = 0; e < x.length; e++) p.values[m + e] !== x[e] && (p.values[m + e] = x[e], g = !0);
510
+ g && i.queue.writeBuffer(p.buffer, m * 4, p.values, m, k / 4), w(u, d, a.zoom, s, c, b.tileWidth, b.tileHeight, r, o, this.reach, S), this.offsets[0] = e * O, _.setBindGroup(0, p.group, this.offsets), _.setBindGroup(1, t.group);
511
+ for (let e = 0; e < v.length; e++) {
512
+ let n = v[e].group;
513
+ if (t.used[e] && n) {
514
+ _.setBindGroup(2, n);
515
+ for (let n = S.firstY; n <= S.lastY; n++) for (let i = S.firstX; i <= S.lastX; i++) {
516
+ let a = n * r + i;
517
+ t.counts[a * v.length + e] && (_.draw(4, y, 0, a * y), this.stats.draws++);
518
+ }
519
+ }
520
+ }
521
+ }
522
+ _.end();
523
+ }
524
+ }, N = 2147483648, P = 1073741824, F = 536870912, I = 3758096384, L = 268435455;
525
+ function R(e) {
526
+ let t = e >>> 0;
527
+ return {
528
+ gid: t & L,
529
+ flipH: (t & N) !== 0,
530
+ flipV: (t & P) !== 0,
531
+ flipD: (t & F) !== 0
532
+ };
533
+ }
534
+ function z(e, t = 0) {
535
+ if (!Number.isInteger(e) || e < 0 || e > 268435455) throw RangeError(`gid must be an integer 0..${L}, got ${e}; split flip bits off with decodeTile.`);
536
+ return (e | t & I) >>> 0;
537
+ }
538
+ function B(e, t, n, r) {
539
+ if (!Number.isInteger(t) || !Number.isInteger(n) || t < 0 || n < 0) throw RangeError(`layer size must be non-negative integers, got ${t} x ${n}.`);
540
+ if (r && r.length !== t * n) throw RangeError(`layer data has ${r.length} values, expected ${t * n}; pass width * height of them.`);
541
+ return {
542
+ type: "tile",
543
+ name: e,
544
+ width: t,
545
+ height: n,
546
+ data: r ?? new Uint32Array(t * n)
547
+ };
548
+ }
549
+ function V(e, t) {
550
+ let n = t & L;
551
+ if (n === 0) return;
552
+ let r;
553
+ for (let t of e.tilesets) t.firstGid <= n && n < t.firstGid + t.tileCount && (!r || t.firstGid > r.firstGid) && (r = t);
554
+ return r;
555
+ }
556
+ function H(e, t) {
557
+ let n = V(e, t);
558
+ if (!n) return;
559
+ let r = (t & L) - n.firstGid;
560
+ return n.tiles?.find((e) => e.id === r);
561
+ }
562
+ function U(e, t, n) {
563
+ return t >= 0 && n >= 0 && t < e.width && n < e.height ? e.data[n * e.width + t] : 0;
564
+ }
565
+ function W(e) {
566
+ let t = (e, t, n = 1) => {
567
+ if (!Number.isInteger(e) || e < n) throw RangeError(`${t} must be an integer of ${n} or more, got ${e}.`);
568
+ };
569
+ if (t(e.width, "map.width", 0), t(e.height, "map.height", 0), t(e.tileWidth, "map.tileWidth"), t(e.tileHeight, "map.tileHeight"), e.orientation !== void 0 && ![
570
+ "orthogonal",
571
+ "isometric",
572
+ "staggered",
573
+ "hexagonal"
574
+ ].includes(e.orientation)) throw RangeError(`map.orientation is "${e.orientation}"; use orthogonal, isometric, staggered or hexagonal.`);
575
+ if (!Array.isArray(e.tilesets) || !Array.isArray(e.layers)) throw TypeError("map.tilesets and map.layers must be arrays; pass [] for none.");
576
+ let n = 1;
577
+ for (let r of [...e.tilesets].sort((e, t) => e.firstGid - t.firstGid)) {
578
+ let e = `tileset "${r.name}"`;
579
+ if (t(r.firstGid, `${e} firstGid`), t(r.tileCount, `${e} tileCount`, 0), t(r.tileWidth, `${e} tileWidth`), t(r.tileHeight, `${e} tileHeight`), r.firstGid < n) throw RangeError(`${e} starts at gid ${r.firstGid}, inside the previous tileset (free from ${n}); raise its firstGid.`);
580
+ n = r.firstGid + r.tileCount;
581
+ for (let t of r.tiles ?? []) {
582
+ if (!Number.isInteger(t.id) || t.id < 0 || t.id >= r.tileCount) throw RangeError(`${e} has a tile entry with id ${t.id}, outside 0..${r.tileCount - 1}; raise tileCount or fix the id.`);
583
+ for (let n of t.animation ?? []) {
584
+ if (!Number.isInteger(n.tileId) || n.tileId < 0 || n.tileId >= r.tileCount) throw RangeError(`${e} tile ${t.id} animates to tile ${n.tileId}, outside 0..${r.tileCount - 1}; point it at a tile of this set.`);
585
+ if (!(n.duration > 0) || !Number.isFinite(n.duration)) throw RangeError(`${e} tile ${t.id} has a frame duration of ${n.duration}; use a positive number of milliseconds.`);
586
+ }
587
+ }
588
+ }
589
+ for (let t of e.layers) {
590
+ if (t.opacity !== void 0 && !(t.opacity >= 0 && t.opacity <= 1)) throw RangeError(`layer "${t.name}" opacity must be 0..1, got ${t.opacity}.`);
591
+ if (t.type === "tile") {
592
+ if (!(t.data instanceof Uint32Array)) throw TypeError(`layer "${t.name}" data must be a Uint32Array; wrap plain arrays with new Uint32Array(values).`);
593
+ if (t.data.length !== t.width * t.height) throw RangeError(`layer "${t.name}" has ${t.data.length} values for ${t.width} x ${t.height} tiles; resize the array to width * height.`);
594
+ } else if (t.type === "object") {
595
+ if (!Array.isArray(t.objects)) throw TypeError(`layer "${t.name}" objects must be an array.`);
596
+ } else if (t.type === "image") {
597
+ if (!t.image?.source) throw TypeError(`layer "${t.name}" needs an image source; pass its path.`);
598
+ } else throw TypeError(`layer "${t.name}" has an unknown type; use 'tile', 'object' or 'image'.`);
599
+ }
600
+ }
601
+ //#endregion
602
+ export { a as A, g as C, u as D, c as E, i as O, m as S, l as T, x as _, L as a, w as b, z as c, V as d, W as f, b as g, T as h, P as i, o as k, U as l, v as m, N as n, B as o, M as p, I as r, R as s, F as t, H as u, E as v, f as w, _ as x, C as y };
@@ -0,0 +1,89 @@
1
+ import { c as e } from "./import-DsL40A38.js";
2
+ import { decodeXML as t, readXMLTree as n } from "@margoengine/loaders/xml";
3
+ //#region src/tiled-xml.ts
4
+ var r = /* @__PURE__ */ new Set([
5
+ "name",
6
+ "type",
7
+ "class",
8
+ "source",
9
+ "image",
10
+ "template",
11
+ "color",
12
+ "fontfamily",
13
+ "halign",
14
+ "valign",
15
+ "orientation",
16
+ "renderorder",
17
+ "draworder",
18
+ "staggeraxis",
19
+ "staggerindex",
20
+ "tintcolor",
21
+ "backgroundcolor",
22
+ "encoding",
23
+ "compression",
24
+ "objectalignment"
25
+ ]), i = /* @__PURE__ */ new Set([
26
+ "visible",
27
+ "wrap",
28
+ "bold",
29
+ "italic",
30
+ "underline",
31
+ "strikeout",
32
+ "kerning",
33
+ "repeatx",
34
+ "repeaty",
35
+ "infinite",
36
+ "hflip",
37
+ "vflip",
38
+ "dflip",
39
+ "rotate",
40
+ "preferuntransformed"
41
+ ]);
42
+ function a(t) {
43
+ let n = {};
44
+ for (let [a, o] of Object.entries(t.attributes)) e(n, a, r.has(a) ? o : i.has(a) ? o === "1" || o === "true" : Number.isFinite(Number(o)) ? Number(o) : o);
45
+ return n;
46
+ }
47
+ function o(e) {
48
+ let t = a(e);
49
+ if (e.name === "map" && (t.tilesets = []), (e.name === "map" || e.name === "group") && (t.layers = []), e.name === "objectgroup" && (t.objects = []), e.name === "property") {
50
+ let n = e.attributes.value ?? e.text, r = e.attributes.type ?? "string";
51
+ t.value = r === "bool" ? n === "true" || n === "1" : r === "int" || r === "float" || r === "object" ? Number(n) : n;
52
+ let i = e.children.find((e) => e.name === "properties");
53
+ i && (t.value = Object.fromEntries(i.children.map((e) => {
54
+ let t = o(e);
55
+ return [String(t.name), t.value];
56
+ })));
57
+ }
58
+ if (e.name === "text" && (t.text = e.text), e.name === "polygon" || e.name === "polyline") return { points: (e.attributes.points ?? "").trim().split(/\s+/).filter(Boolean).map((e) => {
59
+ let [t, n] = e.split(",").map(Number);
60
+ return {
61
+ x: t,
62
+ y: n
63
+ };
64
+ }) };
65
+ e.name === "wangtile" && (t.wangid = (e.attributes.wangid ?? "").split(",").map(Number));
66
+ for (let n of e.children) {
67
+ let r = o(n), i = (e) => {
68
+ (t[e] ??= []).push(r);
69
+ };
70
+ n.name === "properties" ? t.properties = n.children.map(o) : n.name === "image" ? (t.image = n.attributes.source, t.imagewidth = r.width, t.imageheight = r.height) : [
71
+ "layer",
72
+ "objectgroup",
73
+ "imagelayer",
74
+ "group"
75
+ ].includes(n.name) && (e.name === "map" || e.name === "group") ? (i("layers"), r.type = n.name === "layer" ? "tilelayer" : n.name) : n.name === "object" ? e.name === "template" ? t.object = r : i("objects") : n.name === "tileset" ? e.name === "template" ? t.tileset = r : i("tilesets") : n.name === "tile" && e.name === "tileset" ? i("tiles") : n.name === "tile" && e.name === "data" ? (t.data ??= []).push(Number(n.attributes.gid ?? 0)) : n.name === "data" ? (Object.assign(t, r), n.children.length || (t.data = n.attributes.encoding === "csv" ? n.text.trim().split(/[\s,]+/).filter(Boolean).map(Number) : n.text.trim())) : n.name === "chunk" ? (i("chunks"), r.data = e.attributes.encoding === "csv" ? n.text.trim().split(/[\s,]+/).filter(Boolean).map(Number) : n.text.trim()) : n.name === "polygon" || n.name === "polyline" ? t[n.name] = r.points : n.name === "ellipse" || n.name === "point" ? t[n.name] = !0 : n.name === "animation" ? t.animation = n.children.map(o) : n.name === "wangsets" ? t.wangsets = n.children.map(o) : n.name === "wangcolor" || n.name === "wangcornercolor" || n.name === "wangedgecolor" ? i("colors") : n.name === "wangtile" ? i("wangtiles") : t[n.name] = r;
76
+ }
77
+ return t;
78
+ }
79
+ function s(e) {
80
+ let r = n(typeof e == "string" ? e : t(e), "Tiled");
81
+ if (r.children.length !== 1 || ![
82
+ "map",
83
+ "tileset",
84
+ "template"
85
+ ].includes(r.children[0].name)) throw TypeError("Expected a Tiled map, tileset or template XML document; pass the file contents.");
86
+ return o(r.children[0]);
87
+ }
88
+ //#endregion
89
+ export { s as tiledXML };