@margoengine/voxel 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.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +1670 -2
- package/dist/bevel.d.ts +79 -0
- package/dist/bevel.js +453 -0
- package/dist/blocks-BabtpQT-.js +179 -0
- package/dist/blocks.d.ts +220 -0
- package/dist/border.d.ts +9 -0
- package/dist/chunk-BCoaKSn4.js +158 -0
- package/dist/chunk.d.ts +112 -0
- package/dist/codec-BmXhcsFt.js +412 -0
- package/dist/codec.d.ts +125 -0
- package/dist/codec.js +1 -0
- package/dist/debris.d.ts +114 -0
- package/dist/debris.js +387 -0
- package/dist/faces-DUR7LhrN.js +146 -0
- package/dist/faces.d.ts +7 -0
- package/dist/fluids.d.ts +74 -0
- package/dist/fluids.js +226 -0
- package/dist/generate.d.ts +78 -0
- package/dist/generate.js +99 -0
- package/dist/gi.d.ts +76 -0
- package/dist/gi.js +264 -0
- package/dist/gpu-mesher.d.ts +77 -0
- package/dist/gpu-mesher.js +461 -0
- package/dist/granular-mpm.d.ts +40 -0
- package/dist/granular-mpm.js +46 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +4 -0
- package/dist/light-rgb.d.ts +71 -0
- package/dist/light-rgb.js +287 -0
- package/dist/light-worker.d.ts +84 -0
- package/dist/light-worker.js +110 -0
- package/dist/light.d.ts +108 -0
- package/dist/light.js +332 -0
- package/dist/light.worker.d.ts +1 -0
- package/dist/lightmap.d.ts +50 -0
- package/dist/lightmap.js +68 -0
- package/dist/lod.d.ts +87 -0
- package/dist/lod.js +182 -0
- package/dist/mesher.d.ts +214 -0
- package/dist/mesher.js +539 -0
- package/dist/mesher.worker.d.ts +1 -0
- package/dist/model-data-D_rIKJCQ.js +41 -0
- package/dist/model-data.d.ts +21 -0
- package/dist/model-mesh-C4Gi6bMM.js +122 -0
- package/dist/model-mesh.d.ts +21 -0
- package/dist/model-surface.d.ts +5 -0
- package/dist/models.d.ts +74 -0
- package/dist/models.js +308 -0
- package/dist/objects.d.ts +73 -0
- package/dist/objects.js +152 -0
- package/dist/octants-C_Ic7gdn.js +10 -0
- package/dist/octants.d.ts +16 -0
- package/dist/origin-DsMelUxs.js +23 -0
- package/dist/origin.d.ts +7 -0
- package/dist/physics.d.ts +147 -0
- package/dist/physics.js +486 -0
- package/dist/query.d.ts +166 -0
- package/dist/query.js +305 -0
- package/dist/render-post.d.ts +6 -0
- package/dist/render.d.ts +296 -0
- package/dist/render.js +1616 -0
- package/dist/shared/borrowed.d.ts +44 -0
- package/dist/smooth-CEwHkXli.js +968 -0
- package/dist/smooth-clip.d.ts +24 -0
- package/dist/smooth-lod.d.ts +118 -0
- package/dist/smooth-lod.js +244 -0
- package/dist/smooth.d.ts +171 -0
- package/dist/smooth.js +1 -0
- package/dist/stream.d.ts +201 -0
- package/dist/stream.js +402 -0
- package/dist/terrain.worker.d.ts +1 -0
- package/dist/textures.d.ts +86 -0
- package/dist/ticks.d.ts +126 -0
- package/dist/ticks.js +239 -0
- package/dist/unit-light-Ch7roJgB.js +7 -0
- package/dist/vox.d.ts +237 -0
- package/dist/vox.js +780 -0
- package/dist/wind-data.d.ts +13 -0
- package/dist/wind.d.ts +68 -0
- package/dist/wind.js +170 -0
- package/dist/worker-DlGRxlc4.js +44 -0
- package/dist/worker-pool-sPyC6jCE.js +93 -0
- package/dist/workers/light.js +1 -0
- package/dist/workers/mesher.js +1 -0
- package/dist/workers/terrain.js +1 -0
- package/dist/world-CelTlft2.js +153 -0
- package/dist/world.d.ts +117 -0
- package/package.json +173 -4
package/README.md
CHANGED
|
@@ -1,3 +1,1671 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @margoengine/voxel
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Import `margoengine/voxel` from the `margoengine` package, or `@margoengine/voxel` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
|
|
4
|
+
|
|
5
|
+
Voxel worlds for block-building games and voxel editors: a block-type registry, 32 x 32 x 32 palette chunks with a
|
|
6
|
+
light byte per cell, and a chunked world with dirty tracking and change events.
|
|
7
|
+
Meshing, rendering, light, queries, streaming and `.vox` files are optional subpath entries
|
|
8
|
+
(design: [DESIGN.md](DESIGN.md)).
|
|
9
|
+
|
|
10
|
+
## Custom blocks, placed objects and wind
|
|
11
|
+
|
|
12
|
+
These are independent optional entries. `/models` defines a union of 1..64 boxes
|
|
13
|
+
inside [0,1]^3, with strictly positive extent, and precomputes 24 right-handed cube
|
|
14
|
+
orientations. `modelState(id,orientation)` defaults to identity 0; orientation is
|
|
15
|
+
0..23. Each box has six UV rectangles and texture layers in +x,-x,+y,-y,+z,-z order.
|
|
16
|
+
UV defaults are [0,0,1,1] and layers default to the block's textures; flipped UVs are
|
|
17
|
+
allowed. Exact box-union query/collision and covered-face lighting metadata follow
|
|
18
|
+
the orientation. These are cell-local boxes, not arbitrary triangle collision.
|
|
19
|
+
|
|
20
|
+
`VoxelModelRenderer.create(engine,world,options,signal)` lazily loads the optional
|
|
21
|
+
materials renderer. Install the matching `@margoengine/materials` peer from the
|
|
22
|
+
private build when using model drawing. Call update after lighting, before rendering.
|
|
23
|
+
It streams changed chunks without consuming the main renderer's light-dirty queue.
|
|
24
|
+
When a chunk's mesh fails to build (`update` throws), the meshes made for it are kept and the chunk stays pending,
|
|
25
|
+
so the next `update` replaces them.
|
|
26
|
+
The default material uses block colour/PBR factors; a per-type/texture override is
|
|
27
|
+
caller-owned. Disposal removes model meshes/subscriptions, preserving caller textures
|
|
28
|
+
and materials. Cancellation retains its exact reason.
|
|
29
|
+
|
|
30
|
+
`/objects` places a core mesh or glTF `{root,meshes}` graph around each cell centre.
|
|
31
|
+
`objectState(id,turns)` rotates 0..3 positive Y quarter turns, default 0. Definitions
|
|
32
|
+
snapshot transforms and share Geometry/material identity. A source can be moved,
|
|
33
|
+
hidden or disposed after definition; keep borrowed geometry/material resources alive
|
|
34
|
+
until placements are removed. Default solid:false and opacity:0 are storage/light
|
|
35
|
+
properties, not a generated triangle collider. Object geometry can extend beyond a
|
|
36
|
+
cell/chunk and uses core's existing per-mesh culling/instancing. `update()` reconciles
|
|
37
|
+
streamed chunks; unchanged cells keep handles. `at(x,y,z)` returns current core handles,
|
|
38
|
+
root first, or empty before update/unloaded. Disposal removes placements/subscriptions,
|
|
39
|
+
not source resources.
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
import { Engine, box, PbrMaterial } from '@margoengine/core';
|
|
43
|
+
import { BlockTypes, VoxelWorld } from '@margoengine/voxel';
|
|
44
|
+
import { BlockTextures, VoxelRenderer } from '@margoengine/voxel/render';
|
|
45
|
+
import { VoxelLighting } from '@margoengine/voxel/light';
|
|
46
|
+
import { defineBlockModel, modelState, VoxelModelRenderer } from '@margoengine/voxel/models';
|
|
47
|
+
import { VoxelObjects, objectState } from '@margoengine/voxel/objects';
|
|
48
|
+
import { defineWindBlock, VoxelWind } from '@margoengine/voxel/wind';
|
|
49
|
+
|
|
50
|
+
const engine = await Engine.create(document.querySelector<HTMLCanvasElement>('canvas')!);
|
|
51
|
+
const blocks = new BlockTypes();
|
|
52
|
+
const world = new VoxelWorld({ blocks });
|
|
53
|
+
const panel = defineBlockModel(blocks, 'panel', { color: '#dd714b', boxes: [
|
|
54
|
+
{ min: [0,0,0.4], max: [1,1,0.6] },
|
|
55
|
+
] });
|
|
56
|
+
const grass = defineWindBlock(blocks, 'grass', { shape: 'cross', layer: 'cutout', solid: false });
|
|
57
|
+
const textures = new BlockTextures({ images: [
|
|
58
|
+
{ width: 1, height: 1, data: new Uint8Array([90,180,70,255]) },
|
|
59
|
+
] });
|
|
60
|
+
const lighting = VoxelLighting.attach(world);
|
|
61
|
+
const renderer = VoxelRenderer.attach(engine, { world, textures, workers: 1 });
|
|
62
|
+
const wind = new VoxelWind(renderer, { direction: [1,0], time: 0 });
|
|
63
|
+
const models = await VoxelModelRenderer.create(engine, world);
|
|
64
|
+
const objects = VoxelObjects.attach(engine, world);
|
|
65
|
+
const geometry = box(0.5,0.5,0.5);
|
|
66
|
+
const source = engine.createMesh().setGeometry(geometry).setMaterial(new PbrMaterial({ color: '#49a6cf' }));
|
|
67
|
+
const item = objects.define('item', source);
|
|
68
|
+
source.dispose();
|
|
69
|
+
world.setBlock(0,0,0, modelState(panel,4));
|
|
70
|
+
world.setBlock(1,0,0, objectState(item,1));
|
|
71
|
+
world.setBlock(2,0,0, grass);
|
|
72
|
+
const off = engine.onFrame(() => { lighting.update(); models.update(); objects.update(); });
|
|
73
|
+
wind.time = undefined; // Return to the renderer clock after deterministic setup.
|
|
74
|
+
engine.start();
|
|
75
|
+
window.addEventListener('pagehide', () => {
|
|
76
|
+
off(); wind.dispose(); objects.dispose(); models.dispose(); renderer.dispose();
|
|
77
|
+
lighting.dispose(); textures.dispose(); engine.dispose();
|
|
78
|
+
}, { once: true });
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
`/wind` stores per-block motion prepared by `defineWindBlock`. Non-liquids default
|
|
82
|
+
to foliage (amplitude 0.12 blocks), liquids to liquid motion (0.04); speed defaults
|
|
83
|
+
to 1.6 rad/s, frequency 1.3 rad/block, rooted true for crosses and false otherwise.
|
|
84
|
+
Amplitude is 0..0.5; speed/frequency 0..100. Rooted foliage stays fixed at its cell
|
|
85
|
+
floor. Animated faces keep unit quads so shared liquid edges meet; liquid side/bottom
|
|
86
|
+
constraints differ from free foliage bending. This is display motion, not fluid or
|
|
87
|
+
collision simulation. Direction is XZ, default [1,0]; length below one scales motion,
|
|
88
|
+
zero stops it and longer vectors normalize. Explicit time is seconds within +/-1e6;
|
|
89
|
+
undefined restores the renderer clock. The clock stays float64 on the CPU and reaches
|
|
90
|
+
the shader as phases reduced to one turn, so foliage, water and animated textures move
|
|
91
|
+
as smoothly after days of play as at the start. `sampleVoxelWind` gives the deterministic CPU
|
|
92
|
+
offset used by tools/seam checks. Bounds padding covers maximum displacement, and
|
|
93
|
+
beauty, capture and shadow shaders share motion. The optional feature composes with
|
|
94
|
+
the mesher rather than adding work to static worlds. Dispose wind before its renderer;
|
|
95
|
+
renderer disposal also releases attached wind. Block metadata/fine tessellation remain.
|
|
96
|
+
|
|
97
|
+
## Attachment ownership and contributor checks
|
|
98
|
+
|
|
99
|
+
Disposable attachments support `dispose()` and `Symbol.dispose`; repeated disposal
|
|
100
|
+
is safe. VoxelLighting has one owner per world: dispose it before attaching another.
|
|
101
|
+
The renderer owns workers it creates and its GPU buffers, but not caller textures or
|
|
102
|
+
an injected mesher. Dispose caller-owned resources after their consumers. VoxelLod
|
|
103
|
+
also supports `using`; end its lifetime before releasing shared textures/render hosts.
|
|
104
|
+
These ownership rules do not dispose the world/block registry.
|
|
105
|
+
|
|
106
|
+
From the repository root, run `npm run test --workspace @margoengine/voxel` and
|
|
107
|
+
`npm run check:readme-run -- --packages=voxel`. The model browser proof waits for
|
|
108
|
+
pipeline readiness and submitted work before reading pixels; a frame count alone
|
|
109
|
+
does not establish readiness. The focused browser commands are
|
|
110
|
+
`node packages/voxel/tests/models-browser-check.mjs`,
|
|
111
|
+
`node packages/voxel/tests/objects-browser-check.mjs` and
|
|
112
|
+
`node packages/voxel/tests/wind-browser-check.mjs`.
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
import { BlockTypes, VoxelWorld, VoxelChunk, blockState, blockId, blockData } from 'margoengine/voxel';
|
|
116
|
+
|
|
117
|
+
const blocks = new BlockTypes(); // id 0 is 'air'
|
|
118
|
+
const stone = blocks.define('stone');
|
|
119
|
+
const grass = blocks.define('grass', { textures: [2, 2, 0, 1, 2, 2] }); // +x, -x, +y (top), -y, +z, -z layers
|
|
120
|
+
const glass = blocks.define('glass', { layer: 'translucent' });
|
|
121
|
+
const torch = blocks.define('torch', { shape: 'cross', layer: 'cutout', solid: false, light: 14 });
|
|
122
|
+
|
|
123
|
+
const world = new VoxelWorld({ blocks });
|
|
124
|
+
world.setBlock(0, 64, 0, grass); // adds the chunk if it is not loaded
|
|
125
|
+
world.setBlocks([1, 64, 0, stone, 2, 64, 0, glass]); // flat [x, y, z, state, ...]
|
|
126
|
+
world.getBlock(0, 64, 0); // grass; unloaded cells read as air (0)
|
|
127
|
+
|
|
128
|
+
const off = world.onChange((x, y, z, state, previous) => {}); // once per changed cell
|
|
129
|
+
for (const key of world.dirty) {
|
|
130
|
+
// 'cx,cy,cz' chunks to remesh: edits, border edits (neighbours too), added and removed chunks
|
|
131
|
+
world.dirty.delete(key);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const door = blockState(blocks.define('door'), 3); // id in the low 16 bits, data (e.g. facing) in the high 16
|
|
135
|
+
blockId(door);
|
|
136
|
+
blockData(door); // 3
|
|
137
|
+
|
|
138
|
+
// Chunks are plain storage. In a worker: fill one and post it packed.
|
|
139
|
+
const chunk = new VoxelChunk(stone); // uniform: stored as its palette alone
|
|
140
|
+
chunk.set(5, 31, 5, torch);
|
|
141
|
+
const packed = chunk.pack(); // {palette, bits, words, light}: typed arrays that own their buffers
|
|
142
|
+
postMessage(packed, { transfer: [packed.palette.buffer, packed.words.buffer] }); // add light.buffer when light is a Uint8Array
|
|
143
|
+
// On the main thread:
|
|
144
|
+
const worker = new Worker(new URL('./chunks.js', import.meta.url), { type: 'module' });
|
|
145
|
+
worker.onmessage = ({ data }) => world.addChunk(0, 1, 0, VoxelChunk.unpack(data));
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
- **Chunks.** Cell `x | z << 5 | y << 10` holds an index into a palette of distinct block states, 0, 1, 2, 4, 8 or 16
|
|
149
|
+
bits wide (an index never straddles a 32-bit word). Palette entries are reference counted: the width grows as
|
|
150
|
+
states appear and narrows again (with hysteresis) as they disappear; one state left makes the chunk uniform.
|
|
151
|
+
`chunk.fill(state)` makes it uniform at once. Light is `sky << 4 | block` per cell (`getLight`, `setLight`), one
|
|
152
|
+
byte for the whole chunk until a cell differs.
|
|
153
|
+
- **World.** Cells are 32-bit integer x and z and 16-bit y (`minY`/`maxY` narrow it; heightmaps are int16). Chunk
|
|
154
|
+
coordinates are cell >> 5. `addChunk` and `removeChunk` mark the chunk and its 26 loaded neighbours dirty; a dirty
|
|
155
|
+
key with no chunk was removed. `heightmap(cx, cz)` is the column's 32 x 32 Int16Array that `./light` fills. Edit
|
|
156
|
+
loaded chunks through the world (`chunk.set` on a loaded chunk bypasses dirty tracking and events).
|
|
157
|
+
- **Block types.** Options: `textures`, `layer` (`'opaque'`, `'cutout'`, `'translucent'`, `'invisible'`), `shape`
|
|
158
|
+
(`'cube'`, `'cross'`, `'liquid'`, `'slab'`, `'stair'`), `solid`, `liquid`, `light` and `opacity` (0-15), `color`,
|
|
159
|
+
`roughness`, `metalness`, `emissive`, `animation: {frames, fps}`, `maps: {normal, roughness, emissive}` (texture
|
|
160
|
+
layers), `transmission` and `scatter`. `blocks.table` is the resolved list, plain data for workers.
|
|
161
|
+
Ids follow definition order, so define types in the same order wherever saved states are read back.
|
|
162
|
+
- **Slabs and stairs.** Half-block shapes whose orientation is in the block state's data: `slabState(id, top)` (the
|
|
163
|
+
lower half, or the upper half when `top`), `doubleSlabState(id)` (both halves: one block of the slab's material,
|
|
164
|
+
shaped and lit like a cube) and `stairState(id, facing, upsideDown, corner?)` (a lower slab plus the upper quarter on
|
|
165
|
+
its back side, `facing` `'+x'`, `'-x'`, `'+z'` or `'-z'` naming that side; upside down puts the slab on top).
|
|
166
|
+
`connectStairs(world, x, y, z)` turns the stairs in that cell and beside it into the corners their neighbours call
|
|
167
|
+
for: outer when a stair's back meets the side of another stair of the same half (toward that stair's back), inner
|
|
168
|
+
when its front does, unless the cell on the far side of that turn holds a stair of the same facing and half (the
|
|
169
|
+
stair then continues that straight run); a `corner` given to `stairState` (`'straight'`, `'inner+z'`, `'outer-x'`, ...) is kept.
|
|
170
|
+
`waterlogState(state)` waterlogs a slab or stair: the liquid its type names (`waterlog`, a defined liquid's id or
|
|
171
|
+
name) fills the rest of the cell, meshed, lit and swum in like that liquid, while the block keeps colliding.
|
|
172
|
+
`shapeOctants(type, state)` gives the half cells a state fills as an 8-bit mask (bit `x + 2y + 4z`, 255 for a cube).
|
|
173
|
+
They mesh, shade, cast and receive shadows, pass light, collide and pick as those boxes (the sections below), and
|
|
174
|
+
their states go through the codecs unchanged. `opacity` defaults to 0: light is stopped by the faces they cover
|
|
175
|
+
whole, not by a cost.
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
import { BlockTypes, VoxelWorld, connectStairs, doubleSlabState, slabState, stairState, waterlogState } from 'margoengine/voxel';
|
|
179
|
+
const x = 0;
|
|
180
|
+
const y = 0;
|
|
181
|
+
const z = 0;
|
|
182
|
+
|
|
183
|
+
const blocks = new BlockTypes();
|
|
184
|
+
const world = new VoxelWorld({ blocks });
|
|
185
|
+
const stone = 0, planks = 1; // texture layers
|
|
186
|
+
const water = blocks.define('water', { shape: 'liquid', liquid: true, solid: false, layer: 'translucent' });
|
|
187
|
+
const slab = blocks.define('stone_slab', { shape: 'slab', textures: stone, waterlog: water });
|
|
188
|
+
const stairs = blocks.define('oak_stairs', { shape: 'stair', textures: planks, waterlog: 'water' });
|
|
189
|
+
world.setBlock(x, y, z, slabState(slab)); // lower half; slabState(slab, true) is the upper half
|
|
190
|
+
world.setBlock(x, y + 1, z, doubleSlabState(slab)); // both halves
|
|
191
|
+
world.setBlock(x + 1, y, z, stairState(stairs, '+x')); // climbs toward +x; stairState(stairs, '+x', true) hangs
|
|
192
|
+
connectStairs(world, x + 1, y, z); // corners from the neighbouring stairs
|
|
193
|
+
world.setBlock(x + 2, y, z, stairState(stairs, '+x', false, 'outer+z')); // a corner by hand, kept
|
|
194
|
+
world.setBlock(x, y - 1, z, waterlogState(slabState(slab))); // a slab under water
|
|
195
|
+
```
|
|
196
|
+
- **Errors.** `TypeError` for wrong types, `RangeError` for values out of range (cells, states, ids, options),
|
|
197
|
+
`MargoError` `'state'` for a duplicate block name or a chunk that is already loaded.
|
|
198
|
+
|
|
199
|
+
Measured with Node on one core of the development laptop (2026-10-19; `node --test
|
|
200
|
+
packages/voxel/tests/benchmark.test.js` prints yours): chunk get about 120 M/s and set about 27 M/s; world getBlock
|
|
201
|
+
about 7 M/s on random cells and 115 M/s along a column; pack + unpack of a 4-bit chunk 0.13 ms.
|
|
202
|
+
|
|
203
|
+
Apache-2.0. Optional, tree-shakable package; core peer ^1.0.0. Build and unit tests: `npm test --workspace @margoengine/voxel`
|
|
204
|
+
|
|
205
|
+
## Queries: `@margoengine/voxel/query`
|
|
206
|
+
|
|
207
|
+
Ray casts for picking (`engine.pick` does not see voxels), swept boxes for anything that moves through blocks, and a
|
|
208
|
+
player body.
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
import { BlockTypes, VoxelWorld } from 'margoengine/voxel';
|
|
212
|
+
import { raycastVoxels, sweepBox, VoxelCharacter } from 'margoengine/voxel/query';
|
|
213
|
+
import {Engine} from 'margoengine/core';
|
|
214
|
+
const vx = 0;
|
|
215
|
+
const dt = 1 / 60;
|
|
216
|
+
const vy = 0;
|
|
217
|
+
const vz = 0;
|
|
218
|
+
const forwardX = 0;
|
|
219
|
+
const forwardZ = 1;
|
|
220
|
+
const sprint = false;
|
|
221
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
222
|
+
|
|
223
|
+
const blocks = new BlockTypes();
|
|
224
|
+
const stone = blocks.define('stone');
|
|
225
|
+
const world = new VoxelWorld({ blocks });
|
|
226
|
+
const eye: [number, number, number] = [0.5, 81.6, 0.5], forward: [number, number, number] = [0, 0, -1];
|
|
227
|
+
const hit = raycastVoxels(world, eye, forward, 8); // {cell, normal, adjacent, point, distance, state} or null
|
|
228
|
+
if (hit) world.setBlock(...hit.adjacent, stone); // place against the face; setBlock(...hit.cell, 0) breaks it
|
|
229
|
+
raycastVoxels(world, eye, forward, 8, (state, type) => type.liquid); // pick water instead
|
|
230
|
+
|
|
231
|
+
// An item or a mob: never tunnels, whatever the speed.
|
|
232
|
+
const box = { min: { x: 0, y: 80, z: 0 }, max: { x: 1, y: 81, z: 1 } };
|
|
233
|
+
const { position, hit: axes, onGround } = sweepBox(world, box, [vx * dt, vy * dt, vz * dt]); // box: {min, max}, a Box3
|
|
234
|
+
|
|
235
|
+
const player = new VoxelCharacter(world, { stepHeight: 0.6, speeds: { walk: 4.317 } });
|
|
236
|
+
player.position = [0.5, 80, 0.5]; // feet; assign again to teleport
|
|
237
|
+
player.flying = false;
|
|
238
|
+
const jump = false, descend = false;
|
|
239
|
+
engine.onFrame((_, dt) => {
|
|
240
|
+
player.update(dt, { direction: [forwardX, 0, forwardZ], jump, descend, sprint });
|
|
241
|
+
const [x, y, z] = player.renderPosition; // interpolated between fixed steps: smooth at any refresh rate
|
|
242
|
+
engine.camera.position = [x, y + 1.62, z];
|
|
243
|
+
});
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
- **Ray casts.** Cell by cell (Amanatides and Woo, 1987); a cell is the half-open box `[x, x + 1)` on each axis. A ray
|
|
247
|
+
through an exact edge or corner skips the cells it only touches; a ray in a face plane runs in the cells on the
|
|
248
|
+
plane's positive side; a ray that starts inside a block hits it at distance 0 with normal `[0, 0, 0]`. `point` lies
|
|
249
|
+
exactly on the face (that coordinate is an integer). By default every drawn block except liquids is hit, solid or
|
|
250
|
+
not, and a cross block (flower, torch) is hit as its whole cell; the optional `filter(state, type)` changes that. A
|
|
251
|
+
slab or stair is hit where the ray meets its half-block boxes (the walk continues through its open part): `normal`
|
|
252
|
+
is that box face's, `point` lies on it (a multiple of 0.5 there, such as a slab's top at `y + 0.5`).
|
|
253
|
+
- **Sweeps.** `sweepBox` moves along y, then x, then z, each axis stopped by the first solid block (`solid: true`,
|
|
254
|
+
as its whole cell, or a slab's or stair's half-block boxes) after scanning every cell layer the move crosses. Touching, or overlapping by up to 1e-6 blocks,
|
|
255
|
+
is not a collision, and a box can leave a block placed inside it. `position` is the box's new min corner; `onGround`
|
|
256
|
+
is true when the downward move was stopped, or with motion y 0, when the box rests on a block.
|
|
257
|
+
- **Player body.** `update(dt, intent)` runs fixed 1/120 s steps (the remainder carries over, at most 0.25 s per
|
|
258
|
+
call), so the path is the same at 30, 60 or 144 Hz; `renderPosition` interpolates between the last two steps.
|
|
259
|
+
Walking accelerates and brakes in about 0.15 s on the ground (weakly in the air), falls at `gravity` (default 32
|
|
260
|
+
blocks/s², capped at 78.4 blocks/s) and jumps at `speeds.jump` (9: 1.27 blocks high). It steps onto ledges up to
|
|
261
|
+
`stepHeight` (0.6) only from the ground, when landing or in liquid, and only when the raised body fits under the
|
|
262
|
+
ceiling. Full blocks make ground ledges whole blocks; slabs and stairs make half-block ones, so the default 0.6
|
|
263
|
+
walks up stairs and onto slabs without jumping. In a liquid block it swims: slower (`speeds.swim`, 2), buoyant (a fifth of
|
|
264
|
+
gravity), `jump` swims up, and jumping against a wall climbs out onto the bank. `flying` turns gravity off; `jump`
|
|
265
|
+
and `descend` rise and sink at `speeds.fly` (11). Defaults: size `[0.6, 1.8, 0.6]`, walk 4.317, sprint 5.612.
|
|
266
|
+
|
|
267
|
+
Measured with Node on one core of the development laptop (2026-10-19; `node --test packages/voxel/tests/query.test.js`
|
|
268
|
+
prints yours): about 200 rays/ms for 64-block rays over terrain, 600 sweeps/ms for a player box moving one block, and
|
|
269
|
+
700 character updates/ms at 60 Hz (two fixed steps each).
|
|
270
|
+
|
|
271
|
+
## Codecs (`./codec`)
|
|
272
|
+
|
|
273
|
+
## Codecs and chunk stores (`./codec`, `./stream`)
|
|
274
|
+
|
|
275
|
+
Bytes for saves and the network, and where unloaded chunks go. Decoders treat their input as hostile: every count
|
|
276
|
+
and length is checked against the bytes before it is read or allocated, a deflated chunk stops inflating at the
|
|
277
|
+
largest possible chunk (262,148 bytes), and anything malformed throws a `RangeError` naming the problem.
|
|
278
|
+
|
|
279
|
+
```ts
|
|
280
|
+
import { encodeChunk, decodeChunk, encodeBlockChanges, applyBlockChanges, EntityCodec } from 'margoengine/voxel/codec';
|
|
281
|
+
import { IndexedDBChunkStore, MemoryChunkStore } from 'margoengine/voxel/stream';
|
|
282
|
+
import { BlockTypes, VoxelChunk, VoxelWorld } from 'margoengine/voxel';
|
|
283
|
+
const cx = 0;
|
|
284
|
+
const cy = 0;
|
|
285
|
+
const cz = 0;
|
|
286
|
+
|
|
287
|
+
const blocks = new BlockTypes();
|
|
288
|
+
const world = new VoxelWorld({ blocks }), otherWorld = new VoxelWorld({ blocks });
|
|
289
|
+
const chunk = new VoxelChunk(blocks.define('stone'));
|
|
290
|
+
const outgoing: Uint8Array[] = [];
|
|
291
|
+
const send = (message: Uint8Array) => { outgoing.push(message); }; // An inspectable local transport.
|
|
292
|
+
const bytes = await encodeChunk(chunk); // deflate-raw by default; {light: false}, {compress: false}
|
|
293
|
+
world.addChunk(cx, cy, cz, await decodeChunk(bytes));
|
|
294
|
+
|
|
295
|
+
const edits: number[] = [];
|
|
296
|
+
world.onChange((x, y, z, state) => edits.push(x, y, z, state));
|
|
297
|
+
const changes = encodeBlockChanges(edits); // sorted, last state per cell, typically 2-4 bytes per change
|
|
298
|
+
send(changes);
|
|
299
|
+
applyBlockChanges(otherWorld, changes); // all or nothing, through setBlocks (dirty marking, change events)
|
|
300
|
+
|
|
301
|
+
const codec = new EntityCodec({ position: 'position', rotation: 'rotation', health: 'u8', anim: 'u16' });
|
|
302
|
+
const hero = { position: [0, 64, 0] as [number, number, number], rotation: [0, 0, 0, 1] as [number, number, number, number], health: 20, anim: 0 };
|
|
303
|
+
const players = new Map([[1, hero]]);
|
|
304
|
+
const acked = new Map(), received = new Map();
|
|
305
|
+
const message = codec.encode(players, acked); // Maps of u32 id -> entity; only what changed since `acked`
|
|
306
|
+
send(message);
|
|
307
|
+
const state = codec.decode(message, received); // `received`: the receiver's copy of `acked`
|
|
308
|
+
// A server sending one tick to many receivers quantizes each entity once; encode writes the same bytes from it.
|
|
309
|
+
const ready = new Map([...players].map(([id, p]) => [id, codec.prepare(p, id)]));
|
|
310
|
+
const clients = [{ send, lastSent: new Map() }];
|
|
311
|
+
for (const client of clients) client.send(codec.encode(ready, client.lastSent));
|
|
312
|
+
|
|
313
|
+
const store = new IndexedDBChunkStore('world-1'); // or new MemoryChunkStore()
|
|
314
|
+
store.put(cx, cy, cz, chunk); // copies the chunk now; puts in one task share one transaction
|
|
315
|
+
const saved = await store.get(cx, cy, cz); // a VoxelChunk or undefined; sees uncommitted puts
|
|
316
|
+
await store.flush(); // e.g. on visibilitychange: everything committed, or the first failure
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
The example collects transport bytes locally. In a networked application, pass them
|
|
320
|
+
to a connected transport only after its open/ready promise resolves; the codec does
|
|
321
|
+
not create or manage a WebSocket connection.
|
|
322
|
+
|
|
323
|
+
- **Chunks.** u8 version (1), u8 flags (1 light, 2 dense light, 4 deflated), then (deflate-raw when flagged) a
|
|
324
|
+
varint palette length and states, u8 index bits and the `PackedChunk` words as little-endian u32, and the light:
|
|
325
|
+
one byte when every cell shares it, else 32,768. `encodeChunk` reads the chunk before it returns.
|
|
326
|
+
- **Block changes.** A flat `[x, y, z, state, ...]` list in and out (`decodeBlockChanges` returns an Int32Array that
|
|
327
|
+
`setBlocks` takes). Varint count, then per change sorted by chunk and cell index: a varint step (odd: new chunk,
|
|
328
|
+
then three zigzag varint chunk offsets; even: the cell index offset) and a varint state.
|
|
329
|
+
- **Entities.** Fields `'position'` (1/512 block, error <= 1/1024, |coordinate| < 2,097,152), `'rotation'`
|
|
330
|
+
(smallest-three in 32 bits: at most 0.28 degrees, about 0.08 on average), `'u8'`, `'u16'`, `'f32'`; up to 32 per
|
|
331
|
+
schema, in the schema's key order. Per entity in id order: varint id offset, varint field mask (0 = removed),
|
|
332
|
+
changed fields. Decoding against a baseline the bytes were not encoded from throws when an entity is missing.
|
|
333
|
+
- **Stores.** `ChunkStore` is `get`, `put`, `delete`, `flush` (promises; invalid arguments to put and delete throw
|
|
334
|
+
at the call). `IndexedDBChunkStore(name)` keeps one
|
|
335
|
+
deflated record per chunk keyed `[cx, cy, cz]` in object store `'chunks'`, writes each task's puts and deletes in
|
|
336
|
+
one transaction after the previous one, and reports a failed commit (MargoError `'failed'`) through those puts and
|
|
337
|
+
the next `flush`. `MemoryChunkStore` keeps uncompressed records in memory (tests, servers).
|
|
338
|
+
|
|
339
|
+
Measured with Node 24 on the development laptop (2026-10-19; `node --test packages/voxel/tests/codec-benchmark.test.js`
|
|
340
|
+
prints yours): a surface chunk (4-bit, 7 states, dense sky light) is 49,163 bytes raw and 2,586 deflated (16,395 and
|
|
341
|
+
1,876 without light); raw encode about 100 MB/s and decode about 140 MB/s; deflated encode and decode 1-4 ms each,
|
|
342
|
+
most of it Node's stream overhead (32 decodes in flight: about 0.7 ms each). 20,000 block changes in 8 chunks: 1.9
|
|
343
|
+
bytes each. 1,000 entities: 17,940 bytes in full, 1,796 when 30% moved.
|
|
344
|
+
|
|
345
|
+
## Meshing: `@margoengine/voxel/mesher`
|
|
346
|
+
|
|
347
|
+
`meshChunk` turns one chunk and the one-cell shell of its neighbours into greedy quads, 12 bytes each, for a renderer
|
|
348
|
+
that pulls vertices from a storage buffer. It is pure and synchronous (phase 3 runs it in workers).
|
|
349
|
+
|
|
350
|
+
```ts
|
|
351
|
+
import { BlockTypes, VoxelWorld } from 'margoengine/voxel';
|
|
352
|
+
import { meshChunk, meshInput, decodeQuad, blockMaterials, QUAD_WORDS } from 'margoengine/voxel/mesher';
|
|
353
|
+
|
|
354
|
+
const blocks = new BlockTypes();
|
|
355
|
+
const world = new VoxelWorld({ blocks });
|
|
356
|
+
world.setBlock(0, 64, 0, blocks.define('stone'));
|
|
357
|
+
for (const key of world.dirty) {
|
|
358
|
+
const input = meshInput(world, key); // {chunk: packed, shell, light, blocks}; undefined for a removed chunk
|
|
359
|
+
world.dirty.delete(key);
|
|
360
|
+
if (!input) continue; // drop that chunk's mesh
|
|
361
|
+
const mesh = meshChunk(input); // {opaque, cutout, translucent: Uint32Array, visibility}
|
|
362
|
+
for (let i = 0; i < mesh.opaque.length / QUAD_WORDS; i++) decodeQuad(mesh.opaque, i); // {x, y, z, face, w, h, ...}
|
|
363
|
+
}
|
|
364
|
+
const materials = blockMaterials(blocks.table); // material id per block id * 6 + face
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
- **Faces.** An opaque cube hides every face against it; faces between blocks of the same id (glass and glass, water
|
|
368
|
+
and water, leaves and leaves) are hidden; every other face stays, so stone behind glass keeps its face and the glass
|
|
369
|
+
face against the stone goes. Invisible blocks emit nothing. Slabs and stairs, and cube faces with one within a cell,
|
|
370
|
+
are meshed at half-block resolution: a quarter of a face shows when its block fills the half cell behind it and the
|
|
371
|
+
half cell in front is neither an opaque block's nor the same block's, so a cube beside a slab keeps only its upper
|
|
372
|
+
half face, a slab under a cube hides the cube's bottom only as a top slab, and two slabs side by side hide the faces
|
|
373
|
+
between them. Visible quarters become at most two rectangles per face plane, on the cell's side or (for a slab's top,
|
|
374
|
+
a stair's step and riser) half a block inside it, and merge greedily along every axis they are not trimmed on. A
|
|
375
|
+
waterlogged slab or stair also holds its liquid in its open octants, meshed by the liquid rules per half block (no
|
|
376
|
+
faces against the same liquid beside it, its surface waving with the pool's, sides of lowered water beside a slab cut
|
|
377
|
+
at the water line). A chunk without slabs or stairs meshes to the same bytes as before. `cross` blocks emit two diagonal quads (faces 6 and 7),
|
|
378
|
+
unshaded and lit by their own cell. A `liquid` cell without the same liquid above is a surface: its top and sides
|
|
379
|
+
drop by its state data's low 3 bits in eighths of a block (`blockState(water, level)`) and carry the wave bit; a
|
|
380
|
+
lowered top under a solid block stays, and a side above a lower surface of the same liquid stays.
|
|
381
|
+
- **Shading.** Each vertex gets ambient occlusion from the opaque cubes beside it in the face's front layer (0 when both
|
|
382
|
+
edge cells are opaque, else 3 minus the count of edge and diagonal cells; 0fps.net's rule) and smooth light, the
|
|
383
|
+
rounded mean of the open cells around it. The AO picks the triangle diagonal (the brighter pair). Faces merge only when
|
|
384
|
+
their words are equal and their corners equal along the merge axis, so a merged quad shades exactly like the unit
|
|
385
|
+
faces it covers; the tests check this against a one-quad-per-face oracle. On half-block faces the AO and light come
|
|
386
|
+
from the four half cells of the front layer around each corner (a stair's step darkens where it meets its riser),
|
|
387
|
+
and the tests check every face against a half-block oracle.
|
|
388
|
+
- **Quad words** (low bits first). Word 0: x 0-4, y 5-9, z 10-14 (the local cell), face 15-17 (+x, -x, +y, -y, +z, -z,
|
|
389
|
+
then the two cross diagonals), w - 1 at 18-22, h - 1 at 23-27, flip 28, liquidDrop 29-31. Word 1: material 0-11, AO
|
|
390
|
+
per corner at 12-19 (2 bits each), wave 20, inset 21 (the face lies half a block inside its cell), trim 22-25 (bits
|
|
391
|
+
1, 2, 4, 8: the quad starts half a block later along u, ends half a block earlier along u, the same along v). Word
|
|
392
|
+
2: per corner c, sky light at bits 8c-8c+3 and block light at 8c+4-8c+7. The u and v axes are z, y on x faces, x, z on y faces and x, y on z faces; corners run (0, 0), (w, 0),
|
|
393
|
+
(w, h), (0, h). `ChunkMesh` documents the geometry in full.
|
|
394
|
+
- **Materials.** `blockMaterials(table)` numbers each distinct texture layer of each block in id order (up to 4,096), so
|
|
395
|
+
a renderer builds its material table (layer, tint, roughness, metalness, emissive, animation) from the same walk.
|
|
396
|
+
- **Visibility.** `mesh.visibility` has bit `a * 6 + b` set when chunk faces a < b see each other through cells that are
|
|
397
|
+
not opaque cubes, for cave culling.
|
|
398
|
+
- **Shell.** `MeshInput.shell` and `.light` hold the 6,536 cells of the 34-cubed block around the chunk outside it, in
|
|
399
|
+
index order `(x + 1) + 34 (z + 1) + 1156 (y + 1)` for local x, y, z in -1..32; `meshInput` reads them from the
|
|
400
|
+
loaded neighbours (unloaded cells are air with light 0).
|
|
401
|
+
|
|
402
|
+
Measured with Node on one core of the development laptop while other jobs ran (2026-10-19; `node --test
|
|
403
|
+
packages/voxel/tests/mesher-benchmark.test.js` prints yours): about 2 ms per random-terrain chunk (5,900 quads) and
|
|
404
|
+
7.5 ms for a full-chunk stone checkerboard (98,304 quads, the most opaque cubes can make); `meshInput` 0.2 ms. A 3D
|
|
405
|
+
checkerboard of two different blocks that hide nothing (two glasses, say) shows every face of every cell: 196,608 quads
|
|
406
|
+
in one layer.
|
|
407
|
+
|
|
408
|
+
## Light (`@margoengine/voxel/light`)
|
|
409
|
+
|
|
410
|
+
Sky and block light in the chunks' light bytes, by breadth-first flood fill on the main thread with a per-call budget.
|
|
411
|
+
|
|
412
|
+
```ts
|
|
413
|
+
import { VoxelLighting, MAX_LIGHT } from 'margoengine/voxel/light';
|
|
414
|
+
import {Engine} from 'margoengine/core';
|
|
415
|
+
import {BlockTypes, VoxelWorld} from 'margoengine/voxel';
|
|
416
|
+
const blocks = new BlockTypes();
|
|
417
|
+
blocks.define('stone');
|
|
418
|
+
const world = new VoxelWorld({ blocks });
|
|
419
|
+
const x = 0;
|
|
420
|
+
const y = 0;
|
|
421
|
+
const z = 0;
|
|
422
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
423
|
+
|
|
424
|
+
const lighting = VoxelLighting.attach(world, { budget: 4096 }); // also lights the chunks already loaded
|
|
425
|
+
engine.onFrame(() => lighting.update()); // at most `budget` cells a call, so big changes spread over frames
|
|
426
|
+
lighting.skyLight(x, y, z); // 0..MAX_LIGHT (15)
|
|
427
|
+
lighting.blockLight(x, y, z);
|
|
428
|
+
lighting.budget = Infinity; // e.g. behind a loading screen
|
|
429
|
+
lighting.dispose();
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
- **Sky light** is 15 in every cell above its column's heightmap (`world.heightmap`: the highest cell with opacity > 0,
|
|
433
|
+
so glass passes it at full strength) and spreads from there; **block light** spreads from each type's `light`. Each
|
|
434
|
+
step costs 1 plus the entered cell's `opacity` (stone's 15 stops it; leaves with `opacity: 1` dim it by 2 a block).
|
|
435
|
+
- **Slabs and stairs** pass light through their open part: no light crosses a face their boxes cover whole (a lower
|
|
436
|
+
slab's bottom, an upper slab's top, a stair's back and the half it stands on, every face of a double slab), any
|
|
437
|
+
other face passes it at the usual cost (a waterlogged one costs its liquid's opacity when that is more). They end their column's open sky; one whose top is open (a lower slab, a stair) is itself lit as open
|
|
438
|
+
sky when it tops its column, so its top face shades like the ground beside it.
|
|
439
|
+
- Edits and chunk loads and removals (`world.onChunk`) are queued as they happen; `update()` applies them in order,
|
|
440
|
+
across chunk borders: a chunk loaded later takes light in from its loaded neighbours and gives its own out. Darkening
|
|
441
|
+
uses the two-queue removal flood, so removing a torch, closing a roof or unloading a chunk clears only what that
|
|
442
|
+
light reached. A removed chunk's heights stay in the heightmap, so a cave stays dark when the chunks above it unload;
|
|
443
|
+
a chunk loaded again decides the heights of its own 32 cells per column.
|
|
444
|
+
- Chunks whose light changed, and loaded neighbours whose one-cell shell holds a changed cell, go into `world.dirty`.
|
|
445
|
+
A chunk entirely under open sky keeps one light byte (`chunk.fillLight`); its first differing cell makes it 32 KiB.
|
|
446
|
+
- A chunk load is never split; it counts the cells it lights plus an eighth of those it scans (about 130 for open sky,
|
|
447
|
+
up to about 13,000 for mixed blocks with emitters). `update()` returns the cells processed: 0 once light is current.
|
|
448
|
+
- Errors: `TypeError`/`RangeError` for a wrong world, budget or cell; `MargoError` `'attached'` for a second lighting
|
|
449
|
+
on one world, `'disposed'` for `update()` after `dispose()`.
|
|
450
|
+
|
|
451
|
+
Measured with Node on the development laptop (2026-10-19; `node --test packages/voxel/tests/light-benchmark.test.js`
|
|
452
|
+
prints yours): a torch placed or removed in open air (3,300 cells) about 4,000-6,000 cells/ms; a 32 x 32 stone roof
|
|
453
|
+
removed over a 30-deep room (70,000 cells) about 5,400-7,600 cells/ms, put back about 6,800-8,500 cells/ms.
|
|
454
|
+
|
|
455
|
+
## MagicaVoxel `.vox` files (`@margoengine/voxel/vox`)
|
|
456
|
+
|
|
457
|
+
```ts
|
|
458
|
+
import { BlockTypes, VoxelWorld } from 'margoengine/voxel';
|
|
459
|
+
import { parseVox, writeVox, pasteVoxModel, readVoxRenderDictionaries } from 'margoengine/voxel/vox';
|
|
460
|
+
|
|
461
|
+
const blocks = new BlockTypes();
|
|
462
|
+
const stone = blocks.define('stone');
|
|
463
|
+
const world = new VoxelWorld({ blocks });
|
|
464
|
+
// Build a complete two-voxel sample; replace these bytes with a fetched .vox file in an importer.
|
|
465
|
+
const palette = new Uint8Array(256 * 4);
|
|
466
|
+
palette.set([220,100,40,255], 4);
|
|
467
|
+
const scene = parseVox(writeVox({ version: 150,
|
|
468
|
+
models: [{ size: [2,1,1], voxels: new Uint8Array([0,0,0,1, 1,0,0,1]) }],
|
|
469
|
+
palette, materials: [{ id: 1, rough: 0.5 }], nodes: [], layers: [],
|
|
470
|
+
}));
|
|
471
|
+
scene.models[0].size; // [x, y, z], MagicaVoxel z up; voxels: Uint8Array of x, y, z, palette index
|
|
472
|
+
scene.palette; // 256 RGBA8 colours, palette index i at 4 * i
|
|
473
|
+
scene.nodes; // transform / group / shape nodes; transform frames have rotation (3 x 3), translation, frame
|
|
474
|
+
scene.materials[0].rough; // MATL: type, weight, rough, spec, ior, att, flux, plastic (+ attributes Map)
|
|
475
|
+
|
|
476
|
+
pasteVoxModel(world, scene, [0, 64, 0]); // every visible shape; colours become 'vox:rrggbb' block types
|
|
477
|
+
const mapping = new Array<number>(256).fill(stone);
|
|
478
|
+
pasteVoxModel(world, scene.models[0], [10, 64, 0], mapping); // one model: mapping[paletteIndex] = block state
|
|
479
|
+
|
|
480
|
+
for (const node of scene.nodes) {
|
|
481
|
+
if (node.type === 'transform') node.frames[0].translation = [0, 0, 8];
|
|
482
|
+
}
|
|
483
|
+
const bytes = writeVox(scene); // the same bytes as the file, except what you changed
|
|
484
|
+
|
|
485
|
+
const render = readVoxRenderDictionaries(scene); // rOBJ / rCAM decoded; scene.chunks untouched
|
|
486
|
+
render.objects; // Map per rOBJ: '_type' => '_setting', '_sun', '_lens', ...
|
|
487
|
+
render.cameras; // { id, attributes } per rCAM
|
|
488
|
+
render.diagnostics; // { kind: 'malformed' | 'unsupported', id, chunk, message } for what gave no dictionary
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
- **Format.** Versions 150 and 200, from MagicaVoxel's published notes: SIZE + XYZI models, PACK, RGBA (file colour k
|
|
492
|
+
is palette index k + 1; the default palette when absent), MATL, nTRN (the packed rotation byte as a signed
|
|
493
|
+
permutation matrix, `_t`, `_f` per frame), nGRP, nSHP (a model per frame) and LAYR. Every other chunk (rOBJ, rCAM,
|
|
494
|
+
NOTE, IMAP, META, MATT, future ones) stays as bytes in `scene.chunks`, which also records the file's chunk order, so
|
|
495
|
+
`writeVox(parseVox(file))` is the file byte for byte. Typed fields are decoded from each dictionary's `attributes`;
|
|
496
|
+
on write a typed field replaces its key only when its value changed, so untouched text keeps its exact form.
|
|
497
|
+
Dictionary text is UTF-8; text that is not (names saved in a Windows code page) reads as windows-1252 and is written
|
|
498
|
+
back in windows-1252 while unchanged, so such files also round-trip byte for byte; a value set since goes out as
|
|
499
|
+
UTF-8.
|
|
500
|
+
- **Render settings.** `readVoxRenderDictionaries(scene, {maxBytes, maxEntries})` decodes the kept rOBJ chunks (a
|
|
501
|
+
DICT each) and rCAM chunks (an int32 camera id, then a DICT) without changing them, so `writeVox` still gives the
|
|
502
|
+
file back byte for byte. Strings decode like the typed dictionaries (UTF-8, else windows-1252) and a repeated key is
|
|
503
|
+
malformed, as in `parseVox`. A chunk over `maxBytes` (default 1 MiB) or a dictionary over `maxEntries` (default
|
|
504
|
+
4096) is reported `'unsupported'` and not read; truncated or inconsistent content is `'malformed'`; child chunks are
|
|
505
|
+
kept, reported and not read. Nothing throws for chunk content. The result feeds the path tracer's
|
|
506
|
+
`magicaVoxelLighting(objects)` and `magicaVoxelCamera(camera.attributes, objects)`.
|
|
507
|
+
- **Pasting.** MagicaVoxel's z (up) becomes world y and its y becomes world -z (right-handed, not mirrored); the pasted
|
|
508
|
+
box has its minimum corner at `at`. A scene pastes frame 0 of every shape not hidden by its node or layer, each
|
|
509
|
+
model centred on its transform's translation. A bare model has no palette, so it needs a mapping. Without one, a
|
|
510
|
+
colour whose MATL is metal, glass, blend, emit or media gets `voxBlockOptions(material)`: metalness, a translucent
|
|
511
|
+
layer with transmission (`_trans`, `_alpha`, or a glass's `_weight`), `emissive = _weight * (1 + _flux)` (a starting
|
|
512
|
+
point: MagicaVoxel's power steps are not linear), scatter for media; its options go in the type name
|
|
513
|
+
(`vox:rrggbb:metalness=0.5`). Plain diffuse colours stay `vox:rrggbb`. Voxels are
|
|
514
|
+
written chunk by chunk (a stable sort keeps each chunk's voxels in file order, and each chunk's palette widens once),
|
|
515
|
+
with the results of one `setBlock` per voxel: the same cells, return count and dirty keys, and `onChange` once per
|
|
516
|
+
changed cell right after it is written. Only the order across chunks differs.
|
|
517
|
+
- **Errors.** `parseVox` throws `RangeError` for truncated, oversized or inconsistent files (voxels outside SIZE, a
|
|
518
|
+
SIZE outside 1-256, counts past the chunk, broken node references or cycles) and `TypeError` for bytes that are
|
|
519
|
+
not a .vox file; it allocates no more than the file holds. `writeVox` rejects what `parseVox` would.
|
|
520
|
+
|
|
521
|
+
Measured with Node on the development laptop (2026-10-19; `node --test packages/voxel/tests/vox.test.js` prints
|
|
522
|
+
yours): a 1M-voxel model writes in about 10 ms and parses in about 6 ms (4 MiB). Pasting, measured with Node 26 on
|
|
523
|
+
the RTX A6000 desktop (32 logical cores) while other jobs kept it at 36-72% CPU (2026-10-19, best of 3): 1M random
|
|
524
|
+
cells in a 256-cubed box 43-57 ms (one `setBlock` per voxel, as pasting did before: 261-282 ms), and a 398-voxel model
|
|
525
|
+
tiled 2,635 times (1,048,730 voxels; measured with the former sample model, which the Margo-made `tests/fixtures/tree.vox`
|
|
526
|
+
replaced at the same voxel count) 45-52 ms (113-142 ms).
|
|
527
|
+
|
|
528
|
+
## Physics (`@margoengine/voxel/physics`)
|
|
529
|
+
|
|
530
|
+
Colliders for the chunks near moving bodies, so mobs, item drops, debris and balls of a
|
|
531
|
+
[`@margoengine/physics`](../physics/README.md) world collide with the blocks. Needs `@margoengine/physics` (an optional
|
|
532
|
+
peer: only this entry uses it) and a solver with the `voxels` shape, which `physics.supportsShape('voxels')` tells.
|
|
533
|
+
|
|
534
|
+
```ts
|
|
535
|
+
import { sphereGeometry } from 'margoengine/geometry';
|
|
536
|
+
import { PbrMaterial, createMesh } from 'margoengine/materials';
|
|
537
|
+
import { Physics } from 'margoengine/physics';
|
|
538
|
+
import { VoxelPhysics } from 'margoengine/voxel/physics';
|
|
539
|
+
import {Engine} from 'margoengine/core';
|
|
540
|
+
import {BlockTypes, VoxelWorld} from 'margoengine/voxel';
|
|
541
|
+
import {box} from 'margoengine/core';
|
|
542
|
+
const blocks = new BlockTypes();
|
|
543
|
+
blocks.define('stone');
|
|
544
|
+
const world = new VoxelWorld({ blocks });
|
|
545
|
+
const x = 0;
|
|
546
|
+
const y = 0;
|
|
547
|
+
const z = 0;
|
|
548
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
549
|
+
const mesh = engine.createMesh().setGeometry(box());
|
|
550
|
+
|
|
551
|
+
await Physics.load();
|
|
552
|
+
const ball = createMesh(engine, sphereGeometry(0.5, 16, 8), new PbrMaterial()).root;
|
|
553
|
+
const physics = Physics.attach(engine);
|
|
554
|
+
const voxels = new VoxelPhysics(physics, world, { radius: 1, budget: 2 });
|
|
555
|
+
physics.addBody(mesh, { colliders: { shape: 'box' } }); // lands on the blocks
|
|
556
|
+
physics.addBody(ball, { colliders: { shape: 'sphere' } }); // rolls on them (triangle meshes, see below)
|
|
557
|
+
physics.on('contactstart', (event) => {
|
|
558
|
+
if (event.bodyB === voxels.body) console.log(event.bodyA, 'hit chunk', voxels.chunkOf(event.colliderB));
|
|
559
|
+
});
|
|
560
|
+
world.setBlock(x, y, z, 0); // the collider changes in place; the body falls
|
|
561
|
+
voxels.budget = 4; // milliseconds of collider building per physics step, live
|
|
562
|
+
voxels.pending; // chunks whose colliders are still being built
|
|
563
|
+
voxels.colliders; // Map of chunk key -> the colliders bodies touch
|
|
564
|
+
voxels.dispose();
|
|
565
|
+
```
|
|
566
|
+
|
|
567
|
+
- **Which chunks.** Before each physics step, every loaded chunk within `radius` chunks (per axis, default 1: the
|
|
568
|
+
body's chunk and its 26 neighbours) of any non-fixed body gets a collider; sleeping bodies count, so they keep their
|
|
569
|
+
floor, and kinematic ones count, so character controllers walk on blocks. A chunk keeps it until no body is within
|
|
570
|
+
`radius + 1` (a body resting on a chunk border does not make chunks come and go) or the chunk unloads.
|
|
571
|
+
- **Slabs and stairs.** Solid slabs and stairs are left out of the voxel collider and collide as their half-block
|
|
572
|
+
boxes: each chunk with any gets one more triangle mesh of their open faces (`FIX_INTERNAL_EDGES`, always enabled,
|
|
573
|
+
beside the voxels or the mesh pieces), rebuilt when a cell in or beside one changes. A box rests on a slab's top at
|
|
574
|
+
`y + 0.5` and on a stair's step or back.
|
|
575
|
+
- **What collides.** The chunk's surface: cells of block types with `solid` (the default) that touch a non-solid cell
|
|
576
|
+
or an unloaded chunk. Buried cells are left out, so an underground chunk costs almost nothing.
|
|
577
|
+
- **Seams and edits.** Each chunk has a `voxels` collider, coupled with its neighbours through
|
|
578
|
+
`combineVoxelStates`, so bodies slide across chunk borders without catching on internal edges. `onChange` edits
|
|
579
|
+
call `setVoxel` (and `propagateVoxelChange` on chunk borders): no rebuilds. A digging edit adds the solid cells it
|
|
580
|
+
uncovers.
|
|
581
|
+
- **Balls.** Today's solver panics (`RuntimeError: unreachable`, which ends its instance) when a `sphere`
|
|
582
|
+
collider meets a voxel edge: rolling off a ledge, across a chunk border or into a wall. So chunks within `radius` of a body with a `sphere` collider also get a triangle mesh
|
|
583
|
+
of the same faces (merged into rectangles, built with `fixInternalEdges` so balls roll over edges and seams without
|
|
584
|
+
a kick) and their voxel collider is disabled; it is still edited and coupled, so voxel chunks beside them stay
|
|
585
|
+
seamless for boxes and capsules. They switch back once no ball body is within `radius + 1`. A mesh is cut into
|
|
586
|
+
pieces of at most 2,048 triangles (the chunk is halved, horizontal cuts first, until each piece fits: a terrain
|
|
587
|
+
surface is 1-2 pieces, a 50% random cave chunk 60), so no single build is long and an edit in or beside a
|
|
588
|
+
piece rebuilds only that piece. The solver can drop up to one step of travel where a ball passes from one collider to
|
|
589
|
+
the next, a chunk border or a piece seam (separate boxes do the same); there is no bump.
|
|
590
|
+
- **Building over steps.** `budget` (milliseconds per physics step, default 2, live) spreads the building. What a
|
|
591
|
+
body can reach before the next step (its collider's size, plus two steps of its velocity, plus 1 m) is built in that
|
|
592
|
+
step whatever it costs: the surroundings of a body that spawns or is teleported, a chunk loaded under a body, the
|
|
593
|
+
mesh pieces around a ball, an edited piece under a body. Everything else (chunks entering the radius, about a chunk
|
|
594
|
+
from the body that needs them; meshes for a ball still a chunk away; stale borders) is built nearest first while the
|
|
595
|
+
step's estimated cost fits the budget, at least one unit (one chunk's voxel collider, one scan of a chunk, or one
|
|
596
|
+
mesh piece) per step. `budget: Infinity` builds everything in the step that needs it. What a ball touches meanwhile:
|
|
597
|
+
- A chunk entering a ball's radius keeps its voxel collider (for the other bodies) while its mesh pieces are built,
|
|
598
|
+
disabled, over the next steps, and switches to the mesh when the last piece is done. The ball is a chunk away.
|
|
599
|
+
- A ball that reaches a chunk before its mesh is done (spawned or teleported into it, very fast, a chunk loaded
|
|
600
|
+
under it) switches it in that step: the voxel collider is disabled and the pieces within reach of every body (the
|
|
601
|
+
ball, a box resting elsewhere in the chunk) are built at once; each other piece is built in the budget or in the
|
|
602
|
+
step a body comes within reach of it. A ball never touches a voxel collider and no body loses the blocks under it.
|
|
603
|
+
- An edited piece keeps its previous mesh until its rebuild replaces it (in the same step when a body is within
|
|
604
|
+
reach of it).
|
|
605
|
+
- **Events and queries.** Every collider belongs to `voxels.body`, one fixed `PhysicsBody` whose `userData` is the
|
|
606
|
+
VoxelPhysics, so contacts with blocks raise the `Physics` events (`contactstart`, `contactend`, and
|
|
607
|
+
`intersectionstart`/`intersectionend` for sensors) with it as `bodyA` or `bodyB` (its `mesh` is null),
|
|
608
|
+
`contactFilter` sees it, and `physics.raycast` and the other queries hit blocks near bodies (pick anywhere with
|
|
609
|
+
`raycastVoxels` from `./query`). `voxels.chunkOf(collider)` names the chunk of a voxel or mesh collider. A collider
|
|
610
|
+
swap (a chunk switching between voxels and a mesh, a rebuilt piece) ends the contact with the old collider and starts
|
|
611
|
+
one with the new in the same step. Removing `voxels.body` disposes the VoxelPhysics.
|
|
612
|
+
|
|
613
|
+
Measured with Node 26 on the reference desktop (NVIDIA RTX A6000, AMD Ryzen 9 9950X, 32 logical cores; 2026-10-19,
|
|
614
|
+
other jobs running, 11-15% total CPU; three runs of `node --test packages/voxel/tests/physics.test.js`, which
|
|
615
|
+
prints yours; time spent in VoxelPhysics per physics step). One chunk built all at once (best of 3): a terrain-surface
|
|
616
|
+
chunk's voxel collider 0.6 ms and triangle mesh 2.3-2.5 ms (2 pieces); a uniform stone chunk 0.9-1.0 ms and 1.0-1.1 ms;
|
|
617
|
+
a 50% random cave chunk 1.7-2.5 ms and 38-41 ms (60 pieces), the worst case for a ball. Per physics step:
|
|
618
|
+
|
|
619
|
+
- That cave chunk entering a ball's radius: 35-46 ms in one step with `budget: Infinity`; 27-29 steps of at most
|
|
620
|
+
1.9-2.2 ms with the default.
|
|
621
|
+
- A ball spawned inside a cave chunk, at the corner of four pieces: 5.2-6.5 ms in its first step (5 of 39 pieces),
|
|
622
|
+
then 20-21 steps of at most 2.0 ms.
|
|
623
|
+
- A body crossing chunk borders over cave chunks at 12 m/s: worst steps 11-13 ms all at once, 3.1-3.3 ms with the
|
|
624
|
+
default (one cave chunk's voxel collider, 1.7-2.5 ms, is the largest unit). The chunk under it always had its
|
|
625
|
+
collider.
|
|
626
|
+
- On terrain (8 x 8 chunk columns): a body crossing a chunk border builds 6 voxel colliders, 1.9-2.4 ms all at once,
|
|
627
|
+
at most 2.0 ms a step with the default; a ball builds 9 colliders and meshes, 5.9-6.9 ms all at once, over 4-5 steps
|
|
628
|
+
of at most 2.1 ms. A body spawning there builds 18 colliders (6.1-7.4 ms at once, or 4-6 steps of at most 2.0 ms), a
|
|
629
|
+
ball 30 (18-21 ms, or 14-17 steps of at most 2.0 ms).
|
|
630
|
+
- A dig or place on voxel chunks costs 1.2-1.5 us against 0.2-0.3 us without colliders; an edit in a mesh chunk
|
|
631
|
+
rebuilds one piece at the next step, 1.1-1.7 ms.
|
|
632
|
+
|
|
633
|
+
A ball rolling over the piece seams of a floor under caves (41-piece chunks) trails a one-box floor by at most
|
|
634
|
+
0.26 m after 150 steps, with no kick (the chunk-border case: 0.23 m). The cost of one unit on slower machines, and so
|
|
635
|
+
their worst step, is unverified; the development laptop measured these builds two to three times slower before this
|
|
636
|
+
change.
|
|
637
|
+
|
|
638
|
+
## Meshing in workers: `VoxelMesher`
|
|
639
|
+
|
|
640
|
+
`VoxelMesher` (also in `@margoengine/voxel/mesher`) runs `meshChunk` in a pool of workers that share one priority
|
|
641
|
+
queue. The worker script ships as `dist/workers/mesher.js`, a classic script without `eval` (fine under a strict CSP)
|
|
642
|
+
that your bundler copies as an asset.
|
|
643
|
+
|
|
644
|
+
```ts
|
|
645
|
+
import { BlockTypes, VoxelWorld } from 'margoengine/voxel';
|
|
646
|
+
import { VoxelMesher } from 'margoengine/voxel/mesher';
|
|
647
|
+
|
|
648
|
+
const world = new VoxelWorld({ blocks: new BlockTypes() });
|
|
649
|
+
const camera = { position: [0, 80, 0] as [number, number, number] };
|
|
650
|
+
const distanceToCamera = (key: string) => {
|
|
651
|
+
const [cx, cy, cz] = key.split(',').map((part) => Number(part) * 32);
|
|
652
|
+
return Math.hypot(cx - camera.position[0], cy - camera.position[1], cz - camera.position[2]);
|
|
653
|
+
};
|
|
654
|
+
const meshes = new Map<string, unknown>();
|
|
655
|
+
const upload = (key: string, mesh: unknown) => meshes.set(key, mesh); // your GPU upload
|
|
656
|
+
const mesher = new VoxelMesher(); // {workers}: default half the logical cores minus one, 1 to 4
|
|
657
|
+
mesher.warm(); // optional: start the workers now, so their code is not fetched beside the first chunks
|
|
658
|
+
for (const key of world.dirty) {
|
|
659
|
+
world.dirty.delete(key);
|
|
660
|
+
mesher.mesh(world, key, distanceToCamera(key), camera.position).then((mesh) => {
|
|
661
|
+
if (mesh) upload(key, mesh); // null: cancelled, superseded, or the chunk is gone (world.getChunk tells which)
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
mesher.cancel('0,2,0'); // the pending job of one chunk resolves null
|
|
665
|
+
mesher.dispose(); // every pending job resolves null; the workers stop
|
|
666
|
+
```
|
|
667
|
+
|
|
668
|
+
- **Order.** Lower `priority` is meshed sooner (the chunk's distance to the camera, say); equal priorities in call order.
|
|
669
|
+
Workers start as jobs arrive, up to `workers`.
|
|
670
|
+
- **Newest wins.** A `mesh` call for a key that already has a queued or running job supersedes it: the older promise
|
|
671
|
+
resolves null at once (a running job's result is dropped when it arrives) and only the newest call's mesh is
|
|
672
|
+
delivered. The `MeshInput` is built with `meshInput` when a worker takes the job, so it holds the world's latest
|
|
673
|
+
blocks and a queued job holds no copy; its buffers and the mesh's arrays move between the threads without copies.
|
|
674
|
+
- **Translucent order.** Pass the camera's world position as `eye` and the worker returns `translucent` sorted back to
|
|
675
|
+
front. `sortQuads(words, localEye)` does the same on any thread (to re-sort a chunk after the camera moves;
|
|
676
|
+
`localEye` is the world position minus 32 times the chunk coordinates). The order is exact for every quad on a cell
|
|
677
|
+
face: along a ray from the eye, the grid distance of the cells it crosses rises at every face, so quads keyed by
|
|
678
|
+
their cell's grid distance from the eye's cell draw farthest first (Frieder, Gordon and Reynolds 1985). Translucent
|
|
679
|
+
faces are not merged, one quad per cell face, so each has one cell. Quads inside one cell (a lowered or waving liquid
|
|
680
|
+
top, an inset slab face, a stair's parts) draw by centre distance; a cross block's two quads cut each other.
|
|
681
|
+
- **Border.** `mesh(world, key, priority, eye, true)` also returns `mesh.border`: one u32 per whole cube, slab or
|
|
682
|
+
stair face of the chunk's one-cell shell that touches the chunk (local cell + 1 in bits 0-5, 6-11 and 12-17, face
|
|
683
|
+
18-20, render layer 21-22), the faces its neighbours mesh along the seams. A beveled `VoxelRenderer` asks for it.
|
|
684
|
+
- **Failures.** A worker that crashes rejects its job's promise and is replaced for the next job.
|
|
685
|
+
|
|
686
|
+
Measured with Node 24 worker threads on the development laptop (8 logical cores) while other jobs kept the whole machine
|
|
687
|
+
at 98-100% CPU (2026-10-19; `node --test packages/voxel/tests/mesher-worker-benchmark.test.js` prints yours), 64
|
|
688
|
+
random-terrain chunks of about 5,600 quads: 326 meshes/s with 1 worker, 540 with 2, 828 with 3 (3.1-3.7 ms per mesh per
|
|
689
|
+
worker, `meshInput` on the main thread included).
|
|
690
|
+
|
|
691
|
+
## Streaming and generation (`./stream`, `./generate`)
|
|
692
|
+
|
|
693
|
+
`VoxelStreamer` (in `@margoengine/voxel/stream`) loads the chunks around the camera and other viewers and unloads the
|
|
694
|
+
rest: from the store first, else from a generator running in workers. `@margoengine/voxel/generate` holds the built-in
|
|
695
|
+
generator, `noiseTerrain`, and `serveVoxelGenerator` for your own.
|
|
696
|
+
|
|
697
|
+
```ts
|
|
698
|
+
import { IndexedDBChunkStore, VoxelStreamer } from 'margoengine/voxel/stream';
|
|
699
|
+
import {Engine} from 'margoengine/core';
|
|
700
|
+
import {BlockTypes, VoxelWorld} from 'margoengine/voxel';
|
|
701
|
+
const blocks = new BlockTypes();
|
|
702
|
+
for (const name of ['stone', 'dirt', 'grass', 'sand', 'water', 'log', 'leaves']) blocks.define(name);
|
|
703
|
+
const world = new VoxelWorld({ blocks });
|
|
704
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
705
|
+
|
|
706
|
+
const streamer = VoxelStreamer.attach(engine, {
|
|
707
|
+
world,
|
|
708
|
+
generator: { seed: 7, seaLevel: 0, trees: 0.01 }, // NoiseTerrainOptions: the built-in worker
|
|
709
|
+
store: new IndexedDBChunkStore('world-1'), // default: a MemoryChunkStore
|
|
710
|
+
distance: 8, // chunks in x and z (256 blocks); verticalDistance: 4
|
|
711
|
+
frameBudget: 0.5, // main-thread ms per update for chunks joining the world (and chunksPerFrame: 8)
|
|
712
|
+
});
|
|
713
|
+
const otherPlayer = { position: [64, 80, 0] as [number, number, number] };
|
|
714
|
+
streamer.viewers.push(otherPlayer.position); // more positions to load around, in blocks
|
|
715
|
+
if (streamer.pending === 0) document.querySelector('#loading')?.remove(); // chunks in range not loaded yet
|
|
716
|
+
addEventListener('pagehide', () => streamer.save()); // edits of loaded chunks; unloads save their own
|
|
717
|
+
await streamer.dispose(); // saves, flushes the store, stops the workers; the chunks stay in the world
|
|
718
|
+
```
|
|
719
|
+
|
|
720
|
+
```ts
|
|
721
|
+
// islands.worker.js, your module worker. Vite: import islands from './islands.worker.js?worker&url'
|
|
722
|
+
import { serveVoxelGenerator } from 'margoengine/voxel/generate';
|
|
723
|
+
|
|
724
|
+
serveVoxelGenerator((chunk, cx, cy, cz, { blocks }) => {
|
|
725
|
+
const stone = blocks.find((type) => type.name === 'stone')!.id; // the world's BlockTypes table
|
|
726
|
+
if (cy < 0) chunk.fill(stone); // chunk: a new air VoxelChunk; cell (x, y, z) is world (32 cx + x, ...)
|
|
727
|
+
return -1; // optional: no block above cell y -1 in this column, so its chunks with cy >= 0 load as air without a job
|
|
728
|
+
});
|
|
729
|
+
// Main thread: new VoxelStreamer({ world, generator: islands }) (or attach), then streamer.update() each frame.
|
|
730
|
+
```
|
|
731
|
+
|
|
732
|
+
- **Range.** A chunk loads when it is within `distance` chunks of a viewer's chunk in x and z (a circle) and
|
|
733
|
+
`verticalDistance` in y, inside the world's minY..maxY. It unloads once it is more than one chunk past that for every
|
|
734
|
+
viewer, so walking back and forth over a chunk border reloads nothing. `distance` and `verticalDistance` can change
|
|
735
|
+
at run time.
|
|
736
|
+
- **Order.** Loads start closest first, at most 4 per worker running or queued, and the next one starts as each finishes
|
|
737
|
+
(not only once per `update()`) while the memory budget has room for every chunk on its way; finished chunks join the
|
|
738
|
+
world closest first, and lighting and meshing follow through `world.onChunk` and `world.dirty`. A generated chunk is
|
|
739
|
+
unpacked when it joins (about 0.06-0.08 ms on the main thread of the desktop below, 0.15-0.19 ms on the laptop). Per
|
|
740
|
+
`update()` at most `chunksPerFrame` (default 8) join, and none after `frameBudget` milliseconds (default 0.5) of
|
|
741
|
+
adding them, listeners included; one always joins, so loading never stalls (0 means one per update). Behind a loading
|
|
742
|
+
screen set both to `Infinity`, or raise them while the world first fills: the sandbox joins 2 ms of chunks a frame
|
|
743
|
+
then (render distance 16 ready in 3.6 s instead of 8.1-8.4 s at 0.5 ms) and goes back to 0.5 ms once ready.
|
|
744
|
+
- **Air above the ground.** A generator can return its column's ceiling, a cell y that no chunk of that column has a
|
|
745
|
+
block above (`noiseTerrain` returns the highest ground, sea or tree crown that reaches the column). Once one chunk of
|
|
746
|
+
a column has come back with it, the column's chunks wholly above it load as air without a worker job (the store is
|
|
747
|
+
still read first, so built chunks up there load). In the sandbox at render distance 16, about 2,360 of 5,579 chunks
|
|
748
|
+
need no job. A ceiling too low loses blocks; return nothing when unsure.
|
|
749
|
+
- **Saving.** Chunks edited through the world (`onChange`), and chunks someone else added, are saved to the store when
|
|
750
|
+
they unload; chunks generated or read from the store and not edited are dropped and regenerate the same. A failed
|
|
751
|
+
save is reported to `onError` and the chunk is kept in memory, where a reload finds it, until a save succeeds.
|
|
752
|
+
- **Memory.** Over `memoryBudget` (default 128 MiB of `chunk.byteLength`) the least recently used chunks outside the
|
|
753
|
+
load range unload first. Loads reserve the loaded chunks' mean size for both running and finished jobs; each
|
|
754
|
+
finished chunk must fit by its actual `byteLength` before it joins. If it cannot fit, it stays pending until space
|
|
755
|
+
or a larger budget is available (even when one chunk exceeds the whole budget). The initial unknown-size batch,
|
|
756
|
+
pending results, workers, stores and failed saves are outside this loaded-data budget. Edits, externally added
|
|
757
|
+
chunks or a reduced budget can put the load range itself over budget; loading then stops until there is room.
|
|
758
|
+
- **Failures.** A chunk the store or the generator fails on goes to `onError` (the engine's with `attach`) and is
|
|
759
|
+
tried again only after it leaves the range and comes back.
|
|
760
|
+
- **`noiseTerrain(options)`.** A fractal simplex heightmap (`height` 8, `amplitude` 32, `scale` 192 blocks) of grass
|
|
761
|
+
over dirt over stone, sand at the shore and on the sea floor, water up to `seaLevel` (0), cave tunnels where two 3D
|
|
762
|
+
simplex fields are both near zero (`caves` 0..1, default 0.3: about 5% of the rock), and trees on grass (`trees`, the
|
|
763
|
+
chance per column, default 0.01) placed by a hash of the column, so a crown that crosses a chunk border is the same
|
|
764
|
+
in every chunk and every generation order. Caves never reach water: rock at a height where a side neighbour column
|
|
765
|
+
holds sea stays (the top block is never carved either). A tree grows only where its whole crown is in open air above
|
|
766
|
+
the ground of every column it covers, so no leaves end up in hillsides or caves; both rules read only the column
|
|
767
|
+
heights around a cell, so chunks stay independent of generation order. The generator's tests scan 144-chunk regions
|
|
768
|
+
across chunk borders for water beside cave air and leaves in the ground (none). Block types come by name
|
|
769
|
+
(`blocks: {stone, dirt, grass, sand, water, log, leaves}`, each defaulting to its key), checked when the streamer
|
|
770
|
+
is created. It runs on any thread (a `VoxelGenerate`); the streamer runs it in `dist/workers/terrain.js`, a classic
|
|
771
|
+
script without `eval`.
|
|
772
|
+
- **Errors.** `TypeError` and `RangeError` for options; MargoError `'attached'` for a second streamer on a world,
|
|
773
|
+
`'unsupported'` for a generator without Web Workers, `'disposed'` after `dispose()`.
|
|
774
|
+
|
|
775
|
+
Measured with Node 24 worker threads on the development laptop (8 logical cores) while other jobs kept it at 96-99%
|
|
776
|
+
CPU (2026-10-19; `node --test packages/voxel/tests/stream-benchmark.test.js` prints yours): `noiseTerrain` 1.4-1.8 ms
|
|
777
|
+
per chunk on one thread; filling a 565-chunk range: 495 chunks/s with 1 worker, 803 with 2, 765 with 3 (the machine
|
|
778
|
+
had no core left for the third); `update()` 11-14 us per call, unpacking included.
|
|
779
|
+
|
|
780
|
+
The cost of `update()` per frame while chunks join, measured with Node 26 on the RTX A6000 desktop (32 logical cores)
|
|
781
|
+
while other jobs kept it at 10-52% CPU (2026-10-19; same file, 3 terrain workers keeping 12 chunks ready, 16 ms
|
|
782
|
+
frames, 565 chunks): with only the 8-chunk cap (the behaviour before `frameBudget`) 0.51-0.64 ms median, 0.76-1.29 ms
|
|
783
|
+
p95 and 0.91-1.97 ms at worst, 7.8 chunks a frame; with the default 0.5 ms budget 0.52-0.56 ms median, 0.67-0.73 ms
|
|
784
|
+
p95, 0.76-0.85 ms at worst, 7.3-7.6 chunks a frame; with 0.25 ms 0.36-0.39 ms median and 0.60-0.72 ms at worst,
|
|
785
|
+
4.4-4.6 chunks a frame (565 chunks in 3.6-3.8 s instead of 2.2 s). Not yet measured on the laptop, where 8 chunks
|
|
786
|
+
cost 1.2-1.5 ms.
|
|
787
|
+
|
|
788
|
+
## Rendering (`@margoengine/voxel/render`)
|
|
789
|
+
|
|
790
|
+
`VoxelRenderer` draws a world with an engine (WebGPU): it meshes the world's dirty chunks in workers (an all-air chunk
|
|
791
|
+
needs no job: it has no faces whatever its neighbours hold), keeps their quads on the GPU and draws every chunk layer
|
|
792
|
+
with one indirect draw. `BlockTextures` holds the block textures.
|
|
793
|
+
|
|
794
|
+
Size: `./render` is 21,798 B gzip (18,931 before bevels and maps). The extra bytes are the parts every world can
|
|
795
|
+
use: about 1.0 KB draws beveled blocks (quad split, glass and liquid triangles sorted together, the triangle pipelines
|
|
796
|
+
in the beauty, shadow and post passes), about 0.6 KB the material table with normal, roughness and emissive maps,
|
|
797
|
+
transmission and texture layers up to 2,047, about 0.3 KB the lightmap hooks, and the rest multi-view. The bevel
|
|
798
|
+
builder and shader are in `./bevel` (4,154 B) and baked light in `./lightmap` (2,506 B), so plain worlds do not load them.
|
|
799
|
+
|
|
800
|
+
```ts
|
|
801
|
+
import { BlockTextures, VoxelRenderer } from 'margoengine/voxel/render';
|
|
802
|
+
import { VoxelLighting } from 'margoengine/voxel/light';
|
|
803
|
+
import { BlockTypes, VoxelWorld } from 'margoengine/voxel';
|
|
804
|
+
import {Engine} from 'margoengine/core';
|
|
805
|
+
const x = 0;
|
|
806
|
+
const y = 0;
|
|
807
|
+
const z = 0;
|
|
808
|
+
const canvas = document.querySelector('canvas')!;
|
|
809
|
+
const engine = await Engine.create(canvas);
|
|
810
|
+
const blocks = new BlockTypes();
|
|
811
|
+
const stone = blocks.define('stone');
|
|
812
|
+
const world = new VoxelWorld({ blocks });
|
|
813
|
+
|
|
814
|
+
const textures = new BlockTextures({ images: [
|
|
815
|
+
[140,140,140,255], [120,80,50,255], [70,170,60,255], [90,130,55,255],
|
|
816
|
+
].map(rgba => ({ width: 1, height: 1, data: new Uint8Array(rgba) })) }); // layers 0-3
|
|
817
|
+
// or BlockTextures.fromAtlas(image, { size: 16 }), or new BlockTextures({ images: [canvas, bitmap, ...] })
|
|
818
|
+
const lighting = VoxelLighting.attach(world); // the renderer shades with the chunks' light bytes
|
|
819
|
+
const voxels = VoxelRenderer.attach(engine, { world, textures });
|
|
820
|
+
engine.onFrame(() => lighting.update());
|
|
821
|
+
world.setBlock(x, y, z, stone); // drawn two frames later
|
|
822
|
+
textures.set(3, canvas); // live
|
|
823
|
+
voxels.daylight = 0.3; // dusk: sky light dims, block light (torches) does not
|
|
824
|
+
voxels.stats; // {chunks, visible, quads, triangles, bytes, draws, compiling, pending} of the last frame
|
|
825
|
+
voxels.dispose(); // workers and GPU buffers; textures.dispose() separately (their GPU copy goes with the last renderer)
|
|
826
|
+
```
|
|
827
|
+
|
|
828
|
+
- **Meshing.** Each frame the renderer takes the keys in `world.dirty` (it is their consumer), sends loaded chunks to a
|
|
829
|
+
`VoxelMesher` (option `workers`) nearest first and frees removed ones at once. Finished meshes are uploaded nearest
|
|
830
|
+
first, about 4 MiB per frame. Translucent quads come back sorted from the camera; a chunk is sorted again on the CPU
|
|
831
|
+
when the eye's cell changes against it (only which side of the chunk the eye is on counts outside its span), at most
|
|
832
|
+
4 chunks a frame, nearest first, and translucent chunks draw by descending grid distance from the eye's chunk.
|
|
833
|
+
- **GPU memory.** One storage buffer holds every quad (12 bytes) in pages of 64; a chunk layer takes a run of pages
|
|
834
|
+
(first fit, reused in place while it still fits). The buffer starts at 4 MiB and doubles up to `maxQuadBytes`
|
|
835
|
+
(default and most: the device's storage binding limit, or its `maxBufferSize` when smaller, in whole pages: 128 MiB,
|
|
836
|
+
11,184,810 quads, on a default WebGPU device; it only grows as chunks need it). A mesh that does not fit waits until
|
|
837
|
+
chunks free pages; `renderer.stats.poolFull` is true while one waits, and `stats.pending` stays above 0 meanwhile.
|
|
838
|
+
Vertices are pulled from it by vertex index (no vertex buffers, no extra GPU feature).
|
|
839
|
+
- **Draws.** Pass order -6 prepares: frustum cull per chunk on the CPU (`@margoengine/math/frustum`) into the indirect
|
|
840
|
+
arguments, uploads, the frame uniform. Order 1 draws opaque blocks (back faces culled) and cutout blocks (both sides,
|
|
841
|
+
alpha to coverage at 4x MSAA, alpha test at 0.5 at 1x) by replaying a render bundle of one `drawIndexedIndirect` per
|
|
842
|
+
chunk layer, re-recorded only when the set of chunk layers with quads, a buffer or the target changes (0.2-0.8 ms for
|
|
843
|
+
2,000 draws). Order 4.5 draws translucent blocks (premultiplied over, no depth write while they blend), then their
|
|
844
|
+
depth alone, so passes after it (screen-space fog, lines at the default order 20) meet the surface, not what is
|
|
845
|
+
behind it. Draw lines that must show through water before 4.5 (`new Lines({ order: 4 })`). Pipelines compile
|
|
846
|
+
asynchronously: the first frames after attaching, or on a new target format, draw nothing.
|
|
847
|
+
- **Shading.** Each pixel is shaded where its ray meets the face's plane, never from interpolated attributes: texture
|
|
848
|
+
coordinates and their gradients (nearest texels up close, trilinear mips in the distance, no seams on tiled greedy
|
|
849
|
+
quads), and AO, sky light and block light bilinear between the quad's corners, so a greedy quad shades like the unit
|
|
850
|
+
faces it covers. Lighting: `engine.lighting`'s sun (PBR, scaled by sky visibility unless a shadow map covers the
|
|
851
|
+
face, see below), a hemisphere ambient term (`radiance[3]` times the ambient colour) times AO, sky light and
|
|
852
|
+
`daylight`, block light as emission in `blockLightColor`, and each type's `emissive`. Without light bytes every face
|
|
853
|
+
sits in the dark: attach `VoxelLighting`, or fill them (`chunk.fillLight(0xf0)` is open sky). rgba16float targets get
|
|
854
|
+
linear colour; others PBR Neutral and sRGB.
|
|
855
|
+
- **Materials.** One 32-byte entry per `blockMaterials` id: texture layer, animation frames and fps (up to 255.99,
|
|
856
|
+
1/256 steps), tint, roughness, metalness, emissive, the normal, roughness and emissive map layers, transmission and
|
|
857
|
+
scatter. Normal maps are tangent space with +y up the image (glTF): u runs along the face's tile coordinates. A
|
|
858
|
+
roughness map replaces `roughness` (red channel), an emissive map scales `emissive` (red). On translucent blocks
|
|
859
|
+
`transmission` lowers alpha by up to 85% and shows the block's own colour through it, softened by `scatter`: a cheap
|
|
860
|
+
look, not refraction. Opaque blocks ignore texture alpha. `fancyLeaves: false` draws cutout cubes solid; cross blocks
|
|
861
|
+
always cut out.
|
|
862
|
+
- **Textures.** An `rgba8unorm-srgb` 2D array: up to 2,048 layers of `size` x `size` texels (over 256 needs a device
|
|
863
|
+
created with a higher `maxTextureArrayLayers`; the renderer throws `MargoError` `'unsupported'` otherwise) (a power of two; default the
|
|
864
|
+
first image's width, or 16; other sizes are drawn at it, nearest-neighbour). Mips are made once on the CPU per layer:
|
|
865
|
+
colour averaged in linear light weighted by alpha; for cutout textures (alpha only 0 and 255) alpha is rescaled so an
|
|
866
|
+
alpha test keeps the level-0 coverage (Castano 2010), so leaves stay dense in the distance; other alpha is averaged.
|
|
867
|
+
Raw `{width, height, data}` pixels need no DOM. Missing layers are white.
|
|
868
|
+
- **T-junctions.** A greedy quad's edges pass through the corners of smaller neighbours; once the rasterizer snaps the
|
|
869
|
+
vertices to its subpixel grid, slivers there let single samples of the background through (up to 41 pixels of a
|
|
870
|
+
320 x 240 grazing view on the Arc 140V). The vertex shader stretches merged quads 1/128 pixel along their own edges,
|
|
871
|
+
in their plane, which closes them (none left in the browser check). Within that fraction of a pixel of an edge a
|
|
872
|
+
sample can then belong to the neighbour, so a greedy image differs from a one-quad-per-face image in a few edge
|
|
873
|
+
pixels (under 0.6% of those drawn, never over an area).
|
|
874
|
+
- **Device loss.** On `engine.rebootDevice()` (or a lost device) every chunk is meshed and uploaded again.
|
|
875
|
+
- **Errors.** `TypeError` for a wrong world, textures or option type, `RangeError` for values out of range (including
|
|
876
|
+
`maxQuadBytes` over the device limit), `MargoError` `'unsupported'` without WebGPU or Web Workers; `BlockTextures`
|
|
877
|
+
throws `RangeError` for sizes and layers, `MargoError` `'unsupported'` for an image without OffscreenCanvas,
|
|
878
|
+
`'failed'` when `load` gets an HTTP error, `'disposed'` after `dispose()`.
|
|
879
|
+
|
|
880
|
+
Checked on the Arc 140V (`node scripts/run-with-timeout.mjs -- node packages/voxel/tests/render-browser-check.mjs`):
|
|
881
|
+
no T-junction cracks at 4x and 1x MSAA, greedy and one-quad-per-face images equal outside edge samples on the canvas
|
|
882
|
+
format and rgba16float, glass and cutout composites to their exact linear values, an edit drawn two frames later, the
|
|
883
|
+
same image after `engine.rebootDevice()`, no validation errors. Rough timing (`--timing`, machine not quiet, timestamp
|
|
884
|
+
queries in 65 us steps): a synthetic render-distance-16 world (2,178 chunks, 1.13M quads, 13.7 MiB) spawns in 1.5-4.6 s
|
|
885
|
+
and its voxel passes take about 3.2 ms of GPU at 1920 x 1080 with 4x MSAA (582 chunks visible), 0.9 ms of CPU per frame
|
|
886
|
+
for the whole `engine.render`.
|
|
887
|
+
|
|
888
|
+
Checked again on the NVIDIA RTX A6000 desktop (2026-10-19, Edge 155): every check above passes at 4x and 1x MSAA, plus
|
|
889
|
+
the worst case: one chunk of 196,608 cutout quads and one of 196,608 translucent quads (3D checkerboards of two types
|
|
890
|
+
each) draw in full with no validation error. Greedy against one-quad-per-face: 22-207 differing edge pixels of
|
|
891
|
+
29,975-56,488 drawn at 4x (0.04-0.52%), 12-44 at 1x, never a 2 x 2 block; bit-identical images are not possible
|
|
892
|
+
because the two meshes put different vertices on the same edges and the rasterizer snaps each. With the edge stretch
|
|
893
|
+
switched off, a grazing slab view shows 14 crack pixels at 4x on this GPU; with it on, none. Rough timing (`--timing`,
|
|
894
|
+
machine not quiet): the render-distance-16 world above spawns in 0.63 s; its voxel passes take about 0.26 ms of GPU
|
|
895
|
+
(the timestamps here come in 0.26 ms steps) and `engine.render` 0.3 ms of CPU per frame.
|
|
896
|
+
|
|
897
|
+
### Lighting effects, day and night, water and lava
|
|
898
|
+
|
|
899
|
+
```ts
|
|
900
|
+
import { Shadows } from 'margoengine/shadows';
|
|
901
|
+
import { Clustered } from 'margoengine/clustered';
|
|
902
|
+
import { Environment, EnvironmentLighting, Fog, loadEnvironmentImage } from 'margoengine/environment';
|
|
903
|
+
import { Sky } from 'margoengine/sky';
|
|
904
|
+
import { BlockTypes, VoxelWorld } from 'margoengine/voxel';
|
|
905
|
+
import { BlockTextures, VoxelRenderer } from 'margoengine/voxel/render';
|
|
906
|
+
import {Engine} from 'margoengine/core';
|
|
907
|
+
const x = 0;
|
|
908
|
+
const y = 0;
|
|
909
|
+
const z = 0;
|
|
910
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
911
|
+
|
|
912
|
+
const world = new VoxelWorld({ blocks: new BlockTypes() });
|
|
913
|
+
const textures = new BlockTextures({ images: [{ width: 1, height: 1, data: new Uint8Array([140,140,140,255]) }] });
|
|
914
|
+
const voxels = VoxelRenderer.attach(engine, { world, textures });
|
|
915
|
+
const sky = Sky.attach(engine);
|
|
916
|
+
const environment = EnvironmentLighting.attach(engine, await Environment.attach(engine, await loadEnvironmentImage('/studio.hdr')));
|
|
917
|
+
const shadows = Shadows.attach(engine, { distance: 96, cascades: 2 });
|
|
918
|
+
shadows.add(voxels, { static: true }); // casts (opaque and cutout) and receives; the map is redrawn only on change
|
|
919
|
+
const lights = Clustered.attach(engine);
|
|
920
|
+
lights.setLights([{ position: [x, y, z], range: 10, color: [1, 0.7, 0.4], intensity: 20 }]);
|
|
921
|
+
lights.add(voxels);
|
|
922
|
+
Fog.attach(engine, { color: '#b8c8d8', near: 64, far: 256 }).add(voxels);
|
|
923
|
+
environment.add(voxels); // an EnvironmentLighting: image-based ambient instead of the hemisphere term
|
|
924
|
+
engine.onFrame(() => (voxels.daylight = 1 - sky.nightFactor)); // a Sky drives engine.lighting's sun and moon itself
|
|
925
|
+
voxels.blockLightColor = [1, 0.7, 0.45]; // torches warmer
|
|
926
|
+
```
|
|
927
|
+
|
|
928
|
+
- **Effects.** `addLighting(effect)` takes any object with glTF PBR's lighting hooks (`pbr(group)`, `bindings()`):
|
|
929
|
+
`Shadows`, `Clustered`, `Fog` and `EnvironmentLighting` call it from their `add`. The shader is composed again and
|
|
930
|
+
compiled in the background; until it is ready the previous pipelines keep drawing (`stats.compiling` is true
|
|
931
|
+
meanwhile). The last four compositions stay compiled, so taking out the effect added last, or putting one back,
|
|
932
|
+
draws at once. `stats.pending` counts the chunks not yet on the GPU (changed, meshing or waiting for upload): a frame
|
|
933
|
+
with `pending` 0, `compiling` false and `draws` above 0 shows the whole world. Each effect's remover takes it out again. Effects' bindings are group 1 (shadows 1-3, clustered 4-7, IBL 20-24, fog 25).
|
|
934
|
+
- **Shadows.** `drawShadow` draws the opaque and cutout chunks inside each cascade (CPU-culled per cascade) into the
|
|
935
|
+
map, cutout blocks alpha tested at their texture's level 0; translucent blocks cast none. Every quad reaches 1/64
|
|
936
|
+
block past its edges in the map, so T-junction slivers cannot let light through and merged and unit quads cast the
|
|
937
|
+
same shadow. The caster declares its position `@invariant` (WGSL 12.10) as every Margo shadow caster's is, so another program drawing the same surface writes the same depth bit for bit. It returns false while its pipelines still compile (the first call starts them). With `{static: true}` the map is redrawn only when `shadowVersion` changes (chunks with opaque or cutout
|
|
938
|
+
quads arriving, changing or leaving inside the last map's cascades, new textures or buffers) or the cascades move.
|
|
939
|
+
- **Sun and sky.** Without a shadow map the sun reaches a face as far as the open sky does (sky light squared, so
|
|
940
|
+
caves stay dark). Inside a shadow map's range the map decides alone (an overhang's shadow is the map's, not a dimmed
|
|
941
|
+
sky term); over the last tenth of the range the sky term fades back in, and beyond it the sky term rules.
|
|
942
|
+
- **Ambient.** The hemisphere term, or IBL's when an `EnvironmentLighting` is added, is scaled by the occlusion: AO x
|
|
943
|
+
(0.03 + sky light x `daylight`), so caves and night dim it and block light does not. `daylight` 0 leaves 0.03 / 1.03
|
|
944
|
+
of the daytime ambient.
|
|
945
|
+
- **Animation.** A block type's `animation: {frames, fps}` steps through `frames` texture layers from its first one
|
|
946
|
+
(lava and water textures, fire). Liquid surfaces (the mesher's wave bit: a liquid cell's top and sides with no same
|
|
947
|
+
liquid above) rise and fall together by 0.04 blocks (`0.04 sin(1.6 t)`) and ripple: the top's shading normal follows
|
|
948
|
+
three travelling waves of world x and z, so neighbouring quads and chunks match.
|
|
949
|
+
|
|
950
|
+
Checked on the NVIDIA RTX A6000 (2026-10-19, `node scripts/run-with-timeout.mjs -- node
|
|
951
|
+
packages/voxel/tests/render-lighting-browser-check.mjs`; linear HDR radiance at projected world points, 4x and 1x MSAA):
|
|
952
|
+
with the sun straight down and no ambient, the floor under a 4 x 4 slab and under a cutout block's opaque square is 0
|
|
953
|
+
while the floor beside them and under the square's transparent border keeps its unshadowed value (0.9272); five still
|
|
954
|
+
frames reuse the cached static map; removing the slab lights the floor again 2 frames later. A floor with no sky is lit
|
|
955
|
+
inside a 40-block shadow range (0.9316) and black beyond it. A clustered point light (range 8, 3 blocks up) gives 0.990
|
|
956
|
+
under it, 0.557 two blocks away, 0.164 at four and 0 outside its range, and nothing once removed. Linear fog from 0 to
|
|
957
|
+
40 blocks toward linear [0.2, 0.4, 0.8] at 19.42 blocks gives [0.5757, 0.6724, 0.8662] against [0.5750, 0.6721, 0.8662]
|
|
958
|
+
expected. IBL and the
|
|
959
|
+
hemisphere ambient at daylight 0 are 0.02914 of daylight 1 (0.03 / 1.03 = 0.02913). Block light 15 under no sky shows
|
|
960
|
+
`blockLightColor` [0.2, 0.4, 0.8] as [0.2000, 0.3999, 0.7998]. Two-frame animation shows red then blue after a second.
|
|
961
|
+
A water cell's side top edge moves 6 rows at 4x and 5 at 1x between crest and trough (5.54 expected). Greedy against
|
|
962
|
+
one-quad-per-face with soft shadows, a point light, fog and the waving pool: 141-267 differing edge pixels of 76,800 at
|
|
963
|
+
4x, 34-74 at 1x, never a 2 x 2 block. No validation errors.
|
|
964
|
+
|
|
965
|
+
### Far from the origin
|
|
966
|
+
|
|
967
|
+
A float32 position steps by about a centimetre at 100 km, so a world drawn in world coordinates far from zero shakes
|
|
968
|
+
and opens seams. Pass `origin` to each `VoxelRenderer` (a `FloatingOrigin` of `@margoengine/cameras/origin`, or any
|
|
969
|
+
object whose `origin` is the float64 world point at engine zero, read every frame). Chunks stay at their world
|
|
970
|
+
cells; the camera works in engine space (world minus origin). The GPU draws chunks relative to a base snapped to
|
|
971
|
+
1,024 cells near the origin, so chunk origins stay exact integers, and the rest of the origin is folded into the
|
|
972
|
+
camera and shadow matrices in float64: every float32 value the GPU reads stays within about 1,500 cells of zero,
|
|
973
|
+
wherever the world is. Lighting hooks see engine positions; liquid ripples and wind keep their phase across a rebase.
|
|
974
|
+
Tested at 2^24 blocks. Default null: world and engine space are the same.
|
|
975
|
+
|
|
976
|
+
```ts
|
|
977
|
+
import { FloatingOrigin } from 'margoengine/cameras/origin';
|
|
978
|
+
import { Engine } from 'margoengine/core';
|
|
979
|
+
import { BlockTypes, VoxelWorld } from 'margoengine/voxel';
|
|
980
|
+
import { BlockTextures, VoxelRenderer } from 'margoengine/voxel/render';
|
|
981
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
982
|
+
const blocks = new BlockTypes();
|
|
983
|
+
const stone = blocks.define('stone');
|
|
984
|
+
const world = new VoxelWorld({ blocks });
|
|
985
|
+
const textures = new BlockTextures({ images: [{ width: 1, height: 1, data: new Uint8Array([140, 140, 140, 255]) }] });
|
|
986
|
+
const origin = FloatingOrigin.attach(engine);
|
|
987
|
+
const far = 16_000_000; // blocks (metres) from zero
|
|
988
|
+
world.setBlock(far, 64, far, stone);
|
|
989
|
+
origin.lookAt([far - 10, 70, far - 10], [far, 64, far]); // float64 world camera; the origin follows it
|
|
990
|
+
const voxels = VoxelRenderer.attach(engine, { world, textures, origin });
|
|
991
|
+
const eye = origin.cameraPosition; // world blocks, float64: for streamers and VoxelLod.update
|
|
992
|
+
voxels.origin = null; // live: back to world = engine space
|
|
993
|
+
```
|
|
994
|
+
|
|
995
|
+
Give the same `origin` to every far level of `@margoengine/voxel/lod` and pass streamers and `VoxelLod.update` the
|
|
996
|
+
world eye (`origin.cameraPosition`). Bounce light (`/gi`) and RGB light (`/light-rgb`) follow the origin of the
|
|
997
|
+
renderer they were added to with their `add(voxels)`: their windows sit around the camera's world cell and the shading
|
|
998
|
+
reads them in engine space. `SmoothTerrainView`, `VoxelObjects`, `VoxelModelRenderer` and `VoxelDebris` take the same
|
|
999
|
+
`origin` option (a live field): their meshes sit at world minus origin, computed in float64, and move when the origin
|
|
1000
|
+
moves. Debris with `physics` takes no origin (physics simulates in world coordinates; docs/known-bugs.md).
|
|
1001
|
+
|
|
1002
|
+
```ts
|
|
1003
|
+
import { FloatingOrigin } from 'margoengine/cameras/origin';
|
|
1004
|
+
import { Engine, PbrMaterial } from 'margoengine/core';
|
|
1005
|
+
import { VoxelWorld, BlockTypes } from 'margoengine/voxel';
|
|
1006
|
+
import { VoxelObjects } from 'margoengine/voxel/objects';
|
|
1007
|
+
import { VoxelModelRenderer } from 'margoengine/voxel/models';
|
|
1008
|
+
import { VoxelDebris } from 'margoengine/voxel/debris';
|
|
1009
|
+
import { SmoothTerrain, SmoothTerrainView } from 'margoengine/voxel/smooth';
|
|
1010
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
1011
|
+
const origin = FloatingOrigin.attach(engine);
|
|
1012
|
+
const world = new VoxelWorld({ blocks: new BlockTypes() });
|
|
1013
|
+
const objects = VoxelObjects.attach(engine, world, { origin });
|
|
1014
|
+
const models = await VoxelModelRenderer.create(engine, world, { origin });
|
|
1015
|
+
const debris = new VoxelDebris(world, { engine, origin });
|
|
1016
|
+
const smooth = SmoothTerrainView.attach(engine, { terrain: new SmoothTerrain(), materials: [new PbrMaterial({ color: '#7a6a55' })], origin });
|
|
1017
|
+
```
|
|
1018
|
+
|
|
1019
|
+
## Bevels and baked light (`./render`)
|
|
1020
|
+
|
|
1021
|
+
`VoxelRenderer.attach(engine, { world, textures, bevel: voxelBevel(0.15) })` (`voxelBevel` from `./bevel`, its own
|
|
1022
|
+
entry: worlds without a bevel carry none of it) chamfers exposed cube faces by 0.15 blocks along the cells'
|
|
1023
|
+
silhouette: every convex or concave crease of the block surface becomes a 45 degree strip and every corner a small
|
|
1024
|
+
polygon, while faces that go on in the same plane stay flat however the mesher merged or split them, so the surface
|
|
1025
|
+
stays closed. Each chunk layer's cube faces become a triangle mesh (`bevelQuads`, one 48-byte vertex buffer and an index buffer per layer), lit by the same shader end as the quads (sky light, sun, AO, block light, maps and lighting
|
|
1026
|
+
effects), cast into shadow maps and replayed by post (gbuffer, ambient, occlusion, capture; `draw` returns false until
|
|
1027
|
+
the replay's pipelines, compiled in the background on its first call, are ready). Crosses and liquids stay
|
|
1028
|
+
quads (a chamfer has no lowered liquid top). Translucent chamfers and quads of a chunk are sorted together, back to
|
|
1029
|
+
front, within the same distance and per-frame budget as quads. Without `bevel` nothing changes. Chunks meet as one
|
|
1030
|
+
mesh would: with a bevel the renderer asks its mesher for each chunk's `border` (the whole faces of the one-cell shell
|
|
1031
|
+
that touch the chunk, which the neighbouring chunks mesh) and passes them to `bevelQuads(faces, amount, context)`, so
|
|
1032
|
+
an edge or corner on a seam is chamfered from the faces on both sides and both chunks put their vertices at the same
|
|
1033
|
+
points along it, however each merged its quads. A mesher that ignores `border` (one written before it) gives sharp
|
|
1034
|
+
seams, as before.
|
|
1035
|
+
|
|
1036
|
+
```ts
|
|
1037
|
+
import { Engine } from 'margoengine/core';
|
|
1038
|
+
import { bakeLightmap } from 'margoengine/lightmap';
|
|
1039
|
+
import { BlockTypes, VoxelWorld } from 'margoengine/voxel';
|
|
1040
|
+
import { voxelLightmap } from 'margoengine/voxel/lightmap';
|
|
1041
|
+
import { BlockTextures, VoxelRenderer } from 'margoengine/voxel/render';
|
|
1042
|
+
|
|
1043
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
1044
|
+
const world = new VoxelWorld({ blocks: new BlockTypes() });
|
|
1045
|
+
const textures = new BlockTextures({ images: [{ width: 1, height: 1, data: new Uint8Array([140,140,140,255]) }] });
|
|
1046
|
+
const voxels = VoxelRenderer.attach(engine, { world, textures });
|
|
1047
|
+
const positions = new Float32Array([0, 0, 0, 4, 0, 0, 4, 0, 4, 0, 0, 4]);
|
|
1048
|
+
const atlas = await bakeLightmap(
|
|
1049
|
+
{ positions, albedo: new Float32Array([0.8, 0.8, 0.8, 1]) },
|
|
1050
|
+
{ texelsPerUnit: 4, lights: [{ type: 'directional', direction: [0.3, 1, 0.2], intensity: 2 }] },
|
|
1051
|
+
);
|
|
1052
|
+
// Called once per device, so the baked light comes back by itself after a device restore.
|
|
1053
|
+
const texture = (device: GPUDevice) => {
|
|
1054
|
+
const made = device.createTexture({
|
|
1055
|
+
size: [atlas.width, atlas.height],
|
|
1056
|
+
format: 'rgba8unorm',
|
|
1057
|
+
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
|
|
1058
|
+
});
|
|
1059
|
+
device.queue.writeTexture({ texture: made }, atlas.textures.lightmap, { bytesPerRow: atlas.width * 4 }, [atlas.width, atlas.height]);
|
|
1060
|
+
return made;
|
|
1061
|
+
};
|
|
1062
|
+
voxels.lightmap = voxelLightmap({ texture, positions, uv: atlas.uv, scale: atlas.lightmapScale, radiometry: 'physical' });
|
|
1063
|
+
voxels.lightmap = undefined; // live lighting again
|
|
1064
|
+
```
|
|
1065
|
+
|
|
1066
|
+
`voxelLightmap` (its own entry: worlds without baked light carry none of it) takes an atlas from
|
|
1067
|
+
`@margoengine/lightmap` and the world-space quads it was baked for (integer, axis-aligned rectangles; at most 32,768
|
|
1068
|
+
covering 1,048,576 cell faces). Fragments on a chart use the atlas's light times the diffuse
|
|
1069
|
+
colour instead of the sun and ambient terms; emission still adds and the rest stay live. `radiometry: 'physical'`
|
|
1070
|
+
(the bake's physical irradiance) divides by pi once. Positions and UVs are copied; the texture is borrowed, never
|
|
1071
|
+
destroyed. Pass it as `(device) => GPUTexture` and the renderer makes it once per device, so it is back after a device
|
|
1072
|
+
restore. A plain `GPUTexture` is lost with its device: the renderer draws with live lighting, reports it once through
|
|
1073
|
+
`engine.onError` (`'state'`, [#borrowed-lost](https://margoengine.com/errors#borrowed-lost)), and assigning a new
|
|
1074
|
+
`voxelLightmap` brings the baked light back. A hash index finds a fragment's chart in at most 16 probes per cell.
|
|
1075
|
+
|
|
1076
|
+
GPU check (physical GPU): `node packages/voxel/tests/bevel-browser-check.mjs`: bevel silhouettes,
|
|
1077
|
+
texture layers 256 and 2047, maps, glass and liquid sorting, four views, lightmaps, bevel replay, shadows and AO.
|
|
1078
|
+
|
|
1079
|
+
Multi-view: `engine.render({ views })` draws the world once per view (split screen, picture in picture, a minimap).
|
|
1080
|
+
Each view's faces are shaded from rays through that view's own rectangle, so a view at any `viewport` draws the same
|
|
1081
|
+
pixels as the full target would at that size (`render-browser-check.mjs` checks two side-by-side views of one camera).
|
|
1082
|
+
|
|
1083
|
+
## Far levels of detail (`@margoengine/voxel/lod`)
|
|
1084
|
+
|
|
1085
|
+
`VoxelLod` keeps coarse copies of the terrain around the eye so the view reaches kilometres for about the cost of the
|
|
1086
|
+
streamed chunks: level L is a `VoxelWorld` whose cell covers 2^L blocks a side, drawn by a `VoxelRenderer` with
|
|
1087
|
+
`scale: 2^L` and lit by its own `VoxelLighting`. Each level adds a ring of about the same number of nodes (a node is one
|
|
1088
|
+
of its 32-cubed chunks), so every level doubles the view distance at the same cost.
|
|
1089
|
+
|
|
1090
|
+
```ts
|
|
1091
|
+
import { BlockTypes, VoxelWorld } from 'margoengine/voxel';
|
|
1092
|
+
import { VoxelLighting } from 'margoengine/voxel/light';
|
|
1093
|
+
import { noiseTerrainLod, VoxelLod } from 'margoengine/voxel/lod';
|
|
1094
|
+
import { BlockTextures, VoxelRenderer } from 'margoengine/voxel/render';
|
|
1095
|
+
import { VoxelStreamer } from 'margoengine/voxel/stream';
|
|
1096
|
+
import { Engine } from 'margoengine/core';
|
|
1097
|
+
|
|
1098
|
+
const engine = await Engine.create(document.querySelector('canvas')!, { camera: { far: 20000 } });
|
|
1099
|
+
const blocks = new BlockTypes();
|
|
1100
|
+
for (const name of ['stone', 'dirt', 'grass', 'sand', 'log']) blocks.define(name);
|
|
1101
|
+
blocks.define('water', { shape: 'liquid', liquid: true, solid: false, layer: 'translucent' });
|
|
1102
|
+
blocks.define('leaves', { layer: 'cutout' });
|
|
1103
|
+
const world = new VoxelWorld({ blocks });
|
|
1104
|
+
// One plain 16 x 16 layer; or await BlockTextures.load(['stone.png']).
|
|
1105
|
+
const textures = new BlockTextures({ images: [{ width: 16, height: 16, data: new Uint8Array(1024).fill(200) }] });
|
|
1106
|
+
const terrain = { seed: 7 };
|
|
1107
|
+
VoxelStreamer.attach(engine, { world, generator: terrain, distance: 8 });
|
|
1108
|
+
const lighting = VoxelLighting.attach(world);
|
|
1109
|
+
VoxelRenderer.attach(engine, { world, textures });
|
|
1110
|
+
|
|
1111
|
+
const lod = new VoxelLod({ world, generate: noiseTerrainLod(terrain), levels: 4, radius: 8 }); // 4,096 blocks
|
|
1112
|
+
const far = lod.levels.map((level) => ({
|
|
1113
|
+
light: VoxelLighting.attach(level.world),
|
|
1114
|
+
renderer: VoxelRenderer.attach(engine, { world: level.world, textures, scale: level.scale, workers: 1 }),
|
|
1115
|
+
}));
|
|
1116
|
+
engine.onFrame(() => {
|
|
1117
|
+
lod.update(engine.camera.position); // at most `budget` (8) nodes generated a frame, nearest first
|
|
1118
|
+
lighting.update();
|
|
1119
|
+
for (const { light } of far) light.update();
|
|
1120
|
+
});
|
|
1121
|
+
lod.stats; // {nodes: [per level], pending}
|
|
1122
|
+
```
|
|
1123
|
+
|
|
1124
|
+
- **Nodes.** A node of level L >= 2 splits into its 8 children when the eye is nearer than `radius` child sizes
|
|
1125
|
+
(Chebyshev distance to its box); the top level holds the nodes within `radius` of its own size. Level 1 never splits:
|
|
1126
|
+
it fills everything inside the level-2 ring, its cells over chunks the real world has loaded left empty (a node is
|
|
1127
|
+
masked again when one of its 8 chunks loads or unloads), so the real chunks and the coarse ones never overlap and an
|
|
1128
|
+
unloaded chunk shows its coarse copy instead of a hole. Keep `2 * radius` above the streamer's `distance` + 1 so the
|
|
1129
|
+
streamed chunks stay inside level 1. The faces a level shows against an empty neighbour (the finer level's area, a
|
|
1130
|
+
masked chunk) are meshed, which closes the seams like a skirt.
|
|
1131
|
+
- **Changes.** A node no longer wanted stays until no missing node overlaps it, so a level change or a split never
|
|
1132
|
+
opens a hole; meanwhile both may show. New ground at the horizon comes in over a few frames.
|
|
1133
|
+
- **Generators.** `generate(chunk, x, y, z, scale, {blocks})` fills node (x, y, z) of a level: cell (i, j, k) covers
|
|
1134
|
+
blocks from ((32 x + i) scale, ...). `noiseTerrainLod(options)` takes `noiseTerrain`'s options and gives the same
|
|
1135
|
+
ground and sea, each coarse column the ground height at its centre block rounded to the nearest whole cell (within half
|
|
1136
|
+
a cell of the real surface there; the tests check it against `noiseTerrain`). It leaves out caves and trees.
|
|
1137
|
+
- **Scaled renderers.** `VoxelRenderer` option `scale` (a power of two, 1 to 4,096) draws a world whose cells are that
|
|
1138
|
+
many blocks: the camera, its inverse, the eye and the culling planes go to cell units, so meshing, textures (one tile
|
|
1139
|
+
over a coarse cell), AO and light work unchanged. A scaled renderer takes no lighting effects, casts no shadows and
|
|
1140
|
+
joins no capture (`MargoError` `'unsupported'`); screen-space passes that read depth see the right distances.
|
|
1141
|
+
- **Errors.** `TypeError` for a wrong world, generator, eye or option type, `RangeError` for options out of range.
|
|
1142
|
+
|
|
1143
|
+
GPU check (`node packages/voxel/tests/lod-browser-check.mjs`, in `test:gpu`): a world drawn at scale 2 from twice the
|
|
1144
|
+
eye, near and far gives the same image as at scale 1 (0 of 29,823 drawn pixels differ on the Apple silicon Mac, Metal), and four
|
|
1145
|
+
levels of `noiseTerrainLod` draw terrain to the horizon from 90 blocks up with no validation error. Node generation runs
|
|
1146
|
+
on the main thread (about a millisecond a node; `budget` caps it per frame); frame cost at kilometre views is unmeasured.
|
|
1147
|
+
|
|
1148
|
+
## Light in a worker (`@margoengine/voxel/light-worker`)
|
|
1149
|
+
|
|
1150
|
+
`VoxelLightWorker` computes the same sky and block light as `VoxelLighting`, in a Web Worker: the page posts chunk
|
|
1151
|
+
loads, unloads and edits to it and writes back the light bytes it answers with, so removing a roof or loading a chunk
|
|
1152
|
+
costs the page the copies, not the flood fill.
|
|
1153
|
+
|
|
1154
|
+
```ts
|
|
1155
|
+
import { BlockTypes, VoxelWorld } from 'margoengine/voxel';
|
|
1156
|
+
import { VoxelLightWorker } from 'margoengine/voxel/light-worker';
|
|
1157
|
+
import { BlockTextures, VoxelRenderer } from 'margoengine/voxel/render';
|
|
1158
|
+
import { Engine } from 'margoengine/core';
|
|
1159
|
+
|
|
1160
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
1161
|
+
const blocks = new BlockTypes();
|
|
1162
|
+
const stone = blocks.define('stone');
|
|
1163
|
+
const world = new VoxelWorld({ blocks });
|
|
1164
|
+
// One plain 16 x 16 layer; or await BlockTextures.load(['stone.png']).
|
|
1165
|
+
const textures = new BlockTextures({ images: [{ width: 16, height: 16, data: new Uint8Array(1024).fill(200) }] });
|
|
1166
|
+
const lighting = VoxelLightWorker.attach(world); // instead of VoxelLighting.attach(world)
|
|
1167
|
+
VoxelRenderer.attach(engine, { world, textures });
|
|
1168
|
+
engine.onFrame(() => lighting.update()); // posts this frame's changes, writes the light that came back
|
|
1169
|
+
world.setBlock(0, 64, 0, stone);
|
|
1170
|
+
await lighting.settled(); // the worker has answered everything so far (a loading screen)
|
|
1171
|
+
lighting.update();
|
|
1172
|
+
lighting.dispose();
|
|
1173
|
+
```
|
|
1174
|
+
|
|
1175
|
+
- **Same light.** The worker keeps a copy of the world's blocks (chunk loads, unloads, edits and block types defined
|
|
1176
|
+
later go to it in page order) and runs `VoxelLighting` on it with no budget; the tests check every light byte against
|
|
1177
|
+
`VoxelLighting` on the page after loads, torches, a roof removed and put back, slabs, unloads and reloads.
|
|
1178
|
+
- **Writing back.** `update()` writes the light of each chunk the worker changed (its byte, or its 32 KiB) and the
|
|
1179
|
+
heightmaps of their columns, and adds those chunks to `world.dirty`. Light computed for a chunk that has been unloaded
|
|
1180
|
+
or loaded again since is dropped; the newer load's light follows. Light arrives a frame or more after the change.
|
|
1181
|
+
- **Memory.** The worker holds a second copy of every loaded chunk's blocks and light.
|
|
1182
|
+
- **Errors.** `TypeError` for a wrong world or `worker` option, `MargoError` `'unsupported'` without Web Workers,
|
|
1183
|
+
`'attached'` for a second one on a world, `'disposed'` after `dispose()`; a worker failure is thrown by the next
|
|
1184
|
+
`update()` or `settled()`. Do not attach `VoxelLighting` to the same world.
|
|
1185
|
+
|
|
1186
|
+
Measured with Node on the Apple silicon Mac while other lanes ran (diagnostic; `node --test
|
|
1187
|
+
packages/voxel/tests/light-worker-benchmark.test.js` prints yours): removing a 32 x 32 stone roof over a 39-deep room (89,088 cells) took 4.5-8.4 ms
|
|
1188
|
+
of `VoxelLighting.update()` on the page; with `VoxelLightWorker` the page spent 0.12-0.37 ms posting the edits and
|
|
1189
|
+
0.01-0.03 ms writing the 18 chunks back.
|
|
1190
|
+
|
|
1191
|
+
|
|
1192
|
+
## Coloured block light (`@margoengine/voxel/light-rgb`)
|
|
1193
|
+
|
|
1194
|
+
`VoxelColorLight` gives block light a colour: each emitter's `light` level splits into red, green and blue levels by
|
|
1195
|
+
its colour, each channel floods like `VoxelLighting`'s block light, and a `VoxelRenderer` lighting effect adds the
|
|
1196
|
+
coloured light per pixel.
|
|
1197
|
+
|
|
1198
|
+
```ts
|
|
1199
|
+
import { BlockTypes, VoxelWorld } from 'margoengine/voxel';
|
|
1200
|
+
import { VoxelLighting } from 'margoengine/voxel/light';
|
|
1201
|
+
import { VoxelColorLight } from 'margoengine/voxel/light-rgb';
|
|
1202
|
+
import { BlockTextures, VoxelRenderer } from 'margoengine/voxel/render';
|
|
1203
|
+
import { Engine } from 'margoengine/core';
|
|
1204
|
+
|
|
1205
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
1206
|
+
const blocks = new BlockTypes();
|
|
1207
|
+
const stone = blocks.define('stone');
|
|
1208
|
+
const lava = blocks.define('lava', { shape: 'liquid', liquid: true, solid: false, light: 15 });
|
|
1209
|
+
const lamp = blocks.define('lamp', { light: 14 });
|
|
1210
|
+
const world = new VoxelWorld({ blocks });
|
|
1211
|
+
// One plain 16 x 16 layer; or await BlockTextures.load(['stone.png']).
|
|
1212
|
+
const textures = new BlockTextures({ images: [{ width: 16, height: 16, data: new Uint8Array(1024).fill(200) }] });
|
|
1213
|
+
const lighting = VoxelLighting.attach(world); // sky light and the renderer's light bytes
|
|
1214
|
+
const voxels = VoxelRenderer.attach(engine, { world, textures });
|
|
1215
|
+
voxels.blockLightColor = [0, 0, 0]; // the coloured light replaces the single-channel block light
|
|
1216
|
+
const colored = VoxelColorLight.attach(engine, { world, colors: { lava: [1, 0.35, 0.05], lamp: [0.3, 0.6, 1] } });
|
|
1217
|
+
colored.add(voxels);
|
|
1218
|
+
engine.onFrame(() => {
|
|
1219
|
+
lighting.update();
|
|
1220
|
+
colored.update(); // floods up to `budget` cells a channel, uploads what changed near the camera
|
|
1221
|
+
});
|
|
1222
|
+
world.setBlock(0, 64, 0, lamp);
|
|
1223
|
+
colored.update();
|
|
1224
|
+
colored.levels(0, 65, 0); // [3, 7, 13]: the lamp's [4, 8, 14] one cell away
|
|
1225
|
+
colored.setColor('lamp', [0.2, 1, 0.3]); // live
|
|
1226
|
+
```
|
|
1227
|
+
|
|
1228
|
+
- **Levels.** A type's channel level is its `light` times that channel of its colour, rounded (types not in `colors`
|
|
1229
|
+
are white: all three at `light`). Each channel is a copy of the world's blocks lit by `VoxelLighting`, so costs,
|
|
1230
|
+
opacity, slabs and stairs are exactly block light's; the tests check every channel against `VoxelLighting` with the
|
|
1231
|
+
emitters' levels set to that channel. Colours mix where lights overlap, each channel the brighter of the two.
|
|
1232
|
+
- **On the GPU.** The levels of the cells within `extent` blocks around the camera (default 128 x 64 x 128, 4 MiB)
|
|
1233
|
+
sit in an `rgba8unorm` 3D texture that wraps, so moving the camera uploads only the chunks that come into range.
|
|
1234
|
+
The effect takes the cells around the point half a cell in front of each pixel's face, open cells only (one
|
|
1235
|
+
trilinear fetch of level x open and open), and adds the base colour times the renderer's level-to-brightness curve
|
|
1236
|
+
times `strength`. Beyond the box there is no coloured light.
|
|
1237
|
+
- **Cost.** Three copies of every loaded chunk's blocks and light, and three floods per change.
|
|
1238
|
+
- **Errors.** `TypeError` for a wrong engine, world or option type, `RangeError` for colours outside 0..1, an `extent`
|
|
1239
|
+
that is not three multiples of 32 up to 1,024, a `strength` that is not a finite number >= 0 (at attach, and at
|
|
1240
|
+
`update()` for a value set later), or `setColor` of an undefined type; `MargoError` `'disposed'` after
|
|
1241
|
+
`dispose()`.
|
|
1242
|
+
|
|
1243
|
+
GPU check (`node packages/voxel/tests/light-rgb-browser-check.mjs`, in `test:gpu`): a closed room with a red torch and
|
|
1244
|
+
a blue lamp, the renderer's block light off, is black without the effect and red by the torch, blue by the lamp with it
|
|
1245
|
+
(Apple silicon Mac, Metal).
|
|
1246
|
+
|
|
1247
|
+
|
|
1248
|
+
## Flowing liquids (`@margoengine/voxel/fluids`)
|
|
1249
|
+
|
|
1250
|
+
`VoxelFluids` makes liquid blocks flow: a source spreads sideways and falls, flowing cells dry up when nothing feeds
|
|
1251
|
+
them, and two liquids that meet turn into blocks.
|
|
1252
|
+
|
|
1253
|
+
```ts
|
|
1254
|
+
import { BlockTypes, VoxelWorld } from 'margoengine/voxel';
|
|
1255
|
+
import { VoxelFluids } from 'margoengine/voxel/fluids';
|
|
1256
|
+
import { Engine } from 'margoengine/core';
|
|
1257
|
+
|
|
1258
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
1259
|
+
const blocks = new BlockTypes();
|
|
1260
|
+
blocks.define('stone');
|
|
1261
|
+
const water = blocks.define('water', { shape: 'liquid', liquid: true, solid: false, layer: 'translucent' });
|
|
1262
|
+
blocks.define('lava', { shape: 'liquid', liquid: true, solid: false, light: 15 });
|
|
1263
|
+
blocks.define('obsidian');
|
|
1264
|
+
blocks.define('cobblestone');
|
|
1265
|
+
const world = new VoxelWorld({ blocks });
|
|
1266
|
+
const fluids = VoxelFluids.attach(world, {
|
|
1267
|
+
fluids: [{ block: 'water', infinite: true }, { block: 'lava', reach: 3, delay: 30 }],
|
|
1268
|
+
mixes: [{ fluid: 'lava', touches: 'water', source: 'obsidian', flowing: 'cobblestone' }],
|
|
1269
|
+
});
|
|
1270
|
+
engine.onFrame((_, delta) => fluids.update(delta)); // 20 ticks a second
|
|
1271
|
+
world.setBlock(0, 64, 0, water); // a source: it flows
|
|
1272
|
+
```
|
|
1273
|
+
|
|
1274
|
+
- **Levels.** A liquid cell's state data is its level: 0 a source (full), 1 to 7 flowing (the mesher lowers its top
|
|
1275
|
+
by that many eighths), `FLUID_FALLING` (8) falling, full, fed from above. A liquid with `reach` r steps
|
|
1276
|
+
`floor(7 / r)` levels a cell (water 1, lava 2) and runs r cells: a cell past level `r * floor(7 / r)` dries up,
|
|
1277
|
+
so a reach of 4 runs levels 1 to 4.
|
|
1278
|
+
- **Steps.** Any change schedules the cell and its six neighbours `delay` ticks later. A due flowing cell first
|
|
1279
|
+
settles: with the same liquid above it falls, else its level is the lowest beside it plus the step, and past 7 it
|
|
1280
|
+
dries up; with `infinite`, two sources beside it on solid ground or a source make it one. Then it flows: down into
|
|
1281
|
+
an open cell (air, or neither solid nor liquid, so plants wash away) as a falling cell; else, from solid ground or a
|
|
1282
|
+
source below, sideways to the next level, only toward the nearest drop within 4 cells when there is one (counted
|
|
1283
|
+
through cells it already flows in). Mixes: a cell beside or under the liquid it `touches` becomes `source` or
|
|
1284
|
+
`flowing`. Unloaded chunks and the world's y range stop it like rock.
|
|
1285
|
+
- **Ticks.** `update(seconds)` runs whole ticks at `ticksPerSecond` (at most 10 a call), `tick()` one, `settle()`
|
|
1286
|
+
until nothing is pending; at most `maxUpdates` cells a tick, the rest wait a tick. Edits go through the world, so
|
|
1287
|
+
light, meshes and change events follow.
|
|
1288
|
+
- **Errors.** `TypeError` for a wrong world or option type, `RangeError` for options out of range, an undefined block
|
|
1289
|
+
or a fluid that is not a `'liquid'` shape; `MargoError` `'disposed'` after `dispose()`.
|
|
1290
|
+
|
|
1291
|
+
|
|
1292
|
+
## Block ticks and cellular rules (`@margoengine/voxel/ticks`)
|
|
1293
|
+
|
|
1294
|
+
`VoxelTicks` runs block rules on a fixed tick: random ticks for growth and spread, scheduled ticks for timers, and
|
|
1295
|
+
`placed` and `neighbor` hooks when a cell or the cell beside it changes. Built-in rules cover falling sand, spreading
|
|
1296
|
+
grass, growing crops and fire.
|
|
1297
|
+
|
|
1298
|
+
```ts
|
|
1299
|
+
import { BlockTypes, VoxelWorld } from 'margoengine/voxel';
|
|
1300
|
+
import { fallingRule, fireRule, growRule, spreadRule, VoxelTicks } from 'margoengine/voxel/ticks';
|
|
1301
|
+
import { Engine } from 'margoengine/core';
|
|
1302
|
+
|
|
1303
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
1304
|
+
const blocks = new BlockTypes();
|
|
1305
|
+
const dirt = blocks.define('dirt');
|
|
1306
|
+
blocks.define('grass');
|
|
1307
|
+
blocks.define('sand');
|
|
1308
|
+
blocks.define('wheat', { shape: 'cross', solid: false, layer: 'cutout' });
|
|
1309
|
+
const planks = blocks.define('planks');
|
|
1310
|
+
blocks.define('fire', { shape: 'cross', solid: false, layer: 'cutout', light: 15 });
|
|
1311
|
+
const world = new VoxelWorld({ blocks });
|
|
1312
|
+
const ticks = VoxelTicks.attach(world, {
|
|
1313
|
+
rules: {
|
|
1314
|
+
sand: fallingRule(),
|
|
1315
|
+
grass: spreadRule({ onto: dirt, light: 9, smothered: dirt }),
|
|
1316
|
+
wheat: growRule(8, 0.3),
|
|
1317
|
+
fire: fireRule({ burns: { [planks]: 0.3 } }),
|
|
1318
|
+
},
|
|
1319
|
+
});
|
|
1320
|
+
ticks.rule('dirt', { random: (c) => c.random() < 0.001 && c.world.setBlock(c.x, c.y + 1, c.z, 0) }); // your own
|
|
1321
|
+
engine.onFrame((_, delta) => ticks.update(delta)); // 20 ticks a second
|
|
1322
|
+
```
|
|
1323
|
+
|
|
1324
|
+
- **A tick** runs, in order: the scheduled updates due (in the order they were scheduled), the random ticks
|
|
1325
|
+
(`randomTicks` cells per loaded chunk, default 24, picked by a seeded generator, chunks in load order), then the
|
|
1326
|
+
`placed` hook of every cell changed since the last tick and the `neighbor` hooks of its six neighbours. Changes the
|
|
1327
|
+
hooks make run next tick, so a chain never recurses. At most `maxUpdates` scheduled and neighbour updates a tick.
|
|
1328
|
+
The same seed, world and edits give the same result. A hook that throws ends the tick with its error; the updates
|
|
1329
|
+
after it wait for the next tick and stay counted in `pending`.
|
|
1330
|
+
- **Hooks** get `{world, x, y, z, state, tick, random(), schedule(delay)}`; `schedule` runs the cell's `scheduled`
|
|
1331
|
+
hook later (for whatever block is there then).
|
|
1332
|
+
- **Built-in rules.** `fallingRule(delay)`: falls a cell every `delay` ticks while the cell below is open (air or not
|
|
1333
|
+
solid, loaded, in range). If it falls into liquid, that liquid occupies the vacated cell
|
|
1334
|
+
and keeps its level and other state. `spreadRule({onto, chance, light, smothered})`: on a random tick, onto an `onto` block in
|
|
1335
|
+
the 3 x 3 x 3 around it whose cell above is not solid and has at least `light` sky light; a solid block on top turns
|
|
1336
|
+
it into `smothered`. `growRule(stages, chance, grown)`: state data counts the stages, then `grown`.
|
|
1337
|
+
`fireRule({burns, delay, life})`: each step sets each burnable neighbour on fire with its chance, ages, and goes out
|
|
1338
|
+
after `life` steps or with nothing left to burn.
|
|
1339
|
+
- **Errors.** `TypeError` for a wrong world, option or rule type, `RangeError` for options out of range or a rule for an
|
|
1340
|
+
undefined block; `MargoError` `'disposed'` after `dispose()`.
|
|
1341
|
+
|
|
1342
|
+
## Meshing on the GPU (`@margoengine/voxel/gpu-mesher`)
|
|
1343
|
+
|
|
1344
|
+
`GpuVoxelMesher` meshes chunks in WebGPU compute shaders and gives back the same quads, in the same order, as
|
|
1345
|
+
`meshChunk`. Give it to the renderer in place of its worker pool, so a large edit remeshes in a few GPU passes.
|
|
1346
|
+
|
|
1347
|
+
```ts
|
|
1348
|
+
import { Engine } from 'margoengine/core';
|
|
1349
|
+
import { BlockTypes, VoxelWorld } from 'margoengine/voxel';
|
|
1350
|
+
import { GpuVoxelMesher } from 'margoengine/voxel/gpu-mesher';
|
|
1351
|
+
import { BlockTextures, VoxelRenderer } from 'margoengine/voxel/render';
|
|
1352
|
+
|
|
1353
|
+
const engine = await Engine.create(document.querySelector('canvas')!, { backend: 'webgpu' });
|
|
1354
|
+
const grey = { width: 16, height: 16, data: new Uint8Array(1024).fill(180) };
|
|
1355
|
+
const textures = new BlockTextures({ images: [grey] });
|
|
1356
|
+
const blocks = new BlockTypes();
|
|
1357
|
+
const stone = blocks.define('stone', { textures: 0 });
|
|
1358
|
+
const world = new VoxelWorld({ blocks });
|
|
1359
|
+
world.addChunk(0, 0, 0);
|
|
1360
|
+
for (let x = 0; x < 32; x++) for (let z = 0; z < 32; z++) world.setBlock(x, (x * z) % 7, z, stone);
|
|
1361
|
+
const mesher = new GpuVoxelMesher(engine.gpu!, { batch: 8 });
|
|
1362
|
+
VoxelRenderer.attach(engine, { world, textures, mesher });
|
|
1363
|
+
// Or mesh chunks yourself: calls made together go out in one batch.
|
|
1364
|
+
const mesh = await mesher.mesh(world, '0,0,0');
|
|
1365
|
+
console.log(mesh?.opaque.length, mesher.stats); // 3 words per quad; { gpu, cpu, empty, batches }
|
|
1366
|
+
```
|
|
1367
|
+
|
|
1368
|
+
- **Same output.** Faces, ambient occlusion, smooth light, greedy merges, cross blocks, liquid levels and visibility
|
|
1369
|
+
match `meshChunk` word for word (checked on every chunk of a lit test terrain on the Apple silicon Mac's Metal GPU).
|
|
1370
|
+
- **Batches.** `mesh(world, key, priority, eye, border)` works like `VoxelMesher.mesh` (the border is read on the
|
|
1371
|
+
page from the same shell): calls made in the same task go out
|
|
1372
|
+
together, up to `batch` chunks per dispatch (default 8, 1 to 32), lowest priority first; a newer call for a key
|
|
1373
|
+
supersedes the older one (null), `cancel(key)` drops one. Each batch slot takes about 3.5 MB of GPU memory.
|
|
1374
|
+
- **On this thread.** A chunk with a slab or stair within a cell of it is meshed by `meshChunk` on the page
|
|
1375
|
+
(`stats.cpu`); an all-air chunk needs no GPU (`stats.empty`). The page still packs each chunk and its shell and
|
|
1376
|
+
finds which chunk faces see each other, then waits for two GPU round trips per batch.
|
|
1377
|
+
- **Renderer.** `VoxelRendererOptions.mesher` takes this mesher (or any object with `mesh`, `cancel` and `dispose`);
|
|
1378
|
+
the renderer does not dispose a mesher it was given.
|
|
1379
|
+
- **Device restore.** The mesher belongs to the device it was made with. When that device is lost its jobs wait (none
|
|
1380
|
+
runs on the lost device), and `setDevice(device)` moves it to a new one, where they run and the pipelines and scratch
|
|
1381
|
+
are made again. A `VoxelRenderer` given the mesher calls `setDevice(engine.gpu)` from its own restore hook and meshes
|
|
1382
|
+
every chunk again, so nothing is needed; a page meshing chunks itself calls it after `await engine.rebootDevice()`.
|
|
1383
|
+
A mesher of your own that holds GPU objects implements `setDevice` the same way.
|
|
1384
|
+
- **Errors.** `TypeError` without a `GPUDevice`, `RangeError` for a `batch` out of range or over the device's binding
|
|
1385
|
+
limit and for wrong keys, priorities or eyes; a mesh rejects with `MargoError` `'failed'` when the GPU reports a
|
|
1386
|
+
validation error; `MargoError` `'disposed'` after `dispose()` (also `[Symbol.dispose]`).
|
|
1387
|
+
|
|
1388
|
+
## Smooth terrain (`@margoengine/voxel/smooth`)
|
|
1389
|
+
|
|
1390
|
+
`SmoothTerrain` holds smooth voxel terrain in 32-cubed chunks: a signed density per cell (solid above 0) and a material.
|
|
1391
|
+
`meshSmoothChunk` meshes a chunk with Surface Nets, and `SmoothTerrainView` draws the chunks as core meshes, so a block
|
|
1392
|
+
world's `VoxelRenderer` draws beside it in the same scene.
|
|
1393
|
+
|
|
1394
|
+
```ts
|
|
1395
|
+
import { Engine, PbrMaterial } from 'margoengine/core';
|
|
1396
|
+
import { SmoothTerrain, SmoothTerrainView } from 'margoengine/voxel/smooth';
|
|
1397
|
+
|
|
1398
|
+
const engine = await Engine.create(document.querySelector('canvas')!, { backend: 'webgpu' });
|
|
1399
|
+
const terrain = new SmoothTerrain();
|
|
1400
|
+
const height = (x: number, z: number) => 12 + 5 * Math.sin(x / 11) + 4 * Math.cos(z / 9);
|
|
1401
|
+
for (let cx = 0; cx < 3; cx++)
|
|
1402
|
+
for (let cz = 0; cz < 3; cz++)
|
|
1403
|
+
terrain.addChunk(cx, 0, cz, (x, y, z) => height(x, z) - y, (x, y, z) => (y > height(x, z) - 2 ? 0 : 1));
|
|
1404
|
+
const view = SmoothTerrainView.attach(engine, {
|
|
1405
|
+
terrain,
|
|
1406
|
+
materials: [new PbrMaterial({ color: '#3fae3a' }), new PbrMaterial({ color: '#8a6f5a' })],
|
|
1407
|
+
});
|
|
1408
|
+
terrain.sculpt([30, 10, 30], 6, -1); // carve a smooth hollow; 1 builds up instead
|
|
1409
|
+
engine.onFrame(() => view.update()); // meshes up to 4 dirty chunks a frame, nearest first
|
|
1410
|
+
engine.start();
|
|
1411
|
+
```
|
|
1412
|
+
|
|
1413
|
+
Textured ground: pass `createMesh` instead of `materials` and draw each chunk part with any renderer. A triplanar
|
|
1414
|
+
`PbrMaterial` of `@margoengine/materials` projects its maps from world space, so the Surface Nets mesh needs no UVs:
|
|
1415
|
+
|
|
1416
|
+
```ts
|
|
1417
|
+
import { Engine } from 'margoengine/core';
|
|
1418
|
+
import { PbrMaterial, createMesh, loadTexture } from 'margoengine/materials';
|
|
1419
|
+
import { SmoothTerrain, SmoothTerrainView } from 'margoengine/voxel/smooth';
|
|
1420
|
+
|
|
1421
|
+
const engine = await Engine.create(document.querySelector('canvas')!, { backend: 'webgpu' });
|
|
1422
|
+
const terrain = new SmoothTerrain();
|
|
1423
|
+
terrain.addChunk(0, 0, 0, (x, y, z) => 10 + 3 * Math.sin(x / 6) - y, (x, y, z) => (y > 8 ? 0 : 1));
|
|
1424
|
+
const [grass, rock] = await Promise.all(['/grass.png', '/rock.png'].map((url) => loadTexture(url)));
|
|
1425
|
+
const looks = [grass, rock].map((map) => new PbrMaterial({ map, triplanar: true, triplanarScale: 0.25 }));
|
|
1426
|
+
const view = SmoothTerrainView.attach(engine, {
|
|
1427
|
+
terrain,
|
|
1428
|
+
createMesh(part, material, origin) {
|
|
1429
|
+
const mesh = createMesh(engine, part, looks[material] ?? looks[0]);
|
|
1430
|
+
mesh.root.position.set(origin[0], origin[1], origin[2]);
|
|
1431
|
+
return { dispose: () => mesh.destroy() };
|
|
1432
|
+
},
|
|
1433
|
+
});
|
|
1434
|
+
engine.onFrame(() => view.update());
|
|
1435
|
+
engine.start();
|
|
1436
|
+
```
|
|
1437
|
+
|
|
1438
|
+
- **Density.** `addChunk(cx, cy, cz, density, material)` samples `density(x, y, z)` at each cell (positive inside, about
|
|
1439
|
+
the signed distance in blocks near the surface, stored clamped to -1..1 in 1/127ths) and `material` (0 to 255). Chunks
|
|
1440
|
+
load and unload in any order; `removeChunk` unloads one. `sculpt(center, radius, strength, material)` moves every cell
|
|
1441
|
+
within `radius` toward solid (`strength` > 0) or air by `strength` times its closeness to the centre.
|
|
1442
|
+
- **Meshing.** One surface point per net cell the surface crosses, at the mean of its edge crossings, one quad per pair
|
|
1443
|
+
of neighbouring samples across the surface, normals from the density gradient (the method of
|
|
1444
|
+
`@margoengine/voxel-edit/smooth`, over densities instead of filled cells). Samples past the chunk come from its loaded
|
|
1445
|
+
neighbours, so chunks join without seams; past an unloaded neighbour the border repeats along that axis (the surface
|
|
1446
|
+
stays open there, no wall). With `skirt` (blocks, on `meshSmoothChunk` or `SmoothTerrainView`) each chunk mesh is
|
|
1447
|
+
clipped to its box and its faces with no loaded neighbour are closed by caps reaching that far from the border (32
|
|
1448
|
+
closes them whole), to join far levels of `./smooth-lod` with no crack. Each quad takes its solid sample's material; `meshSmoothChunk` returns one
|
|
1449
|
+
part per material.
|
|
1450
|
+
- **Dirty chunks.** Every change puts the chunks that read the changed cells in `terrain.dirty` (a chunk and the
|
|
1451
|
+
neighbours sharing its border cells); `view.update()` meshes up to `budget` of them (default 4) on this thread, nearest
|
|
1452
|
+
the camera first, and swaps their core meshes (one per chunk and material, placed at the chunk's corner).
|
|
1453
|
+
- **Custom meshes.** `createMesh(part, material, origin)` (optional; default: a core mesh with `materials[material]`)
|
|
1454
|
+
gets each part's positions, normals and indices in the chunk's own blocks and the chunk's corner in world blocks; it
|
|
1455
|
+
returns an object with `dispose()`, which the view calls when the chunk is meshed again or unloaded and on
|
|
1456
|
+
`view.dispose()`. `materials` may then be left out.
|
|
1457
|
+
- **Errors.** `TypeError` for a wrong engine, terrain, field or materials list, a `createMesh` that is not a function or
|
|
1458
|
+
returns no `dispose()`; `RangeError` for chunk coordinates
|
|
1459
|
+
outside the y range (`minChunkY` -4, `maxChunkY` 7 by default), a NaN density, a material outside 0 to 255, or sculpt
|
|
1460
|
+
arguments out of range; `MargoError` `'disposed'` after `view.dispose()` (also `[Symbol.dispose]`), which removes its
|
|
1461
|
+
meshes.
|
|
1462
|
+
|
|
1463
|
+
## Smooth far levels (`@margoengine/voxel/smooth-lod`)
|
|
1464
|
+
|
|
1465
|
+
`SmoothLod` draws a smooth terrain out to kilometres: coarse Surface Nets meshes of the same density field around the
|
|
1466
|
+
eye, each level's cells twice the size of the one before, chosen like `VoxelLod` (a level reaches `radius` of its nodes
|
|
1467
|
+
before the next coarser one takes over). Level 1 leaves out the 32-block boxes of the loaded real chunks, and every mesh
|
|
1468
|
+
is clipped to its box with its faces closed by caps, so the levels and the real terrain join with no cracks.
|
|
1469
|
+
|
|
1470
|
+
```ts
|
|
1471
|
+
import { Engine, PbrMaterial } from 'margoengine/core';
|
|
1472
|
+
import { SmoothTerrain, SmoothTerrainView } from 'margoengine/voxel/smooth';
|
|
1473
|
+
import { SmoothLod } from 'margoengine/voxel/smooth-lod';
|
|
1474
|
+
|
|
1475
|
+
const engine = await Engine.create(document.querySelector('canvas')!, { backend: 'webgpu' });
|
|
1476
|
+
const height = (x: number, z: number) => 24 + 14 * Math.sin(x / 53) * Math.cos(z / 41);
|
|
1477
|
+
const density = (x: number, y: number, z: number) => height(x, z) - y;
|
|
1478
|
+
const material = (x: number, y: number, z: number) => (y > height(x, z) - 2 ? 0 : 1);
|
|
1479
|
+
const materials = [new PbrMaterial({ color: '#3fae3a' }), new PbrMaterial({ color: '#8a6f5a' })];
|
|
1480
|
+
const terrain = new SmoothTerrain();
|
|
1481
|
+
for (let cx = -2; cx < 2; cx++)
|
|
1482
|
+
for (let cz = -2; cz < 2; cz++) for (let cy = 0; cy < 2; cy++) terrain.addChunk(cx, cy, cz, density, material);
|
|
1483
|
+
const view = SmoothTerrainView.attach(engine, { terrain, materials, skirt: 32 }); // real chunks with closed faces
|
|
1484
|
+
const far = SmoothLod.attach(engine, { terrain, density, material, materials }); // 4 levels, 4,096 blocks
|
|
1485
|
+
engine.onFrame(() => {
|
|
1486
|
+
view.update();
|
|
1487
|
+
far.update(); // eye: the camera (plus `origin`); meshes up to 8 nodes a frame, nearest first
|
|
1488
|
+
});
|
|
1489
|
+
engine.start();
|
|
1490
|
+
```
|
|
1491
|
+
|
|
1492
|
+
- **Levels.** `levels` (1 to 12, default 4) far levels; level L samples `density` every 2^L blocks, so one node of 32
|
|
1493
|
+
samples per axis covers 32 x 2^L blocks. `radius` (2 to 32, default 8) nodes of a level before the next one: the view
|
|
1494
|
+
reaches `radius * 32 * 2^levels` blocks. `minY` and `maxY` (default -64 and 255) bound the levels in y. Keep the real
|
|
1495
|
+
chunks inside level 1 (`2 * radius` above the streamed distance in chunks + 1).
|
|
1496
|
+
- **Seams.** Each node's triangles are clipped to its box, so two nodes of one level meet exactly on their shared face;
|
|
1497
|
+
every face is closed by a cap, the part of the face plane inside the ground, so each node mesh bounds a closed solid
|
|
1498
|
+
and no ray from the air passes between two levels, even where the ground runs nearly parallel to a node face or
|
|
1499
|
+
folds inside a cell (caves, overhangs): the two faces meeting at a box edge take what is solid there from the same
|
|
1500
|
+
samples.
|
|
1501
|
+
`skirt` (0 to 32, default 32) is how many cells the cap reaches from the border; below 32 a near-parallel seam can
|
|
1502
|
+
open. Draw the real terrain with `SmoothTerrainView` option `skirt: 32` (blocks) so its border with level 1 is closed
|
|
1503
|
+
the same way.
|
|
1504
|
+
- **Real terrain.** Level-1 octants over loaded real chunks are left out and meshed again when a chunk loads or unloads.
|
|
1505
|
+
Sculpted edits show only in the real chunks: far levels sample `density`.
|
|
1506
|
+
- **Handover.** `update(eye?)` meshes up to `budget` (default 8, or `Infinity`) missing nodes nearest first and drops a
|
|
1507
|
+
node no longer wanted once no missing node overlaps it, so moving never opens a hole. `stats` gives nodes on show per
|
|
1508
|
+
level, pending nodes and meshes.
|
|
1509
|
+
- **Meshes.** One core mesh per node and material with `materials[material]`, or `createMesh(part, material, origin,
|
|
1510
|
+
level)` returning an object with `dispose()`. `meshSmoothLodNode(density, level, x, y, z, {material, skirt, mask})`
|
|
1511
|
+
returns a node's parts without drawing. `origin` takes a `FloatingOrigin` like `SmoothTerrainView`.
|
|
1512
|
+
- **Errors.** `TypeError` for a wrong engine, terrain, field, `createMesh` or materials list, or an eye that is not three
|
|
1513
|
+
finite numbers; `RangeError` for an option out of range, `minY` above `maxY`, a NaN density or a material outside 0 to
|
|
1514
|
+
255; `MargoError` `'disposed'` after `dispose()` (also `[Symbol.dispose]`), which removes every node mesh.
|
|
1515
|
+
|
|
1516
|
+
## Ray-traced bounce light (`@margoengine/voxel/gi`)
|
|
1517
|
+
|
|
1518
|
+
`VoxelGI` traces rays through the world's own blocks on the GPU for bounce light (sunlit blocks colour what faces them)
|
|
1519
|
+
and soft sun shadows, and adds both to a `VoxelRenderer` as a lighting effect. It follows the engine's directional
|
|
1520
|
+
light. For path-traced pictures of voxel models, see `@margoengine/voxel-pathtracer`; this one is a real-time term for
|
|
1521
|
+
block worlds.
|
|
1522
|
+
|
|
1523
|
+
```ts
|
|
1524
|
+
import { Engine } from 'margoengine/core';
|
|
1525
|
+
import { BlockTypes, VoxelWorld } from 'margoengine/voxel';
|
|
1526
|
+
import { VoxelGI } from 'margoengine/voxel/gi';
|
|
1527
|
+
import { VoxelLighting } from 'margoengine/voxel/light';
|
|
1528
|
+
import { BlockTextures, VoxelRenderer } from 'margoengine/voxel/render';
|
|
1529
|
+
|
|
1530
|
+
const engine = await Engine.create(document.querySelector('canvas')!, { backend: 'webgpu' });
|
|
1531
|
+
const pixels = (r: number, g: number, b: number) => ({
|
|
1532
|
+
width: 16,
|
|
1533
|
+
height: 16,
|
|
1534
|
+
data: Uint8Array.from({ length: 1024 }, (_, i) => [r, g, b, 255][i & 3]),
|
|
1535
|
+
});
|
|
1536
|
+
const textures = new BlockTextures({ images: [pixels(230, 230, 230), pixels(220, 40, 30)] });
|
|
1537
|
+
const blocks = new BlockTypes();
|
|
1538
|
+
const white = blocks.define('white', { textures: 0 });
|
|
1539
|
+
const red = blocks.define('red', { textures: 1 });
|
|
1540
|
+
const world = new VoxelWorld({ blocks });
|
|
1541
|
+
world.addChunk(0, 0, 0);
|
|
1542
|
+
for (let x = 0; x < 32; x++) for (let z = 0; z < 32; z++) world.setBlock(x, 0, z, white);
|
|
1543
|
+
for (let x = 8; x < 20; x++) for (let y = 1; y < 10; y++) world.setBlock(x, y, 20, red);
|
|
1544
|
+
VoxelLighting.attach(world).update();
|
|
1545
|
+
const voxels = VoxelRenderer.attach(engine, { world, textures });
|
|
1546
|
+
const gi = VoxelGI.attach(engine, { world, albedo: { red: [0.8, 0.05, 0.03] }, softness: 0.05 });
|
|
1547
|
+
gi.add(voxels);
|
|
1548
|
+
engine.onFrame(() => gi.update()); // traces the next 32,768 open cells of the window
|
|
1549
|
+
engine.start();
|
|
1550
|
+
```
|
|
1551
|
+
|
|
1552
|
+
- **What it traces.** The blocks of a 64 x 64 x 64 window around the camera (moved in steps of 32 cells) go to the GPU
|
|
1553
|
+
as a grid; only opaque cubes stop rays. Each `update()` traces the next `cells` open cells of the window (default
|
|
1554
|
+
32,768, so the whole window refreshes every 8 updates): `rays` directions over the sphere (default 4, up to `range`
|
|
1555
|
+
cells, default 32), each hit block face sending back its albedo times the sunlight on it (its own shadow ray to the
|
|
1556
|
+
sun), stored as L1 spherical harmonics per cell, plus one ray toward a random point of the sun's disc (`softness`, its
|
|
1557
|
+
half-angle in radians) for the cell's sun visibility. A new window starts from its first sweep; later sweeps blend in
|
|
1558
|
+
an eighth each, so moving light settles over a few dozen updates.
|
|
1559
|
+
- **Shading.** The renderer adds `albedo x irradiance / pi` in the face's normal, read from the open cells around the
|
|
1560
|
+
point half a cell in front of the face (`strength` scales it, live), and multiplies the sun term by the visibility
|
|
1561
|
+
there. Outside the window there is no bounce light and the sun is unshadowed.
|
|
1562
|
+
- **Cost.** About 26 MB of GPU memory (the 1 MB grid, 16 MB of sums and four 2 MB volumes); the trace cost grows with
|
|
1563
|
+
`cells x rays`. Changing blocks or the block table re-uploads the window's blocks (on this thread, 262,144 cells).
|
|
1564
|
+
- **Device restore.** After a device loss the engine's restored device gets new volumes at the next `update()`, which
|
|
1565
|
+
traces the window from its first sweep again. Frames drawn before that `update()` draw without the effect, as before
|
|
1566
|
+
the first one: `pbr` is undefined and `bindings()` empty, so nothing of the lost device is bound.
|
|
1567
|
+
- **Errors.** `TypeError` for a wrong engine or world, `RangeError` for options out of range, an albedo that is not
|
|
1568
|
+
[r, g, b] in 0..1 or (at `update()`) a `strength` set outside 0 to 8, `MargoError` `'unsupported'` without WebGPU, `'disposed'` after `dispose()` (also
|
|
1569
|
+
`[Symbol.dispose]`).
|
|
1570
|
+
|
|
1571
|
+
## Destruction: loose pieces break off (`@margoengine/voxel/debris`)
|
|
1572
|
+
|
|
1573
|
+
`VoxelDebris` watches a world's edits. When a removal cuts a group of solid blocks off from everything that holds it,
|
|
1574
|
+
`update()` takes the group out of the world in one `setBlocks` and turns it into a piece: a dynamic body in your
|
|
1575
|
+
`Physics` (with `VoxelPhysics` on the same world it lands on the blocks) and, given an `engine`, core meshes of its
|
|
1576
|
+
open faces that follow the body.
|
|
1577
|
+
|
|
1578
|
+
```ts
|
|
1579
|
+
import { Physics } from 'margoengine/physics';
|
|
1580
|
+
import { BlockTypes, VoxelWorld } from 'margoengine/voxel';
|
|
1581
|
+
import { VoxelDebris } from 'margoengine/voxel/debris';
|
|
1582
|
+
import { VoxelPhysics } from 'margoengine/voxel/physics';
|
|
1583
|
+
|
|
1584
|
+
await Physics.load();
|
|
1585
|
+
const physics = new Physics(null, { gravity: [0, -9.81, 0] }); // Physics.attach(engine) in an app
|
|
1586
|
+
const blocks = new BlockTypes();
|
|
1587
|
+
const stone = blocks.define('stone');
|
|
1588
|
+
const world = new VoxelWorld({ blocks });
|
|
1589
|
+
world.addChunk(0, 0, 0);
|
|
1590
|
+
const edits: number[] = [];
|
|
1591
|
+
for (let x = 0; x < 32; x++) for (let z = 0; z < 32; z++) edits.push(x, 0, z, stone);
|
|
1592
|
+
for (let y = 1; y < 5; y++) edits.push(10, y, 10, stone); // a pillar
|
|
1593
|
+
for (let x = 10; x < 16; x++) edits.push(x, 5, 10, stone); // a beam on it
|
|
1594
|
+
world.setBlocks(edits);
|
|
1595
|
+
new VoxelPhysics(physics, world, { budget: Infinity });
|
|
1596
|
+
const debris = new VoxelDebris(world, { physics }); // add `engine` to draw the pieces
|
|
1597
|
+
debris.onBreak((piece) => console.log(`${piece.cells.length / 3} blocks broke off`)); // 8 blocks broke off
|
|
1598
|
+
world.setBlock(10, 2, 10, 0); // cut the pillar
|
|
1599
|
+
for (let i = 0; i < 120; i++) {
|
|
1600
|
+
debris.update(1 / 60); // after edits, before the step
|
|
1601
|
+
physics.step();
|
|
1602
|
+
}
|
|
1603
|
+
console.log(debris.pieces[0].body!.position[1] < 5); // true: the beam fell onto the floor
|
|
1604
|
+
```
|
|
1605
|
+
|
|
1606
|
+
- **What holds a group.** Blocks join through their faces when their type is `solid` and not a liquid (flowers, water
|
|
1607
|
+
and air neither join nor hold). A group is held when it reaches a cell at `floor` or below (default `-Infinity`), an
|
|
1608
|
+
`anchors` block type (ids or names, such as bedrock), a chunk that is not loaded, or `maxCells` cells (default
|
|
1609
|
+
4,096, up to 65,536), which bounds the search. Anything else breaks off. Only removals of solid blocks start a search,
|
|
1610
|
+
from the six cells beside each, depth first and downward first.
|
|
1611
|
+
- **The piece.** `cells` and `states` are the blocks it held, `center` the mean of their centres (the body's start and
|
|
1612
|
+
the mesh origin), `boxes` the merged boxes of its compound collider (runs along x, merged along z, then y), `body` a
|
|
1613
|
+
dynamic body of `density` kg per cell (default 1) and `friction` 0.6 whose `userData` is the piece, and `meshes` one
|
|
1614
|
+
core mesh per block type (`material(type)`, default a `PbrMaterial` of the type's colour), the first driven by the
|
|
1615
|
+
body and the others its children.
|
|
1616
|
+
- **Lifetime.** `update(delta)` ages the pieces; one past `lifetime` seconds (default `Infinity`) is removed, as is the
|
|
1617
|
+
oldest when more than `maxPieces` (default 64) are alive. `remove(piece)` removes one now; `dispose()` (also `using`)
|
|
1618
|
+
removes all and stops watching. Pieces never go back into the world.
|
|
1619
|
+
- **Errors.** `TypeError` for a wrong world, physics, engine or option type, `RangeError` for an option out of range or
|
|
1620
|
+
an anchor that is not a defined block type, `MargoError` `disposed` from `update` after `dispose()`.
|
|
1621
|
+
- **Limits.** Pieces are whole cubes for both the collider and the picture (slabs and stairs too), drawn in flat
|
|
1622
|
+
colour without the world's textures or light; the search runs on this thread; see `docs/limits.md`.
|
|
1623
|
+
|
|
1624
|
+
## Granular piles from voxel cells
|
|
1625
|
+
|
|
1626
|
+
Use `@margoengine/voxel/granular-mpm` to move loose full cubes into the native
|
|
1627
|
+
material point solver for continuous settling, shear and pile flow. The selected
|
|
1628
|
+
cells supply equal-volume midpoint samples in a shared solver, so adjacent cells
|
|
1629
|
+
can interact. Unselected voxels and packed liquid states keep their original values.
|
|
1630
|
+
|
|
1631
|
+
```ts
|
|
1632
|
+
import { GranularMpmSolver } from '@margoengine/physics/granular-mpm';
|
|
1633
|
+
import { PhysicsWorld } from '@margoengine/physics/world';
|
|
1634
|
+
import { BlockTypes, VoxelWorld } from '@margoengine/voxel';
|
|
1635
|
+
import { transferVoxelGranular } from '@margoengine/voxel/granular-mpm';
|
|
1636
|
+
|
|
1637
|
+
const blocks = new BlockTypes();
|
|
1638
|
+
const sand = blocks.define('sand');
|
|
1639
|
+
const voxels = new VoxelWorld({ blocks });
|
|
1640
|
+
voxels.setBlock(0, 2, 0, sand);
|
|
1641
|
+
voxels.setBlock(0, 3, 0, sand);
|
|
1642
|
+
const physics = new PhysicsWorld({ rate: { num: 60, den: 1 } });
|
|
1643
|
+
const grains = await GranularMpmSolver.load();
|
|
1644
|
+
transferVoxelGranular(voxels, physics, grains, {
|
|
1645
|
+
cells: [{ position: [0, 2, 0], block: sand }, { position: [0, 3, 0], block: sand }],
|
|
1646
|
+
metresPerVoxel: 0.25,
|
|
1647
|
+
params: { floor: 0, speedMargin: 5 },
|
|
1648
|
+
});
|
|
1649
|
+
physics.advance(12);
|
|
1650
|
+
console.log(voxels.getBlock(0, 2, 0), grains.sample(0).mass); // 0, 3.125 kg
|
|
1651
|
+
```
|
|
1652
|
+
|
|
1653
|
+
Supply a fresh, loaded solver and call at its step boundary. Each cell includes
|
|
1654
|
+
its expected block ID and can set a material table index (default 0). Voxel side
|
|
1655
|
+
length defaults to 1 m, samples per axis to 2, and solver spacing to the sample
|
|
1656
|
+
spacing. `voxelOrigin` and the solver `cell` both default to `[0, 0, 0]`. Use
|
|
1657
|
+
`voxelOrigin` to anchor voxel coordinates to the chosen floating-origin cell.
|
|
1658
|
+
Choose the expected travel speed for the drop through `params.speedMargin`.
|
|
1659
|
+
|
|
1660
|
+
Existing voxel ticks remain available for distant cells. Remove each selected
|
|
1661
|
+
cell once at setup. The complete selection leaves the voxel world only after
|
|
1662
|
+
the solver accepts the points. Change observers run after the transfer commits.
|
|
1663
|
+
Save voxel and physics states together when a checkpoint crosses the handoff.
|
|
1664
|
+
|
|
1665
|
+
## Preview tier contract
|
|
1666
|
+
|
|
1667
|
+
GPU-only attachments refuse the small WebGL2 preview during setup with `MargoError` code `unsupported` and a help link. Native WebGPU and the full WebGL2 compatibility layer expose the WebGPU-shaped device these passes need. Use [automatic escalation](../webgl2-compat/README.md#automatic-escalation) with awaited setup to load the full layer when required. Existing real preview routes remain available.
|
|
1668
|
+
|
|
1669
|
+
## Film time
|
|
1670
|
+
|
|
1671
|
+
`VoxelRenderer.advanceTime(delta)` moves the renderer's clock (`renderer.time`: water waves, voxel motion) in the frame update; before 2026-11-16 the prepare pass moved it. `seek` from `@margoengine/cutscene/seek` replays it.
|