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

## See what you are doing

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.
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. In a side view of density, **Bottom** and **Top** limit the heights drawn (leave one blank for no limit). Everything else stays empty and doesn't count towards the colour range, and the view moves and zooms to fit the heights you set.

**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.

Expand Down
28 changes: 14 additions & 14 deletions engine/mcp/preview/agent.mjs

Large diffs are not rendered by default.

68 changes: 68 additions & 0 deletions packages/preview/src/preview/Preview.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,13 @@
const topBlocks = $derived(flat && canDown && mode === 'blocks');
/** The side view's y while top-down terrain looks down from the top of the world. */
let sideY: number | null = null;
/**
* The heights a side view of density draws, either end left open with
* null: the rest stays empty and out of the colour range.
*/
let yBounds = $state<{ bottom: number | null; top: number | null }>({ bottom: null, top: null });
/** Whether the Bottom and Top heights apply: density seen from the side. */
const boundsY = $derived(!!info && mode === 'density' && !flat && (info.kind === 'density_function' || info.kind === 'noise_settings'));

/** A switch remembered in this browser. */
function storedFlag(key: string, fallback: boolean): boolean {
Expand Down Expand Up @@ -544,6 +551,7 @@
request();
return;
}
yBounds = { bottom: null, top: null };
if (!sameKind) {
mode = modesOf[info.kind][0];
view = defaultView(info.kind, mode);
Expand Down Expand Up @@ -579,6 +587,7 @@
focus,
rangeMode,
customRange: $state.snapshot(customRange),
yBounds: $state.snapshot(yBounds),
seed
};
// Saved once the target effect has shown this target, so a new
Expand Down Expand Up @@ -606,6 +615,9 @@
focus = text(r.focus, '');
rangeMode = rangeModes.includes(r.rangeMode as RangeMode) ? (r.rangeMode as RangeMode) : 'auto';
customRange = restore({ lo: -1, hi: 1 }, r.customRange);
const b = record(r.yBounds);
const height = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
yBounds = { bottom: height(b?.bottom), top: height(b?.top) };
seed = text(r.seed, seed);
view.scale = Math.min(view.scale, maxScale());
lock = null;
Expand Down Expand Up @@ -676,6 +688,10 @@
setBusy(true);
if (mode === 'iso' || topBlocks) startHelpers();
const sent: PreviewView = { ...$state.snapshot(view), down: lookDown && canDown, blocks: mode === 'density' && blockValues };
if (boundsY) {
if (yBounds.bottom !== null) sent.bottomY = yBounds.bottom;
if (yBounds.top !== null) sent.topY = yBounds.top;
}
sentViews.set(seq + 1, { view: mode === 'iso' ? $state.snapshot(isoView) : sent, flat, resolution, mode });
worker.postMessage({
type: 'render',
Expand Down Expand Up @@ -923,6 +939,40 @@
draw();
}
/** Sets one camera coordinate from an input, ignoring what isn't a number yet. */
/**
* Sets Bottom or Top (blank leaves that end open), then frames the
* heights drawn: the camera moves to their middle and, with both ends
* set, zooms so they fill most of the view's height.
*/
function setBound(end: 'bottom' | 'top', value: string) {
const n = Number(value);
const v = value.trim() === '' || !Number.isFinite(n) ? null : Math.round(n);
const next = { ...yBounds, [end]: v };
// Keep at least one block between them, moving the other end.
if (next.bottom !== null && next.top !== null && next.top <= next.bottom) {
if (end === 'bottom') next.top = next.bottom + 1;
else next.bottom = next.top - 1;
}
yBounds = next;
frameBounds();
request();
}
function frameBounds() {
const { bottom, top } = yBounds;
if (bottom === null && top === null) return;
if (bottom !== null && top !== null) {
view.y = (bottom + top) / 2;
const h = frame().h;
view.scale = Math.min(maxScale(), Math.max(1 / 16, ((top - bottom) * 1.15) / h));
} else {
// One end: bring it a quarter of the way in from its edge of the view.
const half = (frame().h / 2) * view.scale;
if (bottom !== null) view.y = bottom + half / 2;
else view.y = top! - half / 2;
}
lock = null;
}

function setCoord(axis: 'x' | 'y' | 'z', value: string) {
const n = Number(value);
if (value.trim() === '' || !Number.isFinite(n)) return;
Expand Down Expand Up @@ -1338,6 +1388,23 @@
{/if}
</div>
{/if}
{#if boundsY}
<div class="flex items-center gap-1" role="group" aria-label="Heights" title="Draw only the heights from Bottom up to Top (blank: no limit), and fit the view to them">
{#each [['bottom', 'Bottom'], ['top', 'Top']] as const as [end, name] (end)}
<label class="flex items-center gap-1">
{name}
<input
type="number"
aria-label="{name} y"
placeholder="any"
class="w-16 rounded border border-line bg-panel px-1.5 py-0.5 text-ink"
value={yBounds[end] ?? ''}
onchange={(e) => setBound(end, e.currentTarget.value)}
/>
</label>
{/each}
</div>
{/if}
{#if mode !== 'iso' && mode !== 'volume'}
<div class="flex items-center gap-0.5" role="group" aria-label="Overlays">
<button
Expand Down Expand Up @@ -1388,6 +1455,7 @@
sideY = null;
fitTop(false);
lock = null;
if (boundsY) frameBounds();
}
request();
}}>Reset view</button
Expand Down
7 changes: 6 additions & 1 deletion packages/preview/src/preview/preview.worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { biomeColor, blockColor, CAVE, SKY, VOID, type Rgb } from './colors';
import { entryStride, fitness, type ClimateEntries } from './climate';
import { fasten, speedUp } from './fastDensity';
import {
outsideY,
screenAxes,
vanillaSummary,
VOLUME_TILE,
Expand Down Expand Up @@ -1666,6 +1667,10 @@ async function render(req: RenderRequest): Promise<Rendered> {
const compute = (x: number, y: number, z: number) => fn.compute(DensityFunction.context(x, y, z));
for (let py = 0; py < height; py++) {
const y = view.down ? view.y : plane.y(py);
if (outsideY(view, y)) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
values.fill(NaN, py * width, (py + 1) * width);
continue;
}
for (let px = 0; px < width; px++) {
await pace();
const [x, z] = view.down ? [plane.x(px, py), plane.z(px, py)] : plane.at(plane.along(px));
Expand Down Expand Up @@ -1696,7 +1701,7 @@ async function render(req: RenderRequest): Promise<Rendered> {
for (let px = 0; px < width; px++) {
const i = py * width + px;
let v = NaN;
if (y >= minY && y < maxY) {
if (y >= minY && y < maxY && !outsideY(view, y)) {
await pace();
const [x, z] = view.down ? [plane.x(px, py), plane.z(px, py)] : plane.at(plane.along(px));
v = at(px, py, x, y, z, compute);
Expand Down
17 changes: 17 additions & 0 deletions packages/preview/src/preview/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,23 @@ export interface PreviewView {
* sampled at its centre, between blocks. Only density views use it.
*/
blocks?: boolean;
/**
* A side view of density draws only the heights from bottomY up to
* topY (either may be left out); the rest is left empty, unsampled, and
* out of the colour range.
*/
bottomY?: number;
topY?: number;
}

/**
* Whether a side view's y falls outside the heights it draws (see
* PreviewView.bottomY). Per block, y is the block it falls in, as sampled,
* so the whole Top block is drawn.
*/
export function outsideY(view: PreviewView, y: number): boolean {
if (view.blocks) y = Math.floor(y);
return !view.down && ((view.bottomY !== undefined && y < view.bottomY) || (view.topY !== undefined && y > view.topY));
}

export interface PreviewOptions {
Expand Down
43 changes: 33 additions & 10 deletions packages/preview/src/preview/volume.ts
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,10 @@ export class VolumeRenderer {
private settings: VolumeSettings = { ...defaultSettings };
/** Whether the camera has been moved by hand; until then a resize refits it. */
private touched = false;
/** The heights the box was last drawn between, so a change to them can bring the camera along. */
private shownY: { bottom: number; top: number } | null = null;
/** Whether the camera came from a remembered pose, which first framing leaves alone. */
private restored = false;
private full: number;
private queued = false;
private sharpen: ReturnType<typeof setTimeout> | undefined;
Expand Down Expand Up @@ -594,10 +598,8 @@ export class VolumeRenderer {
/** Puts the camera over world (x, z), looking down at an angle from the south-east, far enough back to see the window. */
lookAt(x: number, z: number) {
this.origin = { x: Math.round(x), z: Math.round(z) };
const g = this.grid;
const minY = g?.minY ?? -64;
const maxY = g ? g.minY + (g.ny - 1) * g.sy : 320;
this.controls.target.set(x - this.origin.x, (minY + maxY) / 2, z - this.origin.z);
const y = this.shownY ? (this.shownY.bottom + this.shownY.top) / 2 : 128;
this.controls.target.set(x - this.origin.x, y, z - this.origin.z);
this.fit();
this.followTarget();
}
Expand All @@ -615,14 +617,15 @@ export class VolumeRenderer {
const t = this.controls.target.set(pose.x - this.origin.x, pose.y, pose.z - this.origin.z);
this.camera.position.set(t.x + pose.dx, t.y + pose.dy, t.z + pose.dz);
this.touched = true;
this.restored = true;
this.controls.update();
this.followTarget();
}

/** Backs the camera off along its current direction until the window fits. */
private fit() {
const g = this.grid;
const height = g ? (g.ny - 1) * g.sy : 384;
const height = this.shownY ? this.shownY.top - this.shownY.bottom : g ? (g.ny - 1) * g.sy : 384;
const width = (2 * R + 1) * VOLUME_TILE * Math.SQRT2; // seen corner on
const tan = Math.tan(THREE.MathUtils.degToRad(this.camera.fov / 2));
const dist = 1.1 * Math.max(height / (2 * tan), width / (2 * tan * this.camera.aspect));
Expand Down Expand Up @@ -853,11 +856,7 @@ export class VolumeRenderer {
u.ny.value = tile.ny;
u.cornersAcross.value = across;
this.box.visible = true;
if (!this.touched) {
// Centre on the world's height now that it's known.
this.controls.target.y = tile.minY + ((tile.ny - 1) * tile.sy) / 2;
this.fit();
}
// Placing the box frames the camera on the heights now that they're known.
this.placeBox();
}

Expand Down Expand Up @@ -972,6 +971,7 @@ export class VolumeRenderer {
const maxY = g ? g.minY + (g.ny - 1) * g.sy : 320;
const bottom = Math.max(minY, Math.min(maxY - 1, s.bottomY));
const top = Math.max(bottom + 1, Math.min(maxY, s.topY));
this.frameY(bottom, top);
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);
Expand All @@ -985,6 +985,29 @@ export class VolumeRenderer {
(this.uniforms.wrap.value as THREE.Vector2).set(mod(this.origin.x, W * VOLUME_TILE), mod(this.origin.z, W * VOLUME_TILE));
}

/**
* Keeps the drawn heights in the middle of the view: when Bottom or Top
* change, the camera moves up or down by as much as the middle of the
* box did, so a thin slice such as 0 to 64 isn't left at the bottom of
* the screen. Before the camera has been moved by hand, it is fitted to
* the box again too.
*/
private frameY(bottom: number, top: number) {
const was = this.shownY;
// Without tiles the heights are only guesses; wait for the grid they're clamped to.
if (!this.grid || (was && was.bottom === bottom && was.top === top)) return;
this.shownY = { bottom, top };
// A remembered camera is already where it was left.
if (!was && this.restored) return;
const mid = (bottom + top) / 2;
// A camera moved by hand keeps its offset from the middle; otherwise it looks at the middle.
const dy = mid - (was && this.touched ? (was.bottom + was.top) / 2 : this.controls.target.y);
this.controls.target.y += dy;
this.camera.position.y += dy;
if (this.touched) this.controls.update();
else this.fit();
}

/** While the view moves, draw at half resolution, then sharpen once it has been still a moment. */
private moving() {
if (this.renderer.getPixelRatio() !== this.full / 2) this.renderer.setPixelRatio(this.full / 2);
Expand Down
2 changes: 1 addition & 1 deletion site/guides/terrain.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ In JSON a formula is a deep tree of `add` and `mul` objects. In MMS it is arithm

## See what you are doing

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.
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. In a side view of density, **Bottom** and **Top** limit the heights drawn (leave one blank for no limit). Everything else stays empty and doesn't count towards the colour range, and the view moves and zooms to fit the heights you set.

**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.

Expand Down
53 changes: 53 additions & 0 deletions web/tests/smoke.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,29 @@ test('density previews use the picked palette over the range in view', async ({
expect(errors).toEqual([]);
});

test('a side view of density draws only the heights between Bottom and Top, framed', async ({ page }) => {
await page.goto('./');
await expect(status(page)).toHaveText(/No problems/, { timeout: 30_000 });
// Its value is y / 512, so the colour range in view says which heights were drawn.
await replaceText(page, 'DensityFunction grad = Gradient(axis = y, from_coordinate = 0, to_coordinate = 512, from_value = 0, to_value = 1)\n');
await expect(status(page)).toHaveText(/No problems/);
await page.locator('.cm-line').first().click();
const scale = page.getByLabel('Value scale');
await expect(scale).toContainText(/in view/, { timeout: 20_000 });
const bottom = page.getByLabel('Bottom y', { exact: true });
const top = page.getByLabel('Top y', { exact: true });
await bottom.fill('100');
await bottom.press('Enter');
await top.fill('164');
await top.press('Enter');
// The camera moves to their middle and zooms so 64 blocks fill most of the view.
const view = async () => JSON.parse((await page.locator('canvas[data-view]').getAttribute('data-view'))!);
await expect.poll(async () => (await view()).y).toBe(132);
expect((await view()).scale).toBeLessThan(0.5);
// Only 100 to 164 is sampled: about 0.195 to 0.320 in view.
await expect(scale).toContainText(/in view 0\.19\d … 0\.32\d/, { timeout: 20_000 });
});

test('the preview shows a grid, and per-block values when asked', async ({ page }) => {
const errors: string[] = [];
page.on('pageerror', (e) => errors.push(e.message));
Expand Down Expand Up @@ -594,6 +617,8 @@ test('the 3D density view samples tiles around the camera and travels', async ({
});

test('the 3D density view picks a threshold that shows something', async ({ page }) => {
// It waits for tiles twice, which is slow without a GPU.
test.setTimeout(120_000);
await page.goto('./');
await expect(status(page)).toHaveText(/No problems/, { timeout: 30_000 });
// Never negative, so a threshold of 0 would draw nothing.
Expand All @@ -613,6 +638,34 @@ test('the 3D density view picks a threshold that shows something', async ({ page
await expect(view.getByText(/Nothing in view crosses 0/)).toBeVisible();
await view.getByRole('button', { name: 'Auto', exact: true }).click();
await expect(view.getByText(/Nothing in view crosses/)).toBeHidden();

// A thin slice of heights is brought to the middle of the view, also after an orbit.
const canvas = view.getByRole('application');
const at = (await canvas.boundingBox())!;
await page.mouse.move(at.x + at.width / 2, at.y + at.height / 2);
await page.mouse.down();
await page.mouse.move(at.x + at.width / 2 + 40, at.y + at.height / 2 + 10, { steps: 5 });
await page.mouse.up();
const bottom = page.getByLabel('Bottom value', { exact: true });
await bottom.fill('0');
await bottom.press('Enter');
const top = page.getByLabel('Top value', { exact: true });
await top.fill('64');
await top.press('Enter');
await expect
.poll(async () => {
// Only once the ruler shows the new heights, so stale ticks can't pass.
const ys = ((await view.getByLabel('Height ruler').getAttribute('data-height-ruler')) ?? '').split(' ').map(Number);
if (!ys.includes(0) || ys.some((y) => !(y >= 0 && y <= 64))) return false;
const tops = await view
.getByLabel('Height ruler')
.locator('span')
.evaluateAll((spans) => spans.map((e) => parseFloat((e as HTMLElement).style.top)));
if (!tops.length) return false;
const mid = tops.reduce((a, b) => a + b, 0) / tops.length;
return Math.abs(mid / at.height - 0.5) < 0.08;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}, { timeout: 45_000 })
.toBe(true);
});

test('a preview comes back as it was left for each declaration, also after a reload', async ({ page }) => {
Expand Down
Loading