@margoengine/voxel-edit 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.
Files changed (64) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +446 -3
  4. package/dist/animation.d.ts +50 -0
  5. package/dist/animation.js +88 -0
  6. package/dist/assist.d.ts +24 -0
  7. package/dist/assist.js +52 -0
  8. package/dist/brush-gpu.d.ts +62 -0
  9. package/dist/bytes.d.ts +55 -0
  10. package/dist/collab.d.ts +77 -0
  11. package/dist/collab.js +159 -0
  12. package/dist/edit.d.ts +30 -0
  13. package/dist/edit.js +361 -0
  14. package/dist/export.d.ts +58 -0
  15. package/dist/export.js +52 -0
  16. package/dist/file-colors-DHT5vrzW.js +55 -0
  17. package/dist/file-colors.d.ts +16 -0
  18. package/dist/format-plist.d.ts +4 -0
  19. package/dist/formats-extra.d.ts +20 -0
  20. package/dist/formats-extra.js +335 -0
  21. package/dist/formats.d.ts +96 -0
  22. package/dist/formats.js +924 -0
  23. package/dist/generate.d.ts +63 -0
  24. package/dist/generate.js +103 -0
  25. package/dist/gox.d.ts +60 -0
  26. package/dist/gpu.d.ts +74 -0
  27. package/dist/gpu.js +167 -0
  28. package/dist/grid-B2V0TGLV.js +120 -0
  29. package/dist/grid.d.ts +75 -0
  30. package/dist/history.d.ts +65 -0
  31. package/dist/history.js +75 -0
  32. package/dist/index.d.ts +5 -0
  33. package/dist/index.js +631 -0
  34. package/dist/layout.d.ts +76 -0
  35. package/dist/library.d.ts +50 -0
  36. package/dist/library.js +89 -0
  37. package/dist/mesh.d.ts +127 -0
  38. package/dist/mesh.js +365 -0
  39. package/dist/model.d.ts +173 -0
  40. package/dist/pick.d.ts +34 -0
  41. package/dist/pick.js +122 -0
  42. package/dist/raster.d.ts +89 -0
  43. package/dist/rig.d.ts +88 -0
  44. package/dist/rig.js +216 -0
  45. package/dist/select.d.ts +50 -0
  46. package/dist/select.js +94 -0
  47. package/dist/shaders-CcSeamtF.js +234 -0
  48. package/dist/shaders.d.ts +116 -0
  49. package/dist/shaders.js +1 -0
  50. package/dist/slices.d.ts +75 -0
  51. package/dist/smooth.d.ts +43 -0
  52. package/dist/smooth.js +212 -0
  53. package/dist/sparse.d.ts +239 -0
  54. package/dist/sparse.js +646 -0
  55. package/dist/stamp.d.ts +88 -0
  56. package/dist/vmax.d.ts +48 -0
  57. package/dist/vox-resolve.d.ts +64 -0
  58. package/dist/vox-scene.d.ts +51 -0
  59. package/dist/vox.d.ts +30 -0
  60. package/dist/vox.js +684 -0
  61. package/dist/voxelize.d.ts +70 -0
  62. package/dist/voxelize.js +249 -0
  63. package/dist/vxm.d.ts +54 -0
  64. package/package.json +132 -6
package/dist/assist.js ADDED
@@ -0,0 +1,52 @@
1
+ import { c as e, o as t } from "./grid-B2V0TGLV.js";
2
+ //#region src/assist.ts
3
+ function n(e, t = {}) {
4
+ let [n, r, i] = e;
5
+ if (!Number.isInteger(n) || !Number.isInteger(r) || !Number.isInteger(i) || n < 1 || r < 1 || i < 1) throw RangeError("noiseFill size must be positive integers");
6
+ let a = n * r * i;
7
+ if (a > 16777216) throw RangeError("noiseFill size exceeds 16,777,216 cells; use a smaller size");
8
+ let { threshold: o = .5, seed: s = 1, palette: c = 1 } = t;
9
+ if (!(o >= 0 && o <= 1)) throw RangeError("noiseFill threshold must be from 0 to 1");
10
+ if (!Number.isInteger(s)) throw RangeError("noiseFill seed must be an integer");
11
+ if (!Number.isInteger(c) || c < 1 || c > 255) throw RangeError("noiseFill palette must be an integer from 1 to 255");
12
+ let l = new Uint8Array(a), u = s >>> 0;
13
+ for (let e = 0; e < a; e++) u = u * 1664525 + 1013904223 >>> 0, u / 4294967296 > o && (l[e] = c);
14
+ return {
15
+ size: [
16
+ n,
17
+ r,
18
+ i
19
+ ],
20
+ voxels: l
21
+ };
22
+ }
23
+ function r(e, t = 1) {
24
+ if (!Number.isInteger(e) || e < 1 || e > 16) throw RangeError("suggestPalette count must be an integer from 1 to 16");
25
+ let n = [], r = t >>> 0;
26
+ for (let t = 0; t < e; t++) {
27
+ r = r * 1664525 + 1013904223 >>> 0;
28
+ let e = r % 360 / 360;
29
+ n.push(i(e, .6, .5));
30
+ }
31
+ return n;
32
+ }
33
+ function i(e, t, n) {
34
+ let r = t * Math.min(n, 1 - n), i = (t) => {
35
+ let i = (t + e * 12) % 12, a = n - r * Math.max(Math.min(i - 3, 9 - i, 1), -1);
36
+ return a <= .04045 ? a / 12.92 : ((a + .055) / 1.055) ** 2.4;
37
+ };
38
+ return [
39
+ i(0),
40
+ i(8),
41
+ i(4)
42
+ ];
43
+ }
44
+ function a(n, r = {}) {
45
+ if (typeof r != "object" || !r) throw TypeError("paletteUsage limits are not an object; pass {maxCells}");
46
+ e(n, t(r), "Usage grid");
47
+ let i = /* @__PURE__ */ new Uint32Array(256);
48
+ for (let e of n.voxels) i[e]++;
49
+ return i;
50
+ }
51
+ //#endregion
52
+ export { n as noiseFill, a as paletteUsage, r as suggestPalette };
@@ -0,0 +1,62 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { Vec3 } from '@margoengine/math';
3
+ import { type VoxelGrid } from './grid.js';
4
+ export declare const PRELUDE = "struct Info {\n size: vec4<i32>,\n count: u32,\n every: u32,\n pass_index: u32,\n seed: u32,\n tool_size: vec4<i32>,\n tool_offset: vec4<i32>,\n params: array<vec4<f32>, 4>,\n}\n@group(0) @binding(0) var<uniform> info: Info;\n@group(0) @binding(1) var<storage, read> source_cells: array<u32>;\n@group(0) @binding(2) var<storage, read_write> result_cells: array<u32>;\n@group(0) @binding(3) var<storage, read> selected_cells: array<u32>;\n@group(0) @binding(4) var<storage, read> tool_cells: array<u32>;\n@group(0) @binding(5) var<storage, read> lookup_table: array<u32, 256>;\nfn grid_size() -> vec3<i32> { return info.size.xyz; }\nfn inside(q: vec3<i32>) -> bool { return all(q >= vec3<i32>(0)) && all(q < info.size.xyz); }\nfn cell_index(q: vec3<i32>) -> i32 { return q.x + info.size.x * (q.z + info.size.z * q.y); }\nfn cell(q: vec3<i32>) -> u32 {\n if (!inside(q)) { return 0u; }\n let i = u32(cell_index(q));\n return (source_cells[i >> 2u] >> ((i & 3u) * 8u)) & 255u;\n}\nfn tool(q: vec3<i32>) -> u32 {\n let t = q - info.tool_offset.xyz;\n if (info.tool_size.w == 0 || any(t < vec3<i32>(0)) || any(t >= info.tool_size.xyz)) { return 0u; }\n let i = u32(t.x + info.tool_size.x * (t.z + info.tool_size.z * t.y));\n return (tool_cells[i >> 2u] >> ((i & 3u) * 8u)) & 255u;\n}\nfn lookup(i: u32) -> u32 { return lookup_table[min(i, 255u)]; }\nfn face_offset(d: i32) -> vec3<i32> {\n switch d {\n case 0: { return vec3<i32>(-1, 0, 0); }\n case 1: { return vec3<i32>(1, 0, 0); }\n case 2: { return vec3<i32>(0, -1, 0); }\n case 3: { return vec3<i32>(0, 1, 0); }\n case 4: { return vec3<i32>(0, 0, -1); }\n default: { return vec3<i32>(0, 0, 1); }\n }\n}\nfn param(i: u32) -> f32 {\n let j = min(i, 15u);\n return info.params[j >> 2u][j & 3u];\n}\nfn pass_number() -> u32 { return info.pass_index; }\nfn hash_u32(x: u32) -> u32 {\n var h = x * 747796405u + 2891336453u;\n h = ((h >> ((h >> 28u) + 4u)) ^ h) * 277803737u;\n return (h >> 22u) ^ h;\n}\nfn hash(q: vec3<i32>, salt: u32) -> f32 {\n let h = hash_u32(bitcast<u32>(q.x) ^ hash_u32(bitcast<u32>(q.y) ^ hash_u32(bitcast<u32>(q.z) ^ hash_u32(salt ^ info.seed))));\n return f32(h >> 8u) / 16777216.0;\n}\nfn noise(x: vec3<f32>) -> f32 {\n let c = floor(x);\n let f = x - c;\n let u = f * f * (3.0 - 2.0 * f);\n let i = vec3<i32>(c);\n let a = mix(hash(i, 0u), hash(i + vec3<i32>(1, 0, 0), 0u), u.x);\n let b = mix(hash(i + vec3<i32>(0, 1, 0), 0u), hash(i + vec3<i32>(1, 1, 0), 0u), u.x);\n let d = mix(hash(i + vec3<i32>(0, 0, 1), 0u), hash(i + vec3<i32>(1, 0, 1), 0u), u.x);\n let e = mix(hash(i + vec3<i32>(0, 1, 1), 0u), hash(i + vec3<i32>(1, 1, 1), 0u), u.x);\n return mix(mix(a, b, u.y), mix(d, e, u.y), u.z);\n}\n";
5
+ export declare const MAIN = "\n@compute @workgroup_size(64)\nfn brush_main(@builtin(global_invocation_id) id: vec3<u32>, @builtin(num_workgroups) groups: vec3<u32>) {\n let w = id.x + id.y * groups.x * 64u;\n if (w * 4u >= info.count) { return; }\n let row = info.size.x * info.size.z;\n var out = 0u;\n for (var k = 0u; k < 4u; k++) {\n let i = w * 4u + k;\n if (i >= info.count) { break; }\n var v = (source_cells[w] >> (k * 8u)) & 255u;\n if (info.every == 1u || ((selected_cells[w] >> (k * 8u)) & 255u) != 0u) {\n let n = i32(i);\n let y = n / row;\n let z = (n - y * row) / info.size.x;\n v = min(brush(vec3<i32>(n - y * row - z * info.size.x, y, z), v), 255u);\n }\n out |= v << (k * 8u);\n }\n result_cells[w] = out;\n}\n";
6
+ export declare const PRELUDE_LINES: number;
7
+ /** The device and pipeline of each live ShaderBrush, for GpuGrid.brush; dispose() removes its entry. */
8
+ export declare const brushPipelines: WeakMap<object, {
9
+ device: GPUDevice;
10
+ pipeline: GPUComputePipeline;
11
+ }>;
12
+ /** The full WGSL module a brush compiles to: the prelude, then `code`, then the entry point `brush_main`. */
13
+ export declare function brushSource(code: string): string;
14
+ export declare const isDevice: (device: unknown) => device is GPUDevice;
15
+ /** Compiles brush `code` on `device`, naming the line of `code` on a compile error. */
16
+ export declare function compileBrush(device: GPUDevice, code: string, label: string): Promise<GPUComputePipeline>;
17
+ /** What one {@link GridBuffers.run} reads besides the grid. */
18
+ export interface PassInputs {
19
+ passes: number;
20
+ params: readonly number[];
21
+ seed: number;
22
+ /** Packed cell mask (a byte per cell, 4 per word) or null for every cell. */
23
+ mask: Uint8Array | null;
24
+ tool: VoxelGrid | null;
25
+ toolOffset: Vec3;
26
+ /** 256 entries or null. */
27
+ table: ArrayLike<number> | null;
28
+ }
29
+ /** What a brush run may pass besides the grid, before {@link brushInputs} checks it. */
30
+ export interface BrushRunInputs {
31
+ selection?: ArrayLike<number>;
32
+ passes?: number;
33
+ params?: readonly number[];
34
+ seed?: number;
35
+ tool?: VoxelGrid;
36
+ toolOffset?: Vec3;
37
+ table?: ArrayLike<number>;
38
+ }
39
+ /**
40
+ * Checks a brush run's options for a grid of `count` cells (`toolLimit` cells at most in the tool) and packs them.
41
+ * ShaderBrush.run and GpuGrid.brush share it, so both refuse the same inputs.
42
+ */
43
+ export declare function brushInputs(options: BrushRunInputs, count: number, toolLimit: number, subject: string): PassInputs;
44
+ /** Bytes a grid of `count` cells takes on the GPU, refused past the device's binding limit. */
45
+ export declare function gridBytes(device: GPUDevice, count: number, subject: string): number;
46
+ /** A grid in two ping-pong GPU buffers (packed, a byte per cell) that brushes run on, read back on demand. */
47
+ export declare class GridBuffers {
48
+ #private;
49
+ readonly size: Vec3;
50
+ readonly count: number;
51
+ constructor(device: GPUDevice, grid: VoxelGrid, label: string);
52
+ /** The buffer holding the current cells. */
53
+ get buffer(): GPUBuffer;
54
+ /** Replaces every cell. */
55
+ write(voxels: Uint8Array): void;
56
+ /** Runs `pipeline` for `inputs.passes` passes, each reading the result of the one before. */
57
+ run(pipeline: GPUComputePipeline, inputs: PassInputs): void;
58
+ /** Reads the current cells back; rejects with the signal's reason when aborted first. */
59
+ read(signal?: AbortSignal): Promise<Uint8Array>;
60
+ /** Frees the buffers. Calling it again does nothing. */
61
+ destroy(): void;
62
+ }
@@ -0,0 +1,55 @@
1
+ /** One stretch of storage a value keeps alive; every holder of the same storage reports the same `token`. */
2
+ export interface OwnedBuffer {
3
+ /** Identity of the storage (an ArrayBuffer, or an opaque object for a sparse chunk). */
4
+ readonly token: object;
5
+ /** Bytes the storage holds, a whole number from 0. */
6
+ readonly bytes: number;
7
+ }
8
+ /** A value that lists its own storage, as `SparseGrid` does with `ownedBuffers()`. */
9
+ export interface BufferOwner {
10
+ ownedBuffers(): readonly OwnedBuffer[];
11
+ }
12
+ /**
13
+ * What {@link ownedBuffers} and {@link ByteLedger} read: an ArrayBuffer or typed array (its whole buffer), a grid,
14
+ * cel or window (`voxels`), packed frames (`banks`), an image (`data`), a {@link BufferOwner}, an {@link OwnedBuffer},
15
+ * or an array of any of these.
16
+ */
17
+ export type ByteSource = ArrayBufferLike | ArrayBufferView | {
18
+ readonly voxels: ArrayBufferView;
19
+ } | {
20
+ readonly banks: readonly ByteSource[];
21
+ } | {
22
+ readonly data: ArrayBufferView;
23
+ } | BufferOwner | OwnedBuffer | readonly ByteSource[];
24
+ /**
25
+ * The distinct storage `value` keeps alive, each listed once: a typed array charges its whole buffer (so views of one
26
+ * pool count once), a sparse grid its chunks (snapshots share untouched chunks, and so their tokens).
27
+ */
28
+ export declare function ownedBuffers(value: ByteSource): OwnedBuffer[];
29
+ /** Bytes of the distinct storage the values keep alive together: shared storage counts once. */
30
+ export declare function retainedBytes(...values: ByteSource[]): number;
31
+ /**
32
+ * A running count of the storage that held values keep alive, each buffer counted once however many values share it,
33
+ * for budgets such as an undo history: `retain` an entry's values when it is kept and `release` the same values when
34
+ * it is dropped.
35
+ */
36
+ export declare class ByteLedger {
37
+ #private;
38
+ /** Bytes of the distinct storage held. */
39
+ get bytes(): number;
40
+ /** Distinct buffers held. */
41
+ get buffers(): number;
42
+ /** Whether storage with this token is held. */
43
+ has(token: object): boolean;
44
+ /**
45
+ * Holds the storage `value` keeps alive (a buffer listed twice in one value is held once) and returns the bytes that
46
+ * were not held before.
47
+ */
48
+ retain(value: ByteSource): number;
49
+ /**
50
+ * Lets go of what an earlier `retain(value)` held and returns the bytes no other holder keeps. Nothing changes when
51
+ * `value` lists storage the ledger does not hold.
52
+ * @throws RangeError for storage that was never retained.
53
+ */
54
+ release(value: ByteSource): number;
55
+ }
@@ -0,0 +1,77 @@
1
+ import { type GridLimits, type VoxelGrid } from './grid.js';
2
+ /** One edit: cells set to values, stamped by its site's clock. Plain data; {@link encodeVoxelOp} packs it. */
3
+ export interface VoxelOp {
4
+ /** The site (user) that made it. */
5
+ readonly site: string;
6
+ /** Its place among its site's operations: 1, 2, 3 and so on with no gaps. */
7
+ readonly seq: number;
8
+ /** Its Lamport clock, from 1. */
9
+ readonly clock: number;
10
+ /** Cell indexes of the grid. */
11
+ readonly cells: Uint32Array;
12
+ /** The palette index written to each cell (0 erases). */
13
+ readonly values: Uint8Array;
14
+ }
15
+ /** A replica's state for a newcomer: the cells, each cell's stamp, and every operation seen. */
16
+ export interface VoxelReplicaSnapshot {
17
+ readonly grid: VoxelGrid;
18
+ readonly ops: readonly VoxelOp[];
19
+ }
20
+ /**
21
+ * A replica of a shared grid. {@link VoxelReplica.edit} makes a local operation (send it to the others);
22
+ * {@link VoxelReplica.apply} takes anyone's operation, in any order and any number of times. Replicas that have
23
+ * applied the same operations hold the same cells. {@link VoxelReplica.version} and {@link VoxelReplica.since} let a
24
+ * replica catch another up with only the operations it lacks.
25
+ */
26
+ export declare class VoxelReplica {
27
+ #private;
28
+ readonly site: string;
29
+ readonly size: readonly [number, number, number];
30
+ /**
31
+ * A replica of `grid` (copied) for `site`. Every replica of one shared grid starts from the same grid. A replica
32
+ * keeps 7 bytes a cell (the cell, its write's clock and site).
33
+ * @throws TypeError for a bad grid or site; RangeError past `maxCells` (default 16,777,216).
34
+ */
35
+ constructor(grid: VoxelGrid, options: {
36
+ site: string;
37
+ } & GridLimits);
38
+ /** The current cells (a copy). */
39
+ get grid(): VoxelGrid;
40
+ /** The palette index at cell `index`. */
41
+ get(index: number): number;
42
+ /**
43
+ * Per site, the count of its operations this replica holds with none missing before them (1 to n all applied).
44
+ * Send it to a peer, which answers with {@link VoxelReplica.since}. Operations applied past a gap are held but not
45
+ * counted until the gap fills, so a peer resends them; applying a repeat does nothing.
46
+ */
47
+ get version(): Record<string, number>;
48
+ /** Calls `listener(op, changed)` after each operation this replica applies, local or remote. Returns an unsubscribe. */
49
+ onChange(listener: (op: VoxelOp, changed: number) => void): () => void;
50
+ /**
51
+ * Sets `cells` (indexes) to `value`, or to `values[i]` each, as one local operation, and returns it to send.
52
+ * @throws RangeError for an index outside the grid or a value outside 0 to 255; TypeError for mismatched lengths.
53
+ */
54
+ edit(cells: ArrayLike<number>, value: number | ArrayLike<number>): VoxelOp;
55
+ /**
56
+ * Applies anyone's operation. An operation already applied does nothing; otherwise each cell takes the value when the
57
+ * operation's stamp (clock, then site name) is higher than the stamp of the cell's last write. Returns the cells
58
+ * whose value changed.
59
+ * @throws TypeError or RangeError for a malformed operation or one for a grid of another size.
60
+ */
61
+ apply(op: VoxelOp): number;
62
+ /** The operations this replica has that a replica at `version` (from {@link VoxelReplica.version}) lacks. */
63
+ since(version?: Readonly<Record<string, number>>): VoxelOp[];
64
+ /** The starting grid and every operation, for a newcomer: `VoxelReplica.fromSnapshot(snapshot, {site})`. */
65
+ snapshot(): VoxelReplicaSnapshot;
66
+ /** A replica for `site` built from another replica's {@link VoxelReplica.snapshot}. */
67
+ static fromSnapshot(snapshot: VoxelReplicaSnapshot, options: {
68
+ site: string;
69
+ } & GridLimits): VoxelReplica;
70
+ }
71
+ /**
72
+ * Packs an operation into bytes for the network: `MVOP`, version 1, site length (u16) and UTF-8 site, seq, clock and
73
+ * count (u32 each), then the cell indexes (u32) and values (u8), little-endian.
74
+ */
75
+ export declare function encodeVoxelOp(op: VoxelOp): Uint8Array;
76
+ /** Unpacks {@link encodeVoxelOp}'s bytes. @throws RangeError for bytes that are not a whole version 1 operation. */
77
+ export declare function decodeVoxelOp(bytes: Uint8Array): VoxelOp;
package/dist/collab.js ADDED
@@ -0,0 +1,159 @@
1
+ import { c as e, l as t, o as n } from "./grid-B2V0TGLV.js";
2
+ //#region src/collab.ts
3
+ var r = (e, t) => {
4
+ if (typeof e != "string" || !e || e.length > 256) throw TypeError(`${t} site must be a non-empty string of at most 256 characters; pass a user or device id`);
5
+ return e;
6
+ }, i = class i {
7
+ #e;
8
+ #t;
9
+ #n;
10
+ #r = [""];
11
+ #i = /* @__PURE__ */ new Map([["", 0]]);
12
+ #a = 0;
13
+ #o = [];
14
+ #s = /* @__PURE__ */ new Map();
15
+ #c = /* @__PURE__ */ new Map();
16
+ #l = 0;
17
+ #u = /* @__PURE__ */ new Set();
18
+ constructor(i, a) {
19
+ t(a, "VoxelReplica"), this.site = r(a.site, "VoxelReplica");
20
+ let o = e(i, n(a));
21
+ this.size = [
22
+ i.size[0],
23
+ i.size[1],
24
+ i.size[2]
25
+ ], this.#e = i.voxels.slice(), this.#t = new Uint32Array(o), this.#n = new Uint16Array(o);
26
+ }
27
+ get grid() {
28
+ return {
29
+ size: [...this.size],
30
+ voxels: this.#e.slice()
31
+ };
32
+ }
33
+ get(e) {
34
+ return this.#e[e] ?? 0;
35
+ }
36
+ get version() {
37
+ return Object.fromEntries(this.#c);
38
+ }
39
+ onChange(e) {
40
+ if (typeof e != "function") throw TypeError("VoxelReplica.onChange needs a function; pass (op, changed) => {}");
41
+ return this.#u.add(e), () => this.#u.delete(e);
42
+ }
43
+ edit(e, t) {
44
+ if (typeof e?.length != "number") throw TypeError("VoxelReplica.edit cells must be cell indexes; pass an array");
45
+ let n = e.length, r = new Uint32Array(n), i = new Uint8Array(n), a = this.#e.length;
46
+ if (typeof t != "number" && (typeof t?.length != "number" || t.length !== n)) throw TypeError("VoxelReplica.edit values must be one number or one per cell; pass a value per cell");
47
+ for (let o = 0; o < n; o++) {
48
+ let n = e[o], s = typeof t == "number" ? t : t[o];
49
+ if (!Number.isInteger(n) || n < 0 || n >= a) throw RangeError(`VoxelReplica.edit cell ${n} is outside the grid; pass indexes 0 to ${a - 1}`);
50
+ if (!Number.isInteger(s) || s < 0 || s > 255) throw RangeError(`VoxelReplica.edit value ${s} is not a palette index; pass 0 to 255`);
51
+ r[o] = n, i[o] = s;
52
+ }
53
+ let o = {
54
+ site: this.site,
55
+ seq: this.#l + 1,
56
+ clock: this.#a + 1,
57
+ cells: r,
58
+ values: i
59
+ };
60
+ return this.apply(o), o;
61
+ }
62
+ apply(e) {
63
+ a(e, this.#e.length);
64
+ let t = this.#c.get(e.site) ?? 0, n = this.#s.get(e.site);
65
+ if (e.seq <= t || n?.has(e.seq)) return 0;
66
+ let r = this.#i.get(e.site);
67
+ if (r === void 0) {
68
+ if (this.#r.length > 65535) throw RangeError("VoxelReplica holds 65,535 sites; start a new shared grid");
69
+ r = this.#r.length, this.#r.push(e.site), this.#i.set(e.site, r);
70
+ }
71
+ if (e.seq === t + 1) {
72
+ let t = e.seq;
73
+ for (; n?.delete(t + 1);) t++;
74
+ this.#c.set(e.site, t);
75
+ } else n || this.#s.set(e.site, n = /* @__PURE__ */ new Set()), n.add(e.seq);
76
+ e.site === this.site && (this.#l = Math.max(this.#l, e.seq)), this.#o.push(e), this.#a = Math.max(this.#a, e.clock);
77
+ let i = this.#r, o = 0;
78
+ for (let t = 0; t < e.cells.length; t++) {
79
+ let n = e.cells[t], a = this.#t[n];
80
+ e.clock < a || e.clock === a && e.site < i[this.#n[n]] || (this.#t[n] = e.clock, this.#n[n] = r, this.#e[n] !== e.values[t] && (this.#e[n] = e.values[t], o++));
81
+ }
82
+ for (let t of [...this.#u]) t(e, o);
83
+ return o;
84
+ }
85
+ since(e = {}) {
86
+ return t(e, "VoxelReplica.since version"), this.#o.filter((t) => t.seq > (Object.hasOwn(e, t.site) ? e[t.site] : 0));
87
+ }
88
+ snapshot() {
89
+ return {
90
+ grid: this.#d(),
91
+ ops: [...this.#o]
92
+ };
93
+ }
94
+ static fromSnapshot(e, n) {
95
+ if (t(e, "VoxelReplica.fromSnapshot"), !Array.isArray(e.ops)) throw TypeError("VoxelReplica snapshot ops must be an array; pass replica.snapshot()");
96
+ let r = new i(e.grid, n);
97
+ for (let t of e.ops) r.apply(t);
98
+ return r;
99
+ }
100
+ #d() {
101
+ let e = this.#e.slice(), t = new Uint8Array(e.length);
102
+ for (let e of this.#o) for (let n of e.cells) t[n] = 1;
103
+ for (let n = 0; n < e.length; n++) t[n] && (e[n] = 0);
104
+ return {
105
+ size: [...this.size],
106
+ voxels: e
107
+ };
108
+ }
109
+ };
110
+ function a(e, n) {
111
+ if (t(e, "VoxelReplica operation"), r(e.site, "VoxelReplica operation"), !Number.isInteger(e.seq) || e.seq < 1 || e.seq > 4294967295) throw RangeError(`VoxelReplica operation seq ${e.seq} is not 1 to 4294967295; pass an operation from edit()`);
112
+ if (!Number.isInteger(e.clock) || e.clock < 1 || e.clock > 4294967295) throw RangeError(`VoxelReplica operation clock ${e.clock} is not 1 to 4294967295; pass an operation from edit()`);
113
+ if (!(e.cells instanceof Uint32Array) || !(e.values instanceof Uint8Array) || e.cells.length !== e.values.length) throw TypeError("VoxelReplica operation needs cells (Uint32Array) and values (Uint8Array) of one length; pass an operation from edit()");
114
+ for (let t = 0; t < e.cells.length; t++) if (e.cells[t] >= n) throw RangeError(`VoxelReplica operation cell ${e.cells[t]} is outside this grid; it comes from a grid of another size`);
115
+ }
116
+ var o = new TextEncoder(), s = new TextDecoder("utf-8", { fatal: !0 });
117
+ function c(e) {
118
+ a(e, Infinity);
119
+ let t = o.encode(e.site), n = e.cells.length, r = new Uint8Array(7 + t.length + 12 + n * 5), i = new DataView(r.buffer);
120
+ r.set([
121
+ 77,
122
+ 86,
123
+ 79,
124
+ 80,
125
+ 1
126
+ ]), i.setUint16(5, t.length, !0), r.set(t, 7);
127
+ let s = 7 + t.length;
128
+ i.setUint32(s, e.seq, !0), i.setUint32(s + 4, e.clock, !0), i.setUint32(s + 8, n, !0), s += 12;
129
+ for (let t = 0; t < n; t++) i.setUint32(s + t * 4, e.cells[t], !0);
130
+ return r.set(e.values, s + n * 4), r;
131
+ }
132
+ function l(e) {
133
+ if (!(e instanceof Uint8Array)) throw TypeError("decodeVoxelOp needs a Uint8Array; pass the bytes received");
134
+ let t = (e) => /* @__PURE__ */ RangeError(`decodeVoxelOp: ${e}; pass bytes from encodeVoxelOp`);
135
+ if (e.length < 19 || e[0] !== 77 || e[1] !== 86 || e[2] !== 79 || e[3] !== 80) throw t("not a voxel operation");
136
+ if (e[4] !== 1) throw t(`version ${e[4]} is not 1`);
137
+ let n = new DataView(e.buffer, e.byteOffset, e.byteLength), r = n.getUint16(5, !0);
138
+ if (e.length < 19 + r) throw t("cut short");
139
+ let i;
140
+ try {
141
+ i = s.decode(e.subarray(7, 7 + r));
142
+ } catch {
143
+ throw t("the site is not UTF-8");
144
+ }
145
+ let o = 7 + r, c = n.getUint32(o, !0), l = n.getUint32(o + 4, !0), u = n.getUint32(o + 8, !0);
146
+ if (o += 12, e.length !== o + u * 5) throw t("its length does not match its cell count");
147
+ let d = new Uint32Array(u);
148
+ for (let e = 0; e < u; e++) d[e] = n.getUint32(o + e * 4, !0);
149
+ let f = {
150
+ site: i,
151
+ seq: c,
152
+ clock: l,
153
+ cells: d,
154
+ values: e.slice(o + u * 4)
155
+ };
156
+ return a(f, Infinity), f;
157
+ }
158
+ //#endregion
159
+ export { i as VoxelReplica, l as decodeVoxelOp, c as encodeVoxelOp };
package/dist/edit.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ import type { MutableVec3, Vec3 } from '@margoengine/math';
2
+ import { type GridLimits, type VoxelGrid } from './grid.js';
3
+ import { SparseGrid } from './sparse.js';
4
+ export * from './raster.js';
5
+ export * from './stamp.js';
6
+ /** A dense grid or a sparse one; selections and picking take either. */
7
+ export type GridSource = VoxelGrid | SparseGrid;
8
+ /** The cells of a straight line from `a` to `b` (rounded to cells), both ends included; at most 4,097 cells. */
9
+ export declare function lineCells(a: Vec3, b: Vec3): MutableVec3[];
10
+ /** Options of {@link boxCells}. */
11
+ export interface BoxOptions {
12
+ /** Only the one-cell shell. Default false (solid). */
13
+ hollow?: boolean;
14
+ }
15
+ /** The cells of the box between corners `a` and `b` (either order, both included); at most 16,777,216 cells. */
16
+ export declare function boxCells(a: Vec3, b: Vec3, options?: BoxOptions): MutableVec3[];
17
+ /** The cells whose centres lie within `radius` (0 to 128) of the cell `center` (rounded to cells). */
18
+ export declare function sphereCells(center: Vec3, radius: number): MutableVec3[];
19
+ /**
20
+ * The face-connected cells holding the same palette index as `seed` (air included), as cell indexes
21
+ * ({@link cellAt} turns one back into x, y, z). An empty array when `seed` is outside the grid.
22
+ */
23
+ export declare function floodCells(source: GridSource, seed: Vec3, limits?: GridLimits): Float64Array;
24
+ /** The face-connected filled cells reachable from a filled `seed`, whatever their palette index, as cell indexes. */
25
+ export declare function connectedCells(source: GridSource, seed: Vec3, limits?: GridLimits): Float64Array;
26
+ /**
27
+ * The exposed face region around `seed`: filled cells in the seed's layer whose `normal` side is air (or the grid's
28
+ * edge), joined through edges within that layer, whatever their palette index. `normal` is a unit axis vector.
29
+ */
30
+ export declare function faceCells(source: GridSource, seed: Vec3, normal: Vec3, limits?: GridLimits): Float64Array;