@margoengine/tilemap 0.0.0-stage → 1.0.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,444 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const _=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { C as e, D as t, E as n, O as r, S as i, T as a, a as o, d as s, f as c, h as l, k as u, v as d, w as f, x as p } from "./src-CJvCfCkX.js";
5
+ import { i as m, r as h } from "./iso-C2Hwh5Gr.js";
6
+ import { t as g } from "./layout-CLx3KdGC.js";
7
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
8
+ //#region src/object-quads.ts
9
+ function v(e, t, n) {
10
+ let i = e.tiles?.find((e) => e.id === t), a = i?.animation?.length ? l(i.animation, n) : t;
11
+ if (e.columns === 0) {
12
+ let t = e.tiles?.find((e) => e.id === a)?.image;
13
+ if (!t) throw r("state", `Tile ${a} in ${e.name} needs its image`, "tilemap-options");
14
+ return {
15
+ source: t.source,
16
+ image: !0,
17
+ texel: [0, 0],
18
+ size: [t.width, t.height]
19
+ };
20
+ }
21
+ let o = e.margin ?? 0, s = e.spacing ?? 0;
22
+ return {
23
+ source: e.name,
24
+ image: !1,
25
+ texel: [o + a % e.columns * (e.tileWidth + s), o + Math.floor(a / e.columns) * (e.tileHeight + s)],
26
+ size: [e.tileWidth, e.tileHeight]
27
+ };
28
+ }
29
+ function y(e, t = {}) {
30
+ let n = [], i = t.time ?? 0, a = e.orientation === "hexagonal", c = Math.max(e.tileWidth, e.tileHeight);
31
+ for (let t of e.tilesets) {
32
+ c = Math.max(c, t.tileWidth, t.tileHeight);
33
+ for (let e of t.tiles ?? []) e.image && (c = Math.max(c, e.image.width, e.image.height));
34
+ c += Math.max(Math.abs(t.tileOffset?.[0] ?? 0), Math.abs(t.tileOffset?.[1] ?? 0));
35
+ }
36
+ for (let l of e.layers) {
37
+ if (l.visible === !1 || l.opacity === 0 || t.mapLayers && !t.mapLayers.includes(l.name)) continue;
38
+ let f = t.camera ?? {
39
+ x: 0,
40
+ y: 0
41
+ }, p = t.parallax !== !1, m = (l.offset?.[0] ?? 0) - f.x * (p ? l.parallax?.[0] ?? 1 : 1), _ = (l.offset?.[1] ?? 0) - f.y * (p ? l.parallax?.[1] ?? 1 : 1), y = d(l.tint) ?? [
42
+ 1,
43
+ 1,
44
+ 1,
45
+ 1
46
+ ], b = [
47
+ y[0],
48
+ y[1],
49
+ y[2],
50
+ y[3] * (l.opacity ?? 1)
51
+ ], x = (e, r, i, a, o, s, c, d, f = 0, p = 0, h = 0, g = 0) => {
52
+ if (![
53
+ i,
54
+ a,
55
+ o,
56
+ s,
57
+ p,
58
+ ...d
59
+ ].every(Number.isFinite) || o < 0 || s < 0 || d.some((e) => e <= 0)) throw u("Invalid map image dimensions or transform", "tilemap-options");
60
+ if (!o || !s) return;
61
+ let v = Math.cos(p), y = Math.sin(p), x = [v * o, y * o], S = [-y * s, v * s], C = [m + i - x[0] * h - S[0] * g, _ + a - x[1] * h - S[1] * g];
62
+ if (t.view) {
63
+ let e = [
64
+ C[0],
65
+ C[0] + x[0],
66
+ C[0] + S[0],
67
+ C[0] + x[0] + S[0]
68
+ ], n = [
69
+ C[1],
70
+ C[1] + x[1],
71
+ C[1] + S[1],
72
+ C[1] + x[1] + S[1]
73
+ ], [r, i, a, o] = t.view;
74
+ if (Math.max(...e) <= r || Math.min(...e) >= a || Math.max(...n) <= i || Math.min(...n) >= o) return;
75
+ }
76
+ n.push({
77
+ source: e,
78
+ image: r,
79
+ layer: l.name,
80
+ origin: C,
81
+ axisX: x,
82
+ axisY: S,
83
+ texel: c,
84
+ size: d,
85
+ flags: f,
86
+ tint: b
87
+ });
88
+ }, S = (t, n, r, c) => {
89
+ let l = t & o, u = s(e, l);
90
+ if (!u) return;
91
+ let d = v(u, l - u.firstGid, i), f = !a && !!(t & 536870912), p = f ? d.size[1] : d.size[0], m = f ? d.size[0] : d.size[1], h = c?.width ?? p, g = c?.height ?? m, _ = (t & 2147483648 ? 1 : 0) | (t & 1073741824 ? 2 : 0) | (f ? 4 : 0), y = (c?.rotation ?? 0) * Math.PI / 180, b = 0, S = 0;
92
+ if (c) {
93
+ let t = u.objectAlignment && u.objectAlignment !== "unspecified" ? u.objectAlignment : e.orientation === "isometric" ? "bottom" : "bottomleft";
94
+ b = t.includes("left") ? 0 : t.includes("right") ? 1 : .5, S = t.includes("top") ? 0 : t.includes("bottom") ? 1 : .5;
95
+ }
96
+ let C = (u.tileOffset?.[0] ?? 0) * (c ? h / p : 1), w = (u.tileOffset?.[1] ?? 0) * (c ? g / m : 1);
97
+ n += C * Math.cos(y) - w * Math.sin(y), r += C * Math.sin(y) + w * Math.cos(y), c || (r -= g), a && t & 805306368 && (n += h * (.5 - b), r += g * (.5 - S), b = S = .5, y += ((t & 536870912 ? 1 : 0) + (t & 268435456 ? 2 : 0)) * Math.PI / 3), x(d.source, d.image, n, r, h, g, d.texel, d.size, _, y, b, S);
98
+ };
99
+ if (l.type === "tile") {
100
+ let n = t.view ?? [
101
+ 0,
102
+ 0,
103
+ Infinity,
104
+ Infinity
105
+ ], r = h(e, l, [
106
+ n[0] - m - c,
107
+ n[1] - _ - c,
108
+ n[2] - m + c,
109
+ n[3] - _ + c
110
+ ]);
111
+ if ((e.orientation ?? "orthogonal") === "orthogonal" && e.renderOrder && e.renderOrder !== "right-down") {
112
+ let t = e.renderOrder.endsWith("up"), n = e.renderOrder.startsWith("left");
113
+ r.sort((e, r) => (Math.floor(e / l.width) - Math.floor(r / l.width)) * (t ? -1 : 1) || (e % l.width - r % l.width) * (n ? -1 : 1));
114
+ }
115
+ for (let t of r) {
116
+ let n = g(e, t % l.width, Math.floor(t / l.width));
117
+ S(l.data[t], n.x, n.y + n.height);
118
+ }
119
+ } else if (l.type === "object") {
120
+ let e = l.drawOrder === "index" ? l.objects : [...l.objects].sort((e, t) => e.y - t.y);
121
+ for (let t of e) t.visible !== !1 && t.gid && S(t.gid, t.x, t.y, t);
122
+ } else {
123
+ let n = l.image, i = t.imageSize?.(n.source), a = n.width ?? i?.[0], o = n.height ?? i?.[1];
124
+ if (!(a && o)) throw r("state", `Image ${n.source} needs its dimensions`, "tilemap-options");
125
+ let s = t.view ?? [
126
+ 0,
127
+ 0,
128
+ e.width * e.tileWidth,
129
+ e.height * e.tileHeight
130
+ ], c = l.repeatX ? Math.floor((s[0] - m) / a) : 0, u = l.repeatX ? Math.ceil((s[2] - m) / a) : 1, d = l.repeatY ? Math.floor((s[1] - _) / o) : 0, f = l.repeatY ? Math.ceil((s[3] - _) / o) : 1;
131
+ for (let e = d; e < f; e++) for (let t = c; t < u; t++) x(n.source, !0, t * a, e * o, a, o, [0, 0], [a, o]);
132
+ }
133
+ }
134
+ return n;
135
+ }
136
+ //#endregion
137
+ //#region src/objects.ts
138
+ var b = `
139
+ @group(0) @binding(0) var<uniform> projection:mat4x4f;
140
+ @group(1) @binding(0) var atlas:texture_2d<f32>;
141
+ ${m}
142
+ @vertex fn vertexMain(@builtin(vertex_index) corner:u32,
143
+ @location(0) origin:vec2f,@location(1) ax:vec2f,@location(2) ay:vec2f,
144
+ @location(3) texel:vec2f,@location(4) size:vec2f,@location(5) flags:u32,@location(6) tint:u32)->Varying{
145
+ let c=vec2f(f32(corner&1u),f32(corner>>1u));
146
+ var v:Varying;
147
+ v.position=projection*vec4f(origin+c.x*ax+c.y*ay,0,1);
148
+ var s=c;
149
+ if((flags&1u)!=0u){s.x=1-s.x;}
150
+ if((flags&2u)!=0u){s.y=1-s.y;}
151
+ if((flags&4u)!=0u){s=s.yx;}
152
+ v.texel=texel+s*size;v.low=texel;v.high=texel+size-1;v.tint=unpack4x8unorm(tint);
153
+ return v;
154
+ }
155
+ @fragment fn fragmentMain(v:Varying)->@location(0) vec4f{
156
+ let color=textureLoad(atlas,vec2i(clamp(floor(v.texel),v.low,v.high)),0)*v.tint;
157
+ if(color.a==0){discard;}
158
+ return color;
159
+ }`, x = 0, S = class o {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
160
+ constructor(t) {
161
+ if (this.time = 0, this.stats = {
162
+ draws: 0,
163
+ uploadedBytes: 0
164
+ }, this.textures = /* @__PURE__ */ new Map(), this.pipelines = /* @__PURE__ */ new Map(), this.sources = {}, this.slots = /* @__PURE__ */ new Map(), this.disposed = !1, this.states = new p(() => ({ uniform: this.device.createBuffer({
165
+ size: 64,
166
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
167
+ }) }), (e) => {
168
+ e.uniform.destroy(), e.vertices?.destroy();
169
+ }), c(t.map), !t.atlases) throw r("state", "ObjectTileMap needs atlases", "tilemap-options");
170
+ if (!Number.isFinite(t.order ?? 10)) throw u("Invalid tile map order", "tilemap-options");
171
+ this.options = { ...t }, this.data = t.map, this.name = t.name ?? `object-tilemap-${++x}`, this.camera = t.camera ?? {
172
+ x: 0,
173
+ y: 0,
174
+ zoom: 1
175
+ }, this.snap = t.snap ?? !0, this.parallax = t.parallax ?? !0, this.mask = e(t.layers ?? 1, "ObjectTileMap layers");
176
+ for (let [e, n] of Object.entries(t.atlases)) this.sources[`a:${e}`] = n;
177
+ for (let [e, n] of Object.entries(t.images ?? {})) this.sources[`i:${e}`] = n;
178
+ this.setTarget(t.target);
179
+ }
180
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
181
+ let n = new o(t);
182
+ return _(e).use(n), n;
183
+ }
184
+ get map() {
185
+ return this.data;
186
+ }
187
+ setMap(e) {
188
+ this.assertLive(), c(e), this.data = e;
189
+ }
190
+ setAtlas(e, t) {
191
+ this.setSource(`a:${e}`, t);
192
+ }
193
+ setTarget(e) {
194
+ this.options.target = e, this.targetSlot = a(typeof e == "function" ? void 0 : e, "ObjectTileMap target", "setTarget", this.engine?.gpu);
195
+ }
196
+ setImage(e, t) {
197
+ this.setSource(`i:${e}`, t);
198
+ }
199
+ setup(e) {
200
+ if (this.assertLive(), e.backend !== "webgpu") throw r("unsupported", "ObjectTileMap needs WebGPU or its compatibility device", "webgpu");
201
+ this.engine = e, n(this.targetSlot, e.gpu);
202
+ for (let t of this.slots.values()) n(t, e.gpu);
203
+ e.frameGraph.add({
204
+ name: this.name,
205
+ order: this.options.order ?? 10,
206
+ execute: (e) => {
207
+ e.backend === "webgpu" && this.draw(e);
208
+ }
209
+ });
210
+ }
211
+ advanceTime(e) {
212
+ e > 0 && (this.time += e * 1e3);
213
+ }
214
+ onPreUpdate(e) {
215
+ this.advanceTime(e), e > 0 && this.states.prune();
216
+ }
217
+ onDeviceRestored() {
218
+ this.releaseDevice();
219
+ }
220
+ dispose() {
221
+ this.disposed || (this.disposed = !0, this.engine?.sceneOf(this)?.removePlugin(this.name), this.releaseDevice(), this.engine = void 0);
222
+ }
223
+ [Symbol.dispose ?? Symbol()]() {
224
+ this.dispose();
225
+ }
226
+ projection(e, t, n) {
227
+ return new Float32Array([
228
+ 2 * this.camera.zoom / t,
229
+ 0,
230
+ 0,
231
+ 0,
232
+ 0,
233
+ -2 * this.camera.zoom / n,
234
+ 0,
235
+ 0,
236
+ 0,
237
+ 0,
238
+ 1,
239
+ 0,
240
+ -1,
241
+ 1,
242
+ 0,
243
+ 1
244
+ ]);
245
+ }
246
+ bounds(e, t) {
247
+ return [
248
+ 0,
249
+ 0,
250
+ e / this.camera.zoom,
251
+ t / this.camera.zoom
252
+ ];
253
+ }
254
+ depth(e) {
255
+ return {};
256
+ }
257
+ assertLive() {
258
+ if (this.disposed) throw r("disposed", "ObjectTileMap disposed", "disposed");
259
+ }
260
+ setSource(e, t) {
261
+ this.assertLive();
262
+ let n = this.textures.get(e);
263
+ n?.owned && n.texture.destroy(), this.textures.delete(e), this.sources[e] = t, this.slots.set(e, a(t, `ObjectTileMap ${e[0] === "a" ? "atlas" : "image"}`, e[0] === "a" ? "setAtlas" : "setImage", this.engine?.gpu));
264
+ }
265
+ releaseDevice() {
266
+ this.states.clear();
267
+ for (let e of this.textures.values()) e.owned && e.texture.destroy();
268
+ this.textures.clear(), this.pipelines.clear(), this.device = this.module = this.frameLayout = this.textureLayout = void 0;
269
+ }
270
+ texture(e) {
271
+ let t = this.textures.get(e);
272
+ if (!t) {
273
+ let n = this.sources[e];
274
+ if (!n) throw r("state", `No image for ${e.slice(2)}`, "tilemap-options");
275
+ let i = this.slots.get(e);
276
+ if (!i) {
277
+ let t = e[0] === "a";
278
+ i = a(n, `ObjectTileMap ${t ? "atlas" : "image"}`, t ? "setAtlas" : "setImage", this.engine?.gpu), this.slots.set(e, i);
279
+ }
280
+ let o = f(i, this.device, this.engine, () => u("Invalid tile image pixels", "tilemap-options"));
281
+ if (!o) return;
282
+ t = {
283
+ ...o,
284
+ group: this.device.createBindGroup({
285
+ layout: this.textureLayout,
286
+ entries: [{
287
+ binding: 0,
288
+ resource: o.texture.createView()
289
+ }]
290
+ })
291
+ }, this.textures.set(e, t);
292
+ }
293
+ return t;
294
+ }
295
+ draw(e) {
296
+ if (e.view?.layers !== void 0 && !(e.view.layers & this.mask)) return;
297
+ let n = this.options.target, r = typeof n == "function" ? n() : n && t(this.targetSlot, e.device, this.engine);
298
+ if (n && typeof n != "function" && !r || r && e.view?.index) return;
299
+ if (!(this.camera.zoom > 0) || !Number.isFinite(this.camera.x + this.camera.y + this.camera.zoom)) throw u("Invalid tile map camera", "tilemap-options");
300
+ this.device !== e.device && (this.releaseDevice(), this.device = e.device);
301
+ let a = e.device;
302
+ this.module || (this.module = a.createShaderModule({
303
+ code: b,
304
+ label: "ordered tilemap"
305
+ }), this.frameLayout = a.createBindGroupLayout({ entries: [{
306
+ binding: 0,
307
+ visibility: GPUShaderStage.VERTEX,
308
+ buffer: { type: "uniform" }
309
+ }] }), this.textureLayout = a.createBindGroupLayout({ entries: [{
310
+ binding: 0,
311
+ visibility: GPUShaderStage.FRAGMENT,
312
+ texture: { sampleType: "unfilterable-float" }
313
+ }] }));
314
+ let o = r?.width ?? e.view?.viewport[2] ?? e.width, s = r?.height ?? e.view?.viewport[3] ?? e.height, c = y(this.data, {
315
+ time: this.time,
316
+ mapLayers: this.options.mapLayers,
317
+ camera: this.camera,
318
+ parallax: this.parallax,
319
+ view: this.bounds(o, s),
320
+ imageSize: (e) => {
321
+ let t = this.texture(`i:${e}`)?.texture ?? this.sources[`i:${e}`];
322
+ return t?.width ? [t.width, t.height] : void 0;
323
+ }
324
+ }), l = new Uint32Array(c.length * 12), f = new Float32Array(l.buffer), p = [];
325
+ for (let e = 0; e < c.length; e++) {
326
+ let t = c[e], n = e * 12, r = `${t.image ? "i" : "a"}:${t.source}`;
327
+ this.texture(r), f.set([
328
+ ...t.origin,
329
+ ...t.axisX,
330
+ ...t.axisY,
331
+ ...t.texel,
332
+ ...t.size
333
+ ], n), this.snap && (f[n] = Math.round(f[n] * this.camera.zoom) / this.camera.zoom, f[n + 1] = Math.round(f[n + 1] * this.camera.zoom) / this.camera.zoom), l[n + 10] = t.flags, l[n + 11] = t.tint.reduce((e, t, n) => e | Math.round(t * 255) << n * 8, 0) >>> 0;
334
+ let i = p[p.length - 1];
335
+ i?.key === r ? i.count++ : p.push({
336
+ key: r,
337
+ first: e,
338
+ count: 1
339
+ });
340
+ }
341
+ let m = this.states.get(e), h = this.projection(e, o, s), g = this.depth(e);
342
+ a.queue.writeBuffer(m.uniform, 0, h), m.group ??= a.createBindGroup({
343
+ layout: this.frameLayout,
344
+ entries: [{
345
+ binding: 0,
346
+ resource: { buffer: m.uniform }
347
+ }]
348
+ }), l.byteLength > (m.vertices?.size ?? 0) && (m.vertices?.destroy(), m.vertices = a.createBuffer({
349
+ size: Math.max(1024, l.byteLength * 2),
350
+ usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
351
+ })), l.length && a.queue.writeBuffer(m.vertices, 0, l);
352
+ let _ = {
353
+ view: r?.createView() ?? e.color,
354
+ loadOp: "load",
355
+ storeOp: "store"
356
+ };
357
+ if (r && this.options.clear !== !1) {
358
+ _.loadOp = "clear";
359
+ let e = this.options.clear ?? d(this.data.backgroundColor) ?? [
360
+ 0,
361
+ 0,
362
+ 0,
363
+ 0
364
+ ];
365
+ _.clearValue = this.options.clear ? [...e] : [
366
+ e[0] * e[3],
367
+ e[1] * e[3],
368
+ e[2] * e[3],
369
+ e[3]
370
+ ];
371
+ }
372
+ let v = r?.format ?? e.format, x = r?.sampleCount ?? e.descriptor.multisample?.count ?? 1, S = c.length ? this.pipeline(v, x, g.state) : void 0, C = e.encoder.beginRenderPass({
373
+ colorAttachments: [_],
374
+ ...g.attachment ? { depthStencilAttachment: g.attachment } : {}
375
+ });
376
+ if (r || i(C, e), S) {
377
+ C.setPipeline(S), C.setBindGroup(0, m.group), C.setVertexBuffer(0, m.vertices);
378
+ for (let e of p) {
379
+ let t = this.textures.get(e.key);
380
+ t && (C.setBindGroup(1, t.group), C.draw(4, e.count, 0, e.first));
381
+ }
382
+ }
383
+ C.end(), this.stats.draws = p.length, this.stats.uploadedBytes = l.byteLength;
384
+ }
385
+ pipeline(e, t, n) {
386
+ let r = `${e}/${t}/${n?.format ?? ""}/${n?.depthCompare ?? ""}/${n?.depthWriteEnabled ?? ""}`, i = this.pipelines.get(r);
387
+ return i || (i = this.device.createRenderPipeline({
388
+ layout: this.device.createPipelineLayout({ bindGroupLayouts: [this.frameLayout, this.textureLayout] }),
389
+ vertex: {
390
+ module: this.module,
391
+ entryPoint: "vertexMain",
392
+ buffers: [{
393
+ arrayStride: 48,
394
+ stepMode: "instance",
395
+ attributes: [
396
+ ...[
397
+ 0,
398
+ 1,
399
+ 2,
400
+ 3,
401
+ 4
402
+ ].map((e) => ({
403
+ shaderLocation: e,
404
+ offset: e * 8,
405
+ format: "float32x2"
406
+ })),
407
+ {
408
+ shaderLocation: 5,
409
+ offset: 40,
410
+ format: "uint32"
411
+ },
412
+ {
413
+ shaderLocation: 6,
414
+ offset: 44,
415
+ format: "uint32"
416
+ }
417
+ ]
418
+ }]
419
+ },
420
+ fragment: {
421
+ module: this.module,
422
+ entryPoint: "fragmentMain",
423
+ targets: [{
424
+ format: e,
425
+ blend: {
426
+ color: {
427
+ srcFactor: "src-alpha",
428
+ dstFactor: "one-minus-src-alpha"
429
+ },
430
+ alpha: {
431
+ srcFactor: "one",
432
+ dstFactor: "one-minus-src-alpha"
433
+ }
434
+ }
435
+ }]
436
+ },
437
+ primitive: { topology: "triangle-strip" },
438
+ multisample: { count: t },
439
+ ...n ? { depthStencil: n } : {}
440
+ }), this.pipelines.set(r, i)), i;
441
+ }
442
+ };
443
+ //#endregion
444
+ export { y as n, S as t };
@@ -0,0 +1,88 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin, type PassContext } from '@margoengine/core/extension';
4
+ import { type TileMapData } from './index.js';
5
+ import type { GridTileMapOptions } from './iso.js';
6
+ import type { TileAtlas, TileCamera, TileMapStats, TileTarget } from './renderer.js';
7
+ export { buildMapQuads, type TileQuad, type TileQuadOptions } from './object-quads.js';
8
+ type Context = Extract<PassContext, {
9
+ backend: 'webgpu';
10
+ }>;
11
+ /** Ordered drawing of every map layer. Image keys are image source paths; atlas keys are tileset names. */
12
+ export interface ObjectTileMapOptions extends GridTileMapOptions {
13
+ /** Per-tile collection images and image-layer sources. Default empty. */
14
+ images?: {
15
+ readonly [source: string]: TileAtlas;
16
+ };
17
+ }
18
+ /** Instanced exact-texel drawing in map order, including tile objects, image layers and image collections. */
19
+ export declare class ObjectTileMap implements EnginePlugin {
20
+ readonly name: string;
21
+ /** Read each frame. Default the identity 2D camera. */
22
+ camera: TileCamera;
23
+ /** Snap screen origins to integer pixels. Default true. */
24
+ snap: boolean;
25
+ /** Apply layer parallax. Default true. */
26
+ parallax: boolean;
27
+ /** Animation time in milliseconds. */
28
+ time: number;
29
+ /** Last frame's ordered texture runs and uploaded instance bytes. */
30
+ readonly stats: TileMapStats;
31
+ protected readonly options: ObjectTileMapOptions;
32
+ private data;
33
+ private engine?;
34
+ private device?;
35
+ private module?;
36
+ private frameLayout?;
37
+ private textureLayout?;
38
+ private readonly textures;
39
+ private readonly pipelines;
40
+ private readonly sources;
41
+ private readonly slots;
42
+ private targetSlot;
43
+ private readonly mask;
44
+ private disposed;
45
+ private readonly states;
46
+ constructor(options: ObjectTileMapOptions);
47
+ /** Create and attach an ordered map renderer. */
48
+ static attach(instance: EngineKernel, options: ObjectTileMapOptions): ObjectTileMap;
49
+ /** Current map. Runtime cell and object edits are read on the next frame. */
50
+ get map(): TileMapData;
51
+ /** Replace the map, retaining supplied images. */
52
+ setMap(map: TileMapData): void;
53
+ /** Replace a named tileset atlas. */
54
+ setAtlas(name: string, source: TileAtlas): void;
55
+ /**
56
+ * Replaces the map's own target: a texture, a function read each frame, or undefined for the frame's colour target.
57
+ * After a device restore, hand in a texture made on `engine.gpu` here.
58
+ */
59
+ setTarget(target: TileTarget | undefined): void;
60
+ /** Replace a collection tile or layer image by its source path. */
61
+ setImage(source: string, image: TileAtlas): void;
62
+ setup(engine: Engine): void;
63
+ /**
64
+ * Moves the tile animation clock (`time`, in milliseconds) by `delta` seconds without drawing (a delta of 0 or less
65
+ * moves nothing). Each frame update runs it, so `seek` from `@margoengine/cutscene/seek` replays it exactly.
66
+ */
67
+ advanceTime(delta: number): void;
68
+ onPreUpdate(delta: number): void;
69
+ onDeviceRestored(): void;
70
+ dispose(): void;
71
+ [Symbol.dispose]: () => void;
72
+ /** Projection of map pixels, including the screen camera, to clip coordinates. */
73
+ protected projection(_c: Context, width: number, height: number): Float32Array<ArrayBuffer>;
74
+ /** Culling bounds in camera-relative map pixels. */
75
+ protected bounds(width: number, height: number): readonly [number, number, number, number] | undefined;
76
+ /** Additional render-pass and pipeline settings, for scene-space consumers. */
77
+ protected depth(_c: Context): {
78
+ attachment?: GPURenderPassDepthStencilAttachment;
79
+ state?: GPUDepthStencilState;
80
+ };
81
+ private assertLive;
82
+ private setSource;
83
+ private releaseDevice;
84
+ /** The texture under `key`; undefined while a caller's texture is lost with the device: its quads are skipped. */
85
+ private texture;
86
+ private draw;
87
+ private pipeline;
88
+ }
@@ -0,0 +1 @@
1
+ export { t as ObjectTileMap, n as buildMapQuads } from "./objects-BK2mewd1.js";
package/dist/path.d.ts ADDED
@@ -0,0 +1,82 @@
1
+ import { type TileMapData } from './index.js';
2
+ import type { MapGrid } from './layout.js';
3
+ /** Cells to search: `cost[y * width + x]` is the price of stepping into a cell; 0, a negative or Infinity blocks it. */
4
+ export interface CostGrid {
5
+ readonly width: number;
6
+ readonly height: number;
7
+ readonly cost: ArrayLike<number>;
8
+ /**
9
+ * The map's layout, for staggered and hexagonal maps: steps go to the cells that share an edge. Orthogonal and
10
+ * isometric grids (and no layout) step along rows and columns, and across corners as `diagonal` allows.
11
+ */
12
+ readonly layout?: MapGrid;
13
+ }
14
+ /** Settings of {@link findPath} and {@link flowField}. */
15
+ export interface PathOptions {
16
+ /**
17
+ * Corner steps on orthogonal and isometric grids, which cost `cost * sqrt(2)`: `'never'`, `'always'`, or
18
+ * `'no-corners'` (default), which allows one only when both cells beside it are open, so paths do not cut wall corners.
19
+ */
20
+ diagonal?: 'never' | 'always' | 'no-corners';
21
+ /** Stops a search after this many cells; `findPath` then returns null. Default 1,000,000. */
22
+ maxCells?: number;
23
+ /**
24
+ * `findPath` only: jump point search, which visits far fewer cells on open maps for the same cost. It applies where it
25
+ * is exact, an orthogonal or isometric grid whose open cells all cost the same with `diagonal: 'no-corners'`; on any
26
+ * other grid the search is plain A*. Paths are cheapest ones, as plain A*'s, though where several tie the cells may
27
+ * differ. Default false.
28
+ */
29
+ jumpPoints?: boolean;
30
+ }
31
+ /** Settings of {@link tileCosts}. */
32
+ export interface TileCostOptions {
33
+ /** Tile layers to read, by name; a cell takes the highest cost of its tiles. Default every tile layer. */
34
+ layers?: readonly string[];
35
+ /** Tile property holding a cost, a number above 0. Default `'cost'`. */
36
+ property?: string;
37
+ /** Tile property that blocks a cell when true. Default `'solid'`. */
38
+ solid?: string;
39
+ /** Cost of an empty cell, or of a tile without the property. Default 1. */
40
+ fallback?: number;
41
+ /** Cost of a cell no layer has a tile in: Infinity blocks the gaps. Default `fallback`. */
42
+ empty?: number;
43
+ }
44
+ /**
45
+ * Costs from a tile map's tile properties: a tile with `solid: true` blocks its cell, one with a numeric `cost`
46
+ * sets it, others cost `fallback`. The map's layout comes along, so the grid steps as the map does.
47
+ */
48
+ export declare function tileCosts(map: TileMapData, options?: TileCostOptions): CostGrid;
49
+ /** The result of {@link findPath}: the cells from start to goal, both included, and the summed cost of the steps. */
50
+ export interface GridPath {
51
+ readonly cells: [number, number][];
52
+ readonly cost: number;
53
+ /** Cells the search took from its queue and expanded (with `jumpPoints`, the jump points). */
54
+ readonly searched: number;
55
+ /**
56
+ * Cells a jump passed over without queueing them, with `jumpPoints` (0 for plain A*). A scanned cell costs a few
57
+ * reads of the grid, an expanded one a heap pop and pushes. `maxCells` limits the two together.
58
+ */
59
+ readonly scanned: number;
60
+ }
61
+ /**
62
+ * A cheapest path from `start` to `goal` by A*, or null when the goal cannot be reached (or `maxCells` ran out). A step
63
+ * costs the cell it enters times its length (1, or sqrt(2) across a corner). The estimate is the octile distance (the
64
+ * hex distance on staggered and hexagonal maps) times the lowest cost on the grid, which never overestimates.
65
+ */
66
+ export declare function findPath(grid: CostGrid, start: readonly [number, number], goal: readonly [number, number], options?: PathOptions): GridPath | null;
67
+ /** The result of {@link flowField}. */
68
+ export interface FlowField {
69
+ readonly width: number;
70
+ readonly height: number;
71
+ /** Each cell's cost to reach the nearest goal; Infinity where none can be reached. */
72
+ readonly distance: Float64Array;
73
+ /** Each cell's next cell toward that goal, `y * width + x`; -1 at goals and where none can be reached. */
74
+ readonly next: Int32Array;
75
+ }
76
+ /**
77
+ * Every cell's cheapest cost to the nearest of `goals`, and the next cell toward it, by Dijkstra's search from the goals
78
+ * outward. Steps cost as in {@link findPath}, so following `next` from any cell walks one of its cheapest paths.
79
+ */
80
+ export declare function flowField(grid: CostGrid, goals: readonly (readonly [number, number])[], options?: PathOptions): FlowField;
81
+ /** The cells from (`x`, `y`) along a flow field to its goal, both included; just the start when it has no way. */
82
+ export declare function followFlow(field: FlowField, x: number, y: number): [number, number][];