@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.
package/dist/path.js ADDED
@@ -0,0 +1,178 @@
1
+ import { a as e } from "./src-CJvCfCkX.js";
2
+ import { r as t } from "./layout-CLx3KdGC.js";
3
+ //#region src/path.ts
4
+ function n(t, n = {}) {
5
+ let { property: r = "cost", solid: i = "solid", fallback: a = 1 } = n, o = n.empty ?? a;
6
+ if (!(a > 0)) throw RangeError(`fallback must be above 0, got ${a}.`);
7
+ let s = t.width, c = t.height, l = new Float64Array(s * c).fill(NaN), u = /* @__PURE__ */ new Map(), d = (e) => {
8
+ let n = u.get(e);
9
+ if (n !== void 0) return n;
10
+ let o;
11
+ for (let n of t.tilesets) e >= n.firstGid && e < n.firstGid + n.tileCount && (o = n.tiles?.find((t) => t.id === e - n.firstGid)?.properties);
12
+ let s = o?.[r];
13
+ return n = o?.[i] === !0 ? Infinity : typeof s == "number" && s > 0 ? s : a, u.set(e, n), n;
14
+ }, f = t.layers.filter((e) => e.type === "tile" && (!n.layers || n.layers.includes(e.name)));
15
+ for (let t of f) {
16
+ if (t.width !== s || t.height !== c) throw RangeError(`layer "${t.name}" is ${t.width} x ${t.height}, the map ${s} x ${c}; every tile layer must match the map size.`);
17
+ for (let n = 0; n < l.length; n++) {
18
+ let r = t.data[n] & e;
19
+ if (!r) continue;
20
+ let i = d(r);
21
+ l[n] = Number.isNaN(l[n]) ? i : Math.max(l[n], i);
22
+ }
23
+ }
24
+ for (let e = 0; e < l.length; e++) Number.isNaN(l[e]) && (l[e] = o);
25
+ return {
26
+ width: s,
27
+ height: c,
28
+ cost: l,
29
+ layout: t
30
+ };
31
+ }
32
+ var r = Math.SQRT2, i = (e) => e > 0 && e < Infinity, a = class {
33
+ constructor() {
34
+ this.cells = [], this.keys = [], this.order = [], this.pushed = 0;
35
+ }
36
+ get size() {
37
+ return this.cells.length;
38
+ }
39
+ less(e, t) {
40
+ return this.keys[e] < this.keys[t] || this.keys[e] === this.keys[t] && this.order[e] < this.order[t];
41
+ }
42
+ swap(e, t) {
43
+ for (let n of [
44
+ this.cells,
45
+ this.keys,
46
+ this.order
47
+ ]) [n[e], n[t]] = [n[t], n[e]];
48
+ }
49
+ push(e, t) {
50
+ let n = this.cells.length;
51
+ for (this.cells.push(e), this.keys.push(t), this.order.push(this.pushed++); n > 0;) {
52
+ let e = n - 1 >> 1;
53
+ if (!this.less(n, e)) break;
54
+ this.swap(n, e), n = e;
55
+ }
56
+ }
57
+ pop() {
58
+ let e = this.cells[0], t = this.cells.length - 1;
59
+ this.swap(0, t), this.cells.pop(), this.keys.pop(), this.order.pop();
60
+ for (let e = 0;;) {
61
+ let t = e * 2 + 1, n = t + 1, r = e;
62
+ if (t < this.cells.length && this.less(t, r) && (r = t), n < this.cells.length && this.less(n, r) && (r = n), r === e) break;
63
+ this.swap(e, r), e = r;
64
+ }
65
+ return e;
66
+ }
67
+ }, o = (e, t) => {
68
+ if (!e || !Number.isInteger(e.width) || !Number.isInteger(e.height) || e.cost?.length !== e.width * e.height) throw RangeError("a CostGrid needs whole width and height and width * height costs.");
69
+ let n = t.diagonal ?? "no-corners";
70
+ if (n !== "never" && n !== "always" && n !== "no-corners") throw RangeError(`diagonal must be never, always or no-corners, got ${n}.`);
71
+ let r = t.maxCells ?? 1e6;
72
+ if (!(r >= 1)) throw RangeError(`maxCells must be 1 or more, got ${r}.`);
73
+ let i = e.layout?.orientation ?? "orthogonal";
74
+ return {
75
+ diagonal: n,
76
+ max: r,
77
+ square: i === "orthogonal" || i === "isometric"
78
+ };
79
+ }, s = (e, n, a, o, s) => {
80
+ let { width: c, height: l, cost: u } = e, d = o % c, f = (o - d) / c, p = (e, t) => e >= 0 && t >= 0 && e < c && t < l;
81
+ if (n) {
82
+ for (let [e, t] of [
83
+ [0, -1],
84
+ [1, 0],
85
+ [0, 1],
86
+ [-1, 0]
87
+ ]) p(d + e, f + t) && i(u[(f + t) * c + d + e]) && s((f + t) * c + d + e, 1);
88
+ if (a !== "never") for (let [e, t] of [
89
+ [1, -1],
90
+ [1, 1],
91
+ [-1, 1],
92
+ [-1, -1]
93
+ ]) p(d + e, f + t) && i(u[(f + t) * c + d + e]) && (a !== "no-corners" || i(u[f * c + d + e]) && i(u[(f + t) * c + d])) && s((f + t) * c + d + e, r);
94
+ } else for (let [n, r] of t(e.layout, d, f)) p(n, r) && i(u[r * c + n]) && s(r * c + n, 1);
95
+ }, c = (e, [t, n], r) => {
96
+ if (!Number.isInteger(t) || !Number.isInteger(n) || t < 0 || n < 0 || t >= e.width || n >= e.height) throw RangeError(`${r} (${t}, ${n}) is outside the ${e.width} x ${e.height} grid; pass a cell inside it.`);
97
+ return n * e.width + t;
98
+ };
99
+ function l(e, t, n, l = {}) {
100
+ let { diagonal: d, max: f, square: p } = o(e, l), m = c(e, t, "start"), h = c(e, n, "goal"), { width: g, cost: _ } = e;
101
+ if (!i(_[h]) || !i(_[m])) return null;
102
+ let v = Infinity;
103
+ for (let e = 0; e < _.length; e++) i(_[e]) && _[e] < v && (v = _[e]);
104
+ let y = n[0], b = n[1], x = p ? void 0 : u(e.layout, y, b), S = (t) => {
105
+ let n = t % g, i = (t - n) / g;
106
+ if (x) {
107
+ let [t, r, a] = u(e.layout, n, i);
108
+ return v * Math.max(Math.abs(t - x[0]), Math.abs(r - x[1]), Math.abs(a - x[2]));
109
+ }
110
+ let a = Math.abs(n - y), o = Math.abs(i - b);
111
+ return v * (d === "never" ? a + o : Math.max(a, o) + (r - 1) * Math.min(a, o));
112
+ }, C = new Float64Array(_.length).fill(Infinity), w = new Int32Array(_.length).fill(-1), T = new Uint8Array(_.length), E = new a();
113
+ C[m] = 0, E.push(m, S(m));
114
+ let D = 0;
115
+ for (; E.size;) {
116
+ let t = E.pop();
117
+ if (!T[t]) {
118
+ if (T[t] = 1, t === h) break;
119
+ if (++D > f) return null;
120
+ s(e, p, d, t, (e, n) => {
121
+ let r = C[t] + _[e] * n;
122
+ r < C[e] && (C[e] = r, w[e] = t, E.push(e, r + S(e)));
123
+ });
124
+ }
125
+ }
126
+ if (!T[h]) return null;
127
+ let O = [];
128
+ for (let e = h; e !== -1; e = w[e]) O.push([e % g, Math.floor(e / g)]);
129
+ return {
130
+ cells: O.reverse(),
131
+ cost: C[h]
132
+ };
133
+ }
134
+ var u = (e, t, n) => {
135
+ let r = (e.staggerIndex ?? "odd") === "odd";
136
+ if ((e.staggerAxis ?? "y") === "y") {
137
+ let e = t - (r ? (n - (n & 1)) / 2 : (n + (n & 1)) / 2);
138
+ return [
139
+ e,
140
+ n,
141
+ -e - n
142
+ ];
143
+ }
144
+ let i = n - (r ? (t - (t & 1)) / 2 : (t + (t & 1)) / 2);
145
+ return [
146
+ t,
147
+ i,
148
+ -t - i
149
+ ];
150
+ };
151
+ function d(e, t, n = {}) {
152
+ let { diagonal: r, max: l, square: u } = o(e, n), { width: d, height: f, cost: p } = e, m = new Float64Array(p.length).fill(Infinity), h = new Int32Array(p.length).fill(-1), g = new Uint8Array(p.length), _ = new a();
153
+ for (let n of t) {
154
+ let t = c(e, n, "goal");
155
+ i(p[t]) && m[t] !== 0 && (m[t] = 0, _.push(t, 0));
156
+ }
157
+ let v = 0;
158
+ for (; _.size && v < l;) {
159
+ let t = _.pop();
160
+ g[t] || (g[t] = 1, v++, s(e, u, r, t, (e, n) => {
161
+ let r = m[t] + p[t] * n;
162
+ r < m[e] && (m[e] = r, h[e] = t, _.push(e, r));
163
+ }));
164
+ }
165
+ return {
166
+ width: d,
167
+ height: f,
168
+ distance: m,
169
+ next: h
170
+ };
171
+ }
172
+ function f(e, t, n) {
173
+ let r = [[t, n]];
174
+ for (let i = e.next[n * e.width + t], a = 0; i !== -1 && a < e.next.length; i = e.next[i], a++) r.push([i % e.width, Math.floor(i / e.width)]);
175
+ return r;
176
+ }
177
+ //#endregion
178
+ export { l as findPath, d as flowField, f as followFlow, n as tileCosts };
@@ -0,0 +1,37 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type PassContext } from '@margoengine/core/extension';
4
+ import { ObjectTileMap, type ObjectTileMapOptions } from './objects.js';
5
+ type Context = Extract<PassContext, {
6
+ backend: 'webgpu';
7
+ }>;
8
+ /** An ordered map embedded in a 3D scene. The active core camera projects the plane. */
9
+ export interface PlaneTileMapOptions extends Omit<ObjectTileMapOptions, 'target' | 'clear'> {
10
+ /** Column-major affine map-pixels-to-world transform. Default XY plane, 16 pixels/metre, map y points down. */
11
+ transform?: ArrayLike<number>;
12
+ /** Write scene depth for nonzero-alpha texels. Default true; false for blended transparent planes. */
13
+ depthWrite?: boolean;
14
+ /** Test against scene depth. Default true; false draws over scene geometry. */
15
+ depthTest?: boolean;
16
+ }
17
+ /** Draw all map layers on one transformed plane with perspective-correct texels and shared scene depth. */
18
+ export declare class PlaneTileMap extends ObjectTileMap {
19
+ /** Column-major affine map-pixels-to-world transform, read each frame. Mutable elements. */
20
+ readonly transform: Float32Array<ArrayBuffer>;
21
+ /** Read each frame. Default true. */
22
+ depthWrite: boolean;
23
+ /** Read each frame. Default true. */
24
+ depthTest: boolean;
25
+ private readonly projected;
26
+ constructor(options: PlaneTileMapOptions);
27
+ /** Create and attach a plane map to the engine. */
28
+ static attach(instance: EngineKernel, options: PlaneTileMapOptions): PlaneTileMap;
29
+ protected projection(c: Context, _width: number, _height: number): Float32Array<ArrayBuffer>;
30
+ protected bounds(): undefined;
31
+ protected depth(c: Context): {
32
+ attachment: GPURenderPassDepthStencilAttachment;
33
+ state: GPUDepthStencilState;
34
+ };
35
+ private checkTransform;
36
+ }
37
+ export {};
package/dist/plane.js ADDED
@@ -0,0 +1,76 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const n=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { k as e } from "./src-CJvCfCkX.js";
5
+ import { t } from "./objects-BK2mewd1.js";
6
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
7
+ //#region src/plane.ts
8
+ var r = class r extends t {
9
+ constructor(t) {
10
+ super({
11
+ ...t,
12
+ snap: t.snap ?? !1,
13
+ parallax: t.parallax ?? !1
14
+ }), this.projected = /* @__PURE__ */ new Float32Array(16);
15
+ let n = t.transform ?? [
16
+ 1 / 16,
17
+ 0,
18
+ 0,
19
+ 0,
20
+ 0,
21
+ -1 / 16,
22
+ 0,
23
+ 0,
24
+ 0,
25
+ 0,
26
+ 1,
27
+ 0,
28
+ 0,
29
+ 0,
30
+ 0,
31
+ 1
32
+ ];
33
+ if (n.length !== 16) throw e("Plane transform needs sixteen affine values", "tilemap-options");
34
+ this.transform = Float32Array.from(n), this.depthWrite = t.depthWrite ?? !0, this.depthTest = t.depthTest ?? !0, this.checkTransform();
35
+ }
36
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
37
+ let i = new r(t);
38
+ return n(e).use(i), i;
39
+ }
40
+ projection(e, t, n) {
41
+ this.checkTransform();
42
+ let r = e.camera.matrix, i = this.transform, a = this.projected;
43
+ for (let e = 0; e < 4; e++) for (let t = 0; t < 4; t++) {
44
+ let n = e * 4;
45
+ a[n + t] = r[t] * i[n] + r[4 + t] * i[n + 1] + r[8 + t] * i[n + 2] + r[12 + t] * i[n + 3], e < 2 && (a[n + t] *= this.camera.zoom);
46
+ }
47
+ return a;
48
+ }
49
+ bounds() {}
50
+ depth(t) {
51
+ let n = t.descriptor.depthStencil?.format;
52
+ if (!n) throw e("PlaneTileMap needs a scene depth attachment", "tilemap-options");
53
+ return {
54
+ attachment: {
55
+ view: t.depth,
56
+ depthLoadOp: "load",
57
+ depthStoreOp: "store",
58
+ ...n.includes("stencil") ? {
59
+ stencilLoadOp: "load",
60
+ stencilStoreOp: "store"
61
+ } : {}
62
+ },
63
+ state: {
64
+ format: n,
65
+ depthCompare: this.depthTest ? "greater-equal" : "always",
66
+ depthWriteEnabled: this.depthWrite
67
+ }
68
+ };
69
+ }
70
+ checkTransform() {
71
+ let t = this.transform;
72
+ if (!t.every(Number.isFinite) || t[3] !== 0 || t[7] !== 0 || t[11] !== 0 || t[15] !== 1 || !(Math.hypot(t[1] * t[6] - t[2] * t[5], t[2] * t[4] - t[0] * t[6], t[0] * t[5] - t[1] * t[4]) > 0)) throw e("Invalid plane transform; use finite affine values and independent map axes", "tilemap-options");
73
+ }
74
+ };
75
+ //#endregion
76
+ export { r as PlaneTileMap };
@@ -0,0 +1,177 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin } from '@margoengine/core/extension';
4
+ import type { TileLayer, TileMapData } from './index.js';
5
+ /** Straight-alpha RGBA8 texels, row by row from the top: `ImageData` fits. */
6
+ export interface TilePixels {
7
+ width: number;
8
+ height: number;
9
+ data: Uint8Array | Uint8ClampedArray;
10
+ }
11
+ /**
12
+ * Where a tileset's texels come from. Pixels and `ImageBitmap`s are uploaded to an `rgba8unorm` texture the map owns and
13
+ * uploads again after a device loss. A function is called with the device, also after a device loss. A plain
14
+ * `GPUTexture` stays the caller's: held at a device restore it is reported once through `engine.onError` and its tiles
15
+ * are skipped until {@link TileMap.setAtlas} gives a new one (docs/conventions.md, "Borrowed GPU objects").
16
+ */
17
+ export type TileAtlas = TilePixels | ImageBitmap | GPUTexture | ((device: GPUDevice) => GPUTexture);
18
+ /**
19
+ * A render target, or a function read each frame for one that changes. A pixel layer's `target` fits. A plain texture
20
+ * held at a device restore is reported once through `engine.onError` and the map draws nothing until `setTarget`.
21
+ */
22
+ export type TileTarget = GPUTexture | (() => GPUTexture);
23
+ /** Map pixels to target pixels: the map point at the top left and target pixels per map pixel. A pixel layer's `camera` fits. */
24
+ export interface TileCamera {
25
+ readonly x: number;
26
+ readonly y: number;
27
+ readonly zoom: number;
28
+ }
29
+ /** Settings of {@link TileMap}, fixed when it is created except where a member says otherwise. */
30
+ export interface TileMapOptions {
31
+ /** The map to draw. Required. */
32
+ map: TileMapData;
33
+ /** The texels of each tileset by its name; a tileset no drawn tile uses can be left out. Required. */
34
+ atlases: {
35
+ readonly [tileset: string]: TileAtlas;
36
+ };
37
+ /** Read each frame. Default `{x: 0, y: 0, zoom: 1}`: map pixels are target pixels. */
38
+ camera?: TileCamera;
39
+ /** Rounds each layer's top left to a whole target pixel, read each frame. Default true. */
40
+ snap?: boolean;
41
+ /** Names of the tile layers to draw, in map order. Default every tile layer. */
42
+ mapLayers?: readonly string[];
43
+ /**
44
+ * Scrolls each map layer by its own `parallax`, read each frame. Set it to false when the camera already carries it, as
45
+ * a pixel layer's `camera` does. Default true.
46
+ */
47
+ parallax?: boolean;
48
+ /** Draw here instead of the canvas or the view's target. Default the frame's colour target. */
49
+ target?: TileTarget;
50
+ /**
51
+ * With `target`: the colour `[r, g, b, a]` (0 to 1) to clear it to first, or false to draw over it. Default the map's
52
+ * `backgroundColor`, or `[0, 0, 0, 0]` without one.
53
+ */
54
+ clear?: readonly [number, number, number, number] | false;
55
+ /** Frame-graph order. Runs after the scene (0); 40 draws after a Tonemap. Default 10. */
56
+ order?: number;
57
+ /** Render-layer bits; a view whose `layers` shares none leaves this map out. Default 1. */
58
+ layers?: number;
59
+ /** Plugin name, unique per scene. Default `tilemap-1`, `tilemap-2`, ... */
60
+ name?: string;
61
+ }
62
+ /** What the last frame cost, for a budget check or a test. */
63
+ export interface TileMapStats {
64
+ /** Draw calls in the last frame: one per visible chunk per tileset it uses. */
65
+ draws: number;
66
+ /** Bytes of tile values uploaded in the last frame: 16,384 per changed chunk. */
67
+ uploadedBytes: number;
68
+ }
69
+ /**
70
+ * Draws a {@link TileMapData}'s tile layers, one instanced draw per visible 64 x 64 chunk per tileset, with exact pixels
71
+ * when the target has one sample per pixel. Tile values live in a storage buffer and only changed chunks go up again.
72
+ * Animated tiles change a small lookup in the shader, not the cells. Orthogonal maps only; object layers are not drawn.
73
+ * WebGPU only.
74
+ * @throws TypeError / RangeError on invalid options or, in a frame, a tileset with no atlas or larger than its atlas.
75
+ * @throws MargoError `'unsupported'` on a WebGL engine or for a drawn image-collection tileset, `'disposed'` after
76
+ * `dispose()`. A plain `GPUTexture` atlas or target held at a device restore is reported once through `engine.onError`
77
+ * (`'state'`, help `borrowed-lost`) and the frame goes on without it until {@link TileMap.setAtlas} or
78
+ * {@link TileMap.setTarget} gives a new one.
79
+ */
80
+ export declare class TileMap implements EnginePlugin {
81
+ readonly name: string;
82
+ /** Map pixels to target pixels, read each frame. */
83
+ camera: TileCamera;
84
+ /** Rounds each layer's top left to a whole target pixel, read each frame. */
85
+ snap: boolean;
86
+ /** Scrolls each map layer by its own `parallax`, read each frame. */
87
+ parallax: boolean;
88
+ /** The animation clock in milliseconds. Each frame adds its delta; set it to jump or to hold a frame. */
89
+ time: number;
90
+ /** False draws nothing and costs no draw calls, uploads or target clears; true draws as before. Default true. */
91
+ visible: boolean;
92
+ /** What the last frame cost. */
93
+ readonly stats: TileMapStats;
94
+ private readonly order;
95
+ private readonly layerMask;
96
+ private target?;
97
+ private targetSlot;
98
+ private readonly clear?;
99
+ private readonly names?;
100
+ private atlases;
101
+ private readonly slots;
102
+ private data;
103
+ private sets;
104
+ private runs;
105
+ private reach;
106
+ private engine?;
107
+ private device?;
108
+ private module?;
109
+ private layerLayout?;
110
+ private cellsLayout?;
111
+ private setLayout?;
112
+ private pipelineLayout?;
113
+ private readonly pipelines;
114
+ private readonly chunk;
115
+ private readonly range;
116
+ private readonly offsets;
117
+ private readonly next;
118
+ private readonly words;
119
+ private animatedAt;
120
+ private disposed;
121
+ private readonly states;
122
+ private readonly attachments;
123
+ private readonly pass;
124
+ private targetTexture?;
125
+ private targetView?;
126
+ constructor(options: TileMapOptions);
127
+ /** Creates a map renderer and attaches it to `instance`. */
128
+ static attach(instance: EngineKernel, options: TileMapOptions): TileMap;
129
+ /** The map being drawn. */
130
+ get map(): TileMapData;
131
+ /** Draws another map from the next frame: everything goes up again. */
132
+ setMap(map: TileMapData): void;
133
+ /**
134
+ * Replaces the map's own target: a texture, a function read each frame, or undefined for the frame's colour target.
135
+ * After a device restore, hand in a texture made on `engine.gpu` here.
136
+ */
137
+ setTarget(target: TileTarget | undefined): void;
138
+ /** Replaces a tileset's atlas from the next frame. */
139
+ setAtlas(tileset: string, atlas: TileAtlas): void;
140
+ /**
141
+ * Sets one cell of a tile layer. Only that cell's chunk goes up, on the next frame. Writes straight into `layer.data`
142
+ * need {@link invalidate} instead.
143
+ * @throws RangeError for a cell outside the layer or a layer of another map.
144
+ */
145
+ setTile(layer: TileLayer | string, x: number, y: number, value: number): void;
146
+ /** Sends a layer's cells up again on the next frame, after writing into `layer.data` yourself. Default every layer. */
147
+ invalidate(layer?: TileLayer | string): void;
148
+ setup(engine: Engine): void;
149
+ /**
150
+ * Moves the tile animation clock (`time`, in milliseconds) by `delta` seconds without drawing (a delta of 0 or less
151
+ * moves nothing). Each frame update runs it, so `seek` from `@margoengine/cutscene/seek` replays it exactly.
152
+ */
153
+ advanceTime(delta: number): void;
154
+ onPreUpdate(delta: number): void;
155
+ onDeviceRestored(): void;
156
+ dispose(): void;
157
+ [Symbol.dispose]: () => void;
158
+ private runFor;
159
+ private releaseMap;
160
+ private releaseDevice;
161
+ private prepare;
162
+ private pipeline;
163
+ /** Sends changed chunks up and recounts their tilesets. Several views in a frame upload once. */
164
+ private flush;
165
+ /** The atlas slot of a tileset, made on first use from the atlas given for it. */
166
+ private slot;
167
+ /**
168
+ * The bind group of a tileset some cell uses; made on first use, so an unused tileset needs no atlas. Undefined while
169
+ * a caller's atlas is lost with the device: its tiles are skipped.
170
+ */
171
+ private setGroup;
172
+ /** Writes the frames that changed since the last time this clock value was drawn. */
173
+ private animate;
174
+ /** The layer's top left in target pixels. */
175
+ private origin;
176
+ private draw;
177
+ }