Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions 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. 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 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.

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

Expand Down Expand Up @@ -187,7 +187,7 @@ NoiseSettings hills {

`Interpolated(terrain, 4, 8)` works the formula out once per 4×8×4 cell and blends between, as vanilla does. It is much faster and smooths out single-block noise. The preview of the `NoiseSettings` shows the finished blocks, with water and the surface rule applied.

To see the cells, zoom in on a density preview and turn on **Per block** and **Grid**. Per block samples each block at its own position, as the game does, so each block is one flat square and hovering shows the game's value there. Grid draws block lines when zoomed in, then chunk lines (16-block sections up a side view) and region lines further out.
To see the cells, zoom in on a density preview and turn on **Per block** and **Grid**. Per block samples each block at its own position, as the game does, so each block is one flat square and hovering shows the game's value there. Grid draws block lines when zoomed in, then chunk lines (16-block sections up a side view) and region lines further out. **Rulers** (on by default) label the coordinates along the left and bottom edges, spaced to suit the zoom, and show a scale bar a power of two blocks long, so you can tell how far out you are.

Give each step a name, as the samples here do. A named `DensityFunction` can be previewed on its own, which is how you find the step that went wrong, and its doc comment says what its numbers mean.

Expand Down
72 changes: 69 additions & 3 deletions packages/preview/src/preview/Preview.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import { climateParams, gapLayer, missing, nearest, nearestOf, type BiomeLayer, type NearEntry } from './climate';
import { colorize, cssGradient, formatValue, paletteOf, palettes, position, rangeFor, solidPalette, type PaletteId, type Range } from './colormaps';
import VolumeView from './VolumeView.svelte';
import { scaleBar, ticks } from './rulers';

interface Props {
output: OutputFile[];
Expand Down Expand Up @@ -160,6 +161,12 @@
let grid = $state(storedFlag('mms.preview.grid', false));
/** Density sampled at whole block positions, the values the game computes there (see PreviewView.blocks). */
let blockValues = $state(storedFlag('mms.preview.blocks', false));
/** Coordinates along the left and bottom edges of the 2D views, and a scale bar. */
let rulers = $state(storedFlag('mms.preview.rulers', true));
function setRulers(on: boolean) {
rulers = on;
storeFlag('mms.preview.rulers', on);
}
function setGrid(on: boolean) {
grid = on;
storeFlag('mms.preview.grid', on);
Expand Down Expand Up @@ -803,6 +810,35 @@
return flat && !topBlocks ? `x ${p.x}, z ${p.z}` : `x ${p.x}, y ${p.y}, z ${p.z}`;
}
const axes = $derived(screenAxes(view.facing));
/**
* The rulers along the bottom and left edges, from the camera as it is
* now (the image follows it at once too), and the scale bar under them.
*/
const rulerMarks = $derived.by(() => {
if (!rulers || !info || !last || mode === 'iso' || mode === 'volume' || !boxSize.w || !boxSize.h) return null;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// After a turn or a switch to Top, the old image shows another slice until the new one comes: no rulers over it.
if (!imageMap) return null;
const { w: W, h: H } = boxSize;
const f = frameOf(boxSize);
const [cu, cv] = planeOf(view);
// Blocks per CSS pixel across and down.
const perX = (view.scale * f.w) / W;
const perY = (view.scale * f.h) / H;
const a = axes;
// u runs along the screen's right: it is x or z, or minus one of them.
const hSign = a.rx || a.rz;
const hName = a.rx ? 'x' : 'z';
const hOrigin = hSign * (cu - (f.w / 2) * view.scale);
// Down the screen is y going down (a side view), or x or z (top-down).
const vSign = flat ? a.dx || a.dz : -1;
const vName = flat ? (a.dx ? 'x' : 'z') : 'y';
const vOrigin = flat ? vSign * (cv - (f.h / 2) * view.scale) : cv + (f.h / 2) * view.scale;
return {
h: { name: hName, ticks: ticks(hOrigin, hSign * perX, W, 64) },
v: { name: vName, ticks: ticks(vOrigin, vSign * perY, H, 48) },
bar: scaleBar(perX)
};
});
function coordTitle(axis: 'x' | 'y' | 'z'): string {
if (axis === 'y') {
if (topBlocks) return 'The height the camera looks down from: blocks above it are cut away';
Expand Down Expand Up @@ -1244,6 +1280,12 @@
aria-pressed={grid}
onclick={() => setGrid(!grid)}>Grid</button
>
<button
class="rounded border border-line px-1.5 py-0.5 {rulers ? 'bg-accent text-white' : 'hover:bg-hover'}"
title="Coordinates along the edges, and a scale bar"
aria-pressed={rulers}
onclick={() => setRulers(!rulers)}>Rulers</button
>
{#if mode === 'density'}
<button
class="rounded border border-line px-1.5 py-0.5 {blockValues ? 'bg-accent text-white' : 'hover:bg-hover'}"
Expand Down Expand Up @@ -1313,20 +1355,44 @@
onpointerleave={() => (hover = null)}
onwheel={wheel}
></div>
{#if rulerMarks}
{@const r = rulerMarks}
<!-- Coordinates of the block edges along the bottom and left, and a scale bar above the bottom one. -->
<div class="pointer-events-none absolute inset-x-0 bottom-0 h-4 bg-black/45 font-mono text-[10px] leading-4 text-white" aria-label="{r.h.name} ruler" data-ruler={r.h.name}>
{#each r.h.ticks as t (t.value)}
<span class="absolute bottom-0 h-1.5 w-px bg-white/80" style:left="{t.at}px"></span>
{#if t.at > 16 && t.at < boxSize.w - 48}<span class="absolute top-0 pl-0.5" style:left="{t.at}px">{t.value}</span>{/if}
{/each}
<span class="absolute right-1 top-0 font-semibold">{r.h.name}</span>
</div>
<div class="pointer-events-none absolute top-0 bottom-4 left-0 w-4 bg-black/45 font-mono text-[10px] text-white" aria-label="{r.v.name} ruler" data-ruler={r.v.name}>
{#each r.v.ticks as t (t.value)}
<span class="absolute left-0 h-px w-1.5 bg-white/80" style:top="{t.at}px"></span>
{#if t.at > 48 && t.at < boxSize.h - 16}<span class="absolute left-0 w-4 -translate-y-full rotate-180 pb-0.5 text-center leading-4 [writing-mode:vertical-rl]" style:top="{t.at}px">{t.value}</span>{/if}
{/each}
<span class="absolute top-1 left-0 w-4 text-center font-semibold leading-4">{r.v.name}</span>
</div>
{#if r.bar}
<div class="pointer-events-none absolute bottom-6 left-7 flex flex-col gap-0.5 font-mono text-[10px] text-white [text-shadow:0_0_2px_black]" aria-label="Scale bar" data-scale={r.bar.blocks}>
<span>{r.bar.label}</span>
<span class="h-1.5 border-x-2 border-b-2 border-white shadow-[0_1px_0_black]" style:width="{r.bar.px}px"></span>
</div>
{/if}
{/if}
{#if info && error}
<div class="absolute inset-x-3 top-3 rounded border border-red-300 bg-red-50 px-3 py-2 text-xs text-red-800 dark:border-red-800 dark:bg-red-950 dark:text-red-200">
Preview failed: {error}
</div>
{/if}
{#if info && (readout || lockValue || busy)}
<div class="pointer-events-none absolute bottom-2 left-2 flex flex-col gap-0.5 rounded bg-black/60 px-2 py-1 font-mono text-[11px] text-white">
<div class="pointer-events-none absolute flex flex-col gap-0.5 rounded bg-black/60 px-2 py-1 font-mono text-[11px] text-white {rulerMarks ? 'bottom-12 left-7' : 'bottom-2 left-2'}">
{#if readout && !pinned}<span>{readout}</span>{/if}
{#if lockValue}<span class="text-red-300">● {lockValue}</span>{/if}
{#if busy && (!last || mode !== 'density' || slow)}<span>Rendering…</span>{/if}
</div>
{/if}
{#if info && last && mode !== 'iso'}
<div class="pointer-events-none absolute top-2 left-2 rounded bg-black/60 px-2 py-1 font-mono text-[11px] text-white" aria-label="Camera facing">
<div class="pointer-events-none absolute top-2 rounded bg-black/60 px-2 py-1 font-mono text-[11px] text-white {rulerMarks ? 'left-7' : 'left-2'}" aria-label="Camera facing">
{#if flat && canDown}Looking down, top is {compass(-axes.dx, -axes.dz)} ·{:else}Facing {view.facing} ·{/if}
← {compass(-axes.rx, -axes.rz)} {compass(axes.rx, axes.rz)} →
{#if gridShown.length}· grid: {gridShown.map((g) => g.name).join(', ')}{/if}
Expand Down Expand Up @@ -1368,7 +1434,7 @@
</div>
{/if}
{#if info && last}
<div class="pointer-events-none absolute right-2 bottom-2 flex flex-col items-end gap-1">
<div class="pointer-events-none absolute right-2 flex flex-col items-end gap-1 {rulerMarks ? 'bottom-6' : 'bottom-2'}">
{#if palette && valueRange && palette.id !== 'solid'}
{@const r = valueRange}
{@const stat = layerValues ?? last}
Expand Down
21 changes: 21 additions & 0 deletions packages/preview/src/preview/VolumeView.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,9 @@
gl.lookAt(nx, nz);
}

/** The height ruler up the box's left edge, redrawn with every frame. */
let ruler = $state.raw<{ y: number; px: number; py: number }[]>([]);

onMount(() => {
try {
gl = new VolumeRenderer(canvas);
Expand All @@ -221,6 +224,10 @@
pump();
};
gl.ranged = ranged;
gl.drawn = () => {
const next = gl?.heightRuler() ?? [];
if (next.length !== ruler.length || next.some((t, i) => t.y !== ruler[i].y || Math.abs(t.px - ruler[i].px) > 0.5 || Math.abs(t.py - ruler[i].py) > 0.5)) ruler = next;
};
gl.moved = (nx, nz) => {
at = { x: Math.round(nx), z: Math.round(nz) };
onmove?.(nx, nz);
Expand Down Expand Up @@ -268,6 +275,20 @@
onblur={() => held.clear()}
>
<canvas bind:this={canvas} class="absolute inset-0 h-full w-full touch-none" oncontextmenu={(e) => e.preventDefault()}></canvas>
{#if ruler.length}
<!-- Heights up the box's left edge: a tick to its left and the y beside it. -->
<div class="pointer-events-none absolute inset-0 overflow-hidden font-mono text-[10px] text-white" aria-label="Height ruler" data-height-ruler={ruler.map((t) => t.y).join(' ')}>
{#each ruler as t, i (t.y)}
<span class="absolute h-px w-1.5 -translate-x-full -translate-y-1/2 bg-white shadow-[0_0_0_1px_rgba(0,0,0,0.5)]" style:left="{t.px}px" style:top="{t.py}px"></span>
<!-- Beside the tick, on whichever side of the edge has room. -->
<span
class="absolute -translate-y-1/2 rounded bg-black/55 px-1 leading-4 whitespace-nowrap {t.px < 56 ? 'ml-1' : '-translate-x-full -ml-2.5'}"
style:left="{t.px}px"
style:top="{t.py}px">{i === ruler.length - 1 ? `y ${t.y}` : t.y}</span
>
{/each}
</div>
{/if}
{#if failure}
<div class="absolute inset-x-3 top-3 rounded border border-red-300 bg-red-50 px-3 py-2 text-xs text-red-800 dark:border-red-800 dark:bg-red-950 dark:text-red-200">
The 3D view can't start: {failure}.
Expand Down
59 changes: 59 additions & 0 deletions packages/preview/src/preview/rulers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Rulers and a scale bar for the previews: steps that read well at any
// zoom, and where their ticks land.

/** The smallest of 1, 2 and 5 times a power of ten (whole blocks, at least 1) that is at least `min`. */
export function niceStep(min: number): number {
if (!(min > 1)) return 1;
const p = 10 ** Math.floor(Math.log10(min));
for (const m of [1, 2, 5, 10]) if (m * p >= min) return m * p;
return 10 * p;
}

/**
* The multiples of step between lo and hi (either way round). Counted, not
* stepped, and capped, so a huge coordinate can't loop forever.
*/
export function multiples(lo: number, hi: number, step: number): number[] {
const a = Math.min(lo, hi);
const b = Math.max(lo, hi);
const first = Math.ceil(a / step);
const n = Math.max(0, Math.min(200, Math.floor(b / step) - first + 1));
// Far out, adding one no longer changes a float: keep only values that move on.
const out: number[] = [];
for (let i = 0; i < n; i++) {
const v = (first + i) * step;
if (!out.length || v > out[out.length - 1]) out.push(v);
}
return out;
}

/** A tick on a ruler: its world coordinate and its offset along the edge in CSS pixels. */
export interface Tick {
value: number;
at: number;
}

/**
* The ticks along an edge `length` CSS pixels long, where the coordinate at
* offset p is origin + per·p (per is negative when it counts down the edge).
* Ticks are at least `gap` pixels apart.
*/
export function ticks(origin: number, per: number, length: number, gap: number): Tick[] {
if (!per || !Number.isFinite(per) || !Number.isFinite(origin) || length <= 0) return [];
const step = niceStep(Math.abs(per) * gap);
return multiples(origin, origin + per * length, step).map((value) => ({ value, at: (value - origin) / per }));
}

/**
* A scale bar for a view at `blocksPerPixel`: a power of two blocks (so
* it lands on chunks and regions) whose bar is about 60 to 120 pixels long.
*/
export function scaleBar(blocksPerPixel: number, target = 80): { blocks: number; px: number; label: string } | null {
if (!(blocksPerPixel > 0) || !Number.isFinite(blocksPerPixel)) return null;
const blocks = 2 ** Math.max(0, Math.round(Math.log2(target * blocksPerPixel)));
const px = blocks / blocksPerPixel;
let label = `${blocks} block${blocks === 1 ? '' : 's'}`;
if (blocks >= 512) label += ` · ${blocks / 512} region${blocks === 512 ? '' : 's'}`;
else if (blocks >= 16) label += ` · ${blocks / 16} chunk${blocks === 16 ? '' : 's'}`;
return { blocks, px, label };
}
41 changes: 41 additions & 0 deletions packages/preview/src/preview/volume.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
// under the ground (a cave) from the open air above it.

import * as THREE from 'three';
import { multiples, niceStep } from './rulers';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { VOLUME_TILE, type VolumeTile } from './protocol';

Expand Down Expand Up @@ -493,6 +494,8 @@ export class VolumeRenderer {
private lastWant = '';
/** Called when the camera's target moves, with its world x and z. */
moved: (x: number, z: number) => void = () => {};
/** Called after each frame is drawn, for overlays that follow the camera. */
drawn: () => void = () => {};
/** Called when a tile arrives, with the range of density in the window. */
ranged: (r: ValueRange) => void = () => {};

Expand Down Expand Up @@ -971,5 +974,43 @@ export class VolumeRenderer {
}
(this.uniforms.camPos.value as THREE.Vector3).copy(this.camera.position);
this.renderer.render(this.scene, this.camera);
this.drawn();
}

/**
* A height ruler up one of the box's upright edges, in CSS pixels of the
* canvas: the edge furthest left on screen, so it runs up the box's
* outline rather than across the inside, with ticks at least `gap`
* pixels apart. Empty when no edge is wholly in front of the camera.
*/
heightRuler(gap = 28): { y: number; px: number; py: number }[] {
const min = this.uniforms.boxMin.value as THREE.Vector3;
const max = this.uniforms.boxMax.value as THREE.Vector3;
if (!(max.y > min.y)) return [];
const w = this.canvas.clientWidth;
const h = this.canvas.clientHeight;
const p = new THREE.Vector3();
const toScreen = (x: number, y: number, z: number): [number, number] | null => {
p.set(x, y, z).project(this.camera);
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;
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;
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 || 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] });
}
return out;
}
}
Loading
Loading