Skip to content
2 changes: 1 addition & 1 deletion engine/mcp/docs/guides/terrain.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ In JSON a formula is a deep tree of `add` and `mul` objects. In MMS it is arithm

Put the cursor on a `Noise`, a `DensityFunction` or a `NoiseSettings` and open the **Preview** tab of the web editor (in VS Code, click **Preview** above it). It draws the function as a slice of the world: the raw density, the blocks it makes, or a 3D view. The picture redraws on every edit, so changing a number and watching is the normal way to work.

**3D density** shows a density function or a noise settings' final density in 3D, so you can see caves inside the ground. **Caves** draws air under solid ground coloured by height, **Shell** draws every surface see-through, and **Solid** draws the ground opaque so you can cut into it from the top, east or south. Drag to orbit, and right-drag or use WASD to travel (hold Shift to go faster). New ground is sampled as it comes into view. Noise settings are sampled at their cell corners and blended as the game blends them, while a plain density function is sampled at most every 2 blocks across and 4 up. Ground far from the camera is sampled more sparsely, always on whole blocks: the view fills in coarse first and sharpens as you zoom in. A height ruler runs up the box's left edge. It draws whole blocks by default, each solid where the density at that block is over the threshold; switch to **Smooth** for a blended surface. The threshold starts at 0, or for a density function that never crosses 0 in view, at its median, and **Auto** picks it again. Aquifers, carvers and surface rules aren't shown here, so use **Blocks** for those.
**3D density** shows a density function or a noise settings' final density in 3D, so you can see caves inside the ground. **Caves** draws air under solid ground coloured by height, **Shell** draws every surface see-through, and **Solid** draws the ground opaque so you can cut into it from the east or south. **Bottom** and **Top** set the heights shown: a density function is sampled over them (anywhere from y -2032 to 2031, more sparsely up past 1024 blocks), while noise settings keep their own height and are cut to them. Colour runs from purple at the bottom to blue at the top. Drag to orbit, and right-drag or use WASD to travel (hold Shift to go faster). New ground is sampled as it comes into view. Noise settings are sampled at their cell corners and blended as the game blends them, while a plain density function is sampled at most every 2 blocks across and 4 up. Ground far from the camera is sampled more sparsely, always on whole blocks: the view fills in coarse first and sharpens as you zoom in. A height ruler runs up the box's left edge. It draws whole blocks by default, each solid where the density at that block is over the threshold; switch to **Smooth** for a blended surface. The threshold starts at 0, or for a density function that never crosses 0 in view, at its median, and **Auto** picks it again. Aquifers, carvers and surface rules aren't shown here, so use **Blocks** for those.

Every sample on this page is a file of its own. Paste one into a new project to see it.

Expand Down
30 changes: 15 additions & 15 deletions engine/mcp/preview/agent.mjs

Large diffs are not rendered by default.

82 changes: 78 additions & 4 deletions packages/preview/src/preview/VolumeView.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
// WASD to travel; the window of tiles follows the camera.

import { onMount, untrack } from 'svelte';
import type { PreviewKind, VolumeTile, VolumeTileRequest } from './protocol';
import { yGrid, type PreviewKind, type VolumeTile, type VolumeTileRequest } from './protocol';
import Slider from './Slider.svelte';
import { defaultSettings, VolumeRenderer, type TileWant, type ValueRange, type VolumeLook, type VolumePose, type VolumeSettings } from './volume';
import { record, restore, useMemory } from '../memory';
Expand Down Expand Up @@ -78,6 +78,14 @@
/** Tiles the window needs, in the order to ask for them. */
let queue: TileWant[] = [];
const failed = new Set<string>();
/**
* The heights this session samples a density function over: a change
* to Bottom or Top starts a new session once it settles, so one
* session's tiles all share a grid.
*/
let sampled = { bottomY: settings.bottomY, topY: settings.topY };
/** The heights the tiles in view cover, once one arrives. */
let gridY = $state.raw<{ min: number; max: number } | null>(null);

function pump() {
const busy = new Set(inFlight.values());
Expand All @@ -88,7 +96,7 @@
const job = nextJob++;
inFlight.set(job, key);
busy.add(key);
send({ type: 'tile', session, job, kind, id, seed, tx, tz, lod });
send({ type: 'tile', session, job, kind, id, seed, tx, tz, lod, ...sampled });
}
const m = gl?.missing();
loading = m ? m.missing : 0;
Expand All @@ -105,6 +113,8 @@
} else {
// Keep the reason up while some tile is still failing.
if (failed.size === 0) tileError = '';
const max = t.minY + (t.ny - 1) * t.sy;
if (gridY?.min !== t.minY || gridY.max !== max) gridY = { min: t.minY, max };
gl?.add(t);
}
pump();
Expand All @@ -117,6 +127,8 @@

function fresh() {
session = ++sessions;
sampled = { bottomY: settings.bottomY, topY: settings.topY };
gridY = null;
inFlight.clear();
failed.clear();
queue = [];
Expand Down Expand Up @@ -182,6 +194,42 @@
settings[k] = v;
}

// ---- heights ----
/** The game's limits for a dimension's height. */
const WORLD_BOTTOM = -2032;
const WORLD_TOP = 2031;
/** Bottom and Top can go anywhere in the world for a density function; noise settings have their own height. */
const yLimits = $derived(kind === 'noise_settings' ? (gridY ?? { min: -64, max: 320 }) : { min: WORLD_BOTTOM, max: WORLD_TOP });
const yReset = $derived(kind === 'noise_settings' && gridY ? { bottomY: gridY.min, topY: gridY.max } : { bottomY: defaultSettings.bottomY, topY: defaultSettings.topY });
/** The heights drawn, inside what's sampled. */
const shownY = $derived.by(() => {
const b = Math.max(yLimits.min, Math.min(yLimits.max - 1, settings.bottomY));
return { bottom: b, top: Math.max(b + 1, Math.min(yLimits.max, settings.topY)) };
});
/** Blocks between samples up, as the worker picks them for a density function's range. */
const ySpacing = $derived(yGrid(settings.bottomY, settings.topY).sy);
/** Sets Bottom or Top, moving the other along to keep at least a block between them. */
function setY(k: 'bottomY' | 'topY', v: number) {
v = Math.round(v);
if (k === 'bottomY') {
settings.bottomY = v;
if (settings.topY <= v) settings.topY = v + 1;
} else {
settings.topY = v;
if (settings.bottomY >= v) settings.bottomY = v - 1;
}
}
// A density function samples the new heights once a drag has settled.
$effect(() => {
const want = { bottomY: settings.bottomY, topY: settings.topY };
if (kind === 'noise_settings') return;
if (want.bottomY === sampled.bottomY && want.topY === sampled.topY) return;
const t = setTimeout(() => {
if (gl) fresh();
}, 350);
return () => clearTimeout(t);
});

function colors() {
if (!gl || !host) return;
const style = getComputedStyle(host);
Expand Down Expand Up @@ -389,7 +437,31 @@
{/if}
{/if}
</div>
<Slider label="Cut from top" prefix="y" value={settings.cutY} min={-64} max={320} step={1} reset={defaultSettings.cutY} onchange={(v) => set('cutY', v)} />
<Slider
label="Top"
prefix="y"
value={shownY.top}
min={yLimits.min + 1}
max={yLimits.max}
step={1}
reset={yReset.topY}
title={kind === 'noise_settings' ? 'The highest y drawn, within the noise settings\' height' : 'The highest y sampled and drawn'}
onchange={(v) => setY('topY', v)}
/>
<Slider
label="Bottom"
prefix="y"
value={shownY.bottom}
min={yLimits.min}
max={yLimits.max - 1}
step={1}
reset={yReset.bottomY}
title={kind === 'noise_settings' ? 'The lowest y drawn, within the noise settings\' height' : 'The lowest y sampled and drawn'}
onchange={(v) => setY('bottomY', v)}
/>
{#if kind !== 'noise_settings' && ySpacing > 4}
<p class="-mt-2 text-[11px] text-muted" data-y-spacing={ySpacing}>Over this many heights, density is sampled every {ySpacing} blocks up.</p>
{/if}
<Slider label="Cut from east" suffix="%" value={settings.cutX * 100} min={1} max={100} step={1} reset={100} onchange={(v) => set('cutX', v / 100)} />
<Slider label="Cut from south" suffix="%" value={settings.cutZ * 100} min={1} max={100} step={1} reset={100} onchange={(v) => set('cutZ', v / 100)} />
{#if settings.look === 'caves'}
Expand All @@ -399,7 +471,9 @@
<div class="flex flex-col gap-1">
<span>Colour is height</span>
<div class="h-2 rounded-sm" style="background: linear-gradient(90deg, rgb(115 31 140), rgb(219 69 56), rgb(237 173 51), rgb(64 168 115), rgb(89 148 235))"></div>
<div class="flex justify-between font-mono text-[10px] text-muted"><span>-64</span><span>2</span><span>68</span><span>134</span><span>200</span></div>
<div class="flex justify-between font-mono text-[10px] text-muted" data-colour-heights>
{#each [0, 1, 2, 3, 4] as i (i)}<span>{Math.round(shownY.bottom + ((shownY.top - shownY.bottom) * i) / 4)}</span>{/each}
</div>
</div>
<form
class="flex items-center gap-1"
Expand Down
44 changes: 35 additions & 9 deletions packages/preview/src/preview/preview.worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ import {
type PreviewResponse,
type PreviewView,
type VolumeTile,
type VolumeTileRequest
type VolumeTileRequest,
yGrid
} from './protocol';

// Renders previews with Deepslate. User files are registered under their
Expand Down Expand Up @@ -681,12 +682,14 @@ function addHelpers(ports: MessagePort[]) {
helpers.push(helper);
}
dispatch();
sendTiles();
}

function finish(helper: (typeof helpers)[number], reply: HelperReply) {
if (reply.type === 'tile') {
helper.tiles--;
postTile(reply);
sendTiles();
return;
}
const job = helper.job;
Expand Down Expand Up @@ -842,7 +845,7 @@ interface Volume {
let volume: Volume | null = null;

async function volumeOf(req: VolumeTileRequest): Promise<Volume> {
const key = [version, req.seed, req.kind, req.id].join('|');
const key = [version, req.seed, req.kind, req.id, ...(req.kind === 'noise_settings' ? [] : [req.bottomY, req.topY])].join('|');
if (volume?.key === key) return volume;
const seed = seedOf(req.seed);
// The cell size comes from the interpolated nodes taken out (4 × 8 in vanilla).
Expand All @@ -868,8 +871,10 @@ async function volumeOf(req: VolumeTileRequest): Promise<Volume> {
const df = new DensityFunction.HolderHolder(Holder.reference(WorldgenRegistries.DENSITY_FUNCTION, Identifier.parse(req.id)));
const fn = fasten(df.mapAll(rs.createVisitor(false)));
fn.compute(DensityFunction.context(0, 0, 0));
// The overworld's height, two blocks across and four up.
return { key, fn, sx: 2, sy: 4, minY: -64, ny: 384 / 4 + 1 };
// The asked-for heights, two blocks across and four up; a tall range
// is sampled more sparsely up, so a tile stays at most 256 layers.
const { sy, minY, layers } = yGrid(req.bottomY, req.topY);
return { key, fn, sx: 2, sy, minY, ny: layers + 1 };
});
return volume;
}
Expand Down Expand Up @@ -906,16 +911,37 @@ function postTile(tile: VolumeTile) {
(self as unknown as Worker).postMessage(tile, 'values' in tile ? [tile.values.buffer] : []);
}

/** Hands a tile to the least busy helper, or samples it here when there are none. */
/**
* Tiles waiting for a helper. Each helper holds one tile at a time, so when
* the view starts a new session (its Y range changed, say) the old
* session's waiting tiles are dropped here instead of keeping every core
* busy with samples nobody will draw.
*/
let tileQueue: VolumeTileRequest[] = [];
let tileSession = -Infinity;

/** Hands a tile to an idle helper, or samples it here when there are none. */
async function askTile(req: VolumeTileRequest) {
if (req.session < tileSession) return;
if (req.session > tileSession) {
tileSession = req.session;
tileQueue = [];
}
if (helpers.length === 0) {
postTile(await sampleTile(req));
return;
}
let best = helpers[0];
for (const h of helpers) if (h.tiles + (h.job ? 1 : 0) < best.tiles + (best.job ? 1 : 0)) best = h;
best.tiles++;
best.port.postMessage(req satisfies HelperMessage);
tileQueue.push(req);
sendTiles();
}

function sendTiles() {
for (const h of helpers) {
if (!tileQueue.length) return;
if (h.tiles > 0) continue;
h.tiles++;
h.port.postMessage(tileQueue.shift()! satisfies HelperMessage);
}
}

/**
Expand Down
16 changes: 16 additions & 0 deletions packages/preview/src/preview/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,19 @@ export const VOLUME_TILE = 64;
* costs fewer samples; spacings are whole blocks, sampled at block
* positions.
*/
/**
* The heights a density function's tiles are sampled at for Bottom..Top:
* every sy blocks from minY, in a multiple of 16 layers (so coarser
* levels keep the top layer), sy doubling from 4 until that's at most 256.
*/
export function yGrid(bottomY: number, topY: number): { sy: number; minY: number; layers: number } {
for (let sy = 4; ; sy *= 2) {
const minY = Math.floor(bottomY / sy) * sy;
const layers = Math.max(16, Math.ceil((topY - minY) / sy / 16) * 16);
if (layers <= 256 || sy >= 1 << 12) return { sy, minY, layers };
}
}

export interface VolumeTileRequest {
type: 'tile';
session: number;
Expand All @@ -204,6 +217,9 @@ export interface VolumeTileRequest {
tx: number;
tz: number;
lod: number;
/** The y range to sample a density function over (noise settings use their own height). */
bottomY: number;
topY: number;
}

/**
Expand Down
52 changes: 39 additions & 13 deletions packages/preview/src/preview/volume.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,13 @@ export interface ValueRange {
export interface VolumeSettings {
look: VolumeLook;
threshold: number;
/** The highest y drawn. */
cutY: number;
/**
* The lowest and highest y drawn. A density function is sampled over
* this range; noise settings are sampled over their own height and cut
* to it.
*/
bottomY: number;
topY: number;
/** How much of the window to keep along x and z, 0 to 1, cut from the east and south. */
cutX: number;
cutZ: number;
Expand All @@ -74,7 +79,7 @@ export interface VolumeSettings {
blocks: boolean;
}

export const defaultSettings: VolumeSettings = { look: 'caves', threshold: 0, cutY: 320, cutX: 1, cutZ: 1, haze: 0.004, caveOpacity: 0.55, blocks: true };
export const defaultSettings: VolumeSettings = { look: 'caves', threshold: 0, bottomY: -64, topY: 320, cutX: 1, cutZ: 1, haze: 0.004, caveOpacity: 0.55, blocks: true };

const mod = (a: number, n: number) => ((a % n) + n) % n;

Expand Down Expand Up @@ -287,7 +292,8 @@ const fragmentShader = /* glsl */ `
}
// Height: deep magenta, red, amber, green, sky blue, from the bottom of the world to y 200.
vec3 ramp(float y) {
float t = clamp((y - minY) / (200.0 - minY), 0.0, 1.0) * 4.0;
// From the bottom of the box (purple) to its top (blue).
float t = clamp((y - boxMin.y) / max(1.0, boxMax.y - boxMin.y), 0.0, 1.0) * 4.0;
vec3 c0 = vec3(0.45, 0.12, 0.55), c1 = vec3(0.86, 0.27, 0.22), c2 = vec3(0.93, 0.68, 0.20), c3 = vec3(0.25, 0.66, 0.45), c4 = vec3(0.35, 0.58, 0.92);
if (t < 1.0) return mix(c0, c1, t);
if (t < 2.0) return mix(c1, c2, t - 1.0);
Expand Down Expand Up @@ -331,7 +337,8 @@ const fragmentShader = /* glsl */ `
return vec4(ramp(cell.y + 0.5) * 0.78, 1.0);
}
float maxJump = 2.0 * min(sx, sy) - 1.0;
for (int i = 0; i < 4000; i++) {
// Enough block crossings for a ray across the tallest box (4063 up, 320 by 320 across).
for (int i = 0; i < 6000; i++) {
if (acc.a > 0.97) break;
if (ok) {
// Within s blocks along the ray, every block corner is within s + 1.74 blocks of this block's centre.
Expand Down Expand Up @@ -412,7 +419,8 @@ const fragmentShader = /* glsl */ `
outColor = vec4(ramp(p.y) * 0.78, 1.0);
return;
}
for (int i = 0; i < 3000; i++) {
// Enough half-block steps for a ray across the tallest box, where density stays near 0.
for (int i = 0; i < 9000; i++) {
float dt = ok ? clamp(0.9 * abs(d) / lipAt(p), minStep, maxStep) : sx;
if (ok && dt > minStep) dt = clamp(0.9 * abs(d) / lipAlong(p, rd, dt), minStep, dt);
float t1 = t + dt;
Expand Down Expand Up @@ -928,8 +936,14 @@ export class VolumeRenderer {
}
const { x, z } = this.target();
this.moved(x, z);
const tx = Math.floor(x / VOLUME_TILE);
const tz = Math.floor(z / VOLUME_TILE);
// Panning moves the camera within the box; the box only follows
// when the target comes within a tile of its edge, and then just
// far enough to keep it there.
const tx0 = Math.floor(x / VOLUME_TILE);
const tz0 = Math.floor(z / VOLUME_TILE);
const near = (c: number, t: number) => (Number.isFinite(c) ? Math.min(t + R - 1, Math.max(t - R + 1, c)) : t);
const tx = near(this.centre.tx, tx0);
const tz = near(this.centre.tz, tz0);
if (tx !== this.centre.tx || tz !== this.centre.tz) {
this.centre = { tx, tz };
for (let dz = -R; dz <= R; dz++) {
Expand All @@ -956,8 +970,9 @@ export class VolumeRenderer {
const span = (2 * R + 1) * VOLUME_TILE - (g?.sx ?? 4);
const minY = g?.minY ?? -64;
const maxY = g ? g.minY + (g.ny - 1) * g.sy : 320;
const top = Math.max(minY + 1, Math.min(maxY, s.cutY));
const min = new THREE.Vector3(x0, minY, z0);
const bottom = Math.max(minY, Math.min(maxY - 1, s.bottomY));
const top = Math.max(bottom + 1, Math.min(maxY, s.topY));
const min = new THREE.Vector3(x0, bottom, z0);
const max = new THREE.Vector3(x0 + Math.max(1, span * s.cutX), top, z0 + Math.max(1, span * s.cutZ));
(this.uniforms.boxMin.value as THREE.Vector3).copy(min);
(this.uniforms.boxMax.value as THREE.Vector3).copy(max);
Expand Down Expand Up @@ -1022,21 +1037,32 @@ export class VolumeRenderer {
if (p.z < -1 || p.z > 1) return null;
return [((p.x + 1) / 2) * w, ((1 - p.y) / 2) * h];
};
let best: { x: number; z: number; len: number; left: number } | null = null;
// An edge counts when it stands inside the view, with enough of it showing for a few ticks.
const onScreen = (b: [number, number], t: [number, number]) =>
Math.min(b[0], t[0]) >= 0 && Math.max(b[0], t[0]) <= w && Math.min(h, Math.max(b[1], t[1])) - Math.max(0, Math.min(b[1], t[1])) >= 3 * gap;
let best: { x: number; z: number; len: number; left: number; pin?: number } | null = null;
for (const x of [min.x, max.x])
for (const z of [min.z, max.z]) {
const b = toScreen(x, min.y, z);
const t = toScreen(x, max.y, z);
if (!b || !t) continue;
if (!b || !t || !onScreen(b, t)) continue;
const left = b[0] + t[0];
if (!best || left < best.left) best = { x, z, len: Math.hypot(t[0] - b[0], t[1] - b[1]), left };
}
if (!best) {
// Zoomed in past the box's edges: measure the column the camera
// looks at, and pin its ticks to the left edge of the view.
const { x, z } = this.controls.target;
const b = toScreen(x, min.y, z);
const t = toScreen(x, max.y, z);
if (b && t) best = { x, z, len: Math.abs(t[1] - b[1]), left: 0, pin: 12 };
}
if (!best || best.len < gap) return [];
const step = niceStep(((max.y - min.y) / best.len) * gap);
const out: { y: number; px: number; py: number }[] = [];
for (const y of multiples(min.y, max.y, step)) {
const at = toScreen(best.x, y, best.z);
if (at) out.push({ y, px: at[0], py: at[1] });
if (at) out.push({ y, px: best.pin ?? at[0], py: at[1] });
}
return out;
}
Expand Down
Loading
Loading