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
21 changes: 16 additions & 5 deletions editors/vscode/webview/App.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,32 @@
// the declaration to show (picked with a Preview CodeLens); the pane is
// the web editor's own component from packages/preview. The panel stays
// on that declaration while you edit elsewhere.
import { itemPath, PreviewPane, type OutputFile, type OutputItem } from '@mms/preview';
import { itemPath, PreviewPane, previewMemory, type OutputFile, type OutputItem } from '@mms/preview';
import PreviewWorker from '@mms/preview/worker?worker&inline';
import type { OutputAsset, OutputText, SplineAt, ToPanel, ToExtension } from '../src/messages';

// The state is what VS Code hands back when it restores the panel.
const vscode = acquireVsCodeApi<{ path: string | null; page?: number }>();
// It also holds what each preview was left showing, per declaration
// (mode, camera, cuts and so on), so it lasts as long as the panel does,
// across VS Code restarts too.
type Saved = { path: string | null; page?: number; memory?: [string, unknown][] };
const vscode = acquireVsCodeApi<Saved>();
let saved: Saved = vscode.getState() ?? { path: null };
function save(change: Partial<Saved>) {
saved = { ...saved, ...change };
vscode.setState(saved);
}
const memory = previewMemory(saved.memory ?? [], (entries) => save({ memory: entries }));

let output = $state<OutputFile[]>([]);
let items = $state<OutputItem[]>([]);
let texts = $state<OutputText[]>([]);
let assets = $state<OutputAsset[]>([]);
let textures = $state<Record<string, string>>({});
let structures = $state<Record<string, string>>({});
let path = $state<string | null>(vscode.getState()?.path ?? null);
let path = $state<string | null>(saved.path ?? null);
// The book page to open, from 0.
let page = $state(vscode.getState()?.page ?? 0);
let page = $state(saved.page ?? 0);
let ready = $state(false);
// The spline at the cursor in the last .mms editor, for the spline editor.
// What goes back to the extension is a $state.snapshot: postMessage
Expand All @@ -28,7 +38,7 @@
// The document version the spline's ranges are in, sent back with each edit.
let splineVersion = -1;

$effect(() => vscode.setState({ path, page }));
$effect(() => save({ path, page }));

window.addEventListener('message', (e: MessageEvent<ToPanel>) => {
const m = e.data;
Expand Down Expand Up @@ -88,6 +98,7 @@
unpinLabel="clear it"
onunpin={() => vscode.postMessage({ type: 'clear' } satisfies ToExtension)}
createWorker={() => new PreviewWorker()}
{memory}
{spline}
onsplineedit={(edits) => splineUri && vscode.postMessage({ type: 'splineEdit', uri: splineUri, version: splineVersion, edits: $state.snapshot(edits) } satisfies ToExtension)}
hint="Click Preview above a noise, density function, noise settings, surface rule, dimension, loot table, recipe, biome, template pool, jigsaw structure or book to show it here, or Edit spline above a spline to graph it."
Expand Down
2 changes: 2 additions & 0 deletions engine/mcp/docs/guides/editors.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ Distances are the game's: the square root of the sum of squares of how far each

Previews redraw as you type. The pin button in the web editor keeps the Preview tab on one declaration while you edit another, which is how you watch terrain change while editing the noise behind it.

Each declaration's preview remembers how you left it: the mode, camera and zoom, the 3D view's look, cuts and threshold, a jigsaw simulation's seed and slice, and a spline's coordinate sliders. Go back to a declaration and it shows the same view. The web editor keeps this in your browser for each project, and VS Code keeps it with the preview panel. **Reset view** puts the camera back.

## Seeing the output

- **JSON** (web) shows the file the declaration at the cursor becomes.
Expand Down
40 changes: 36 additions & 4 deletions packages/preview/src/PreviewPane.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import SplineView from './spline/SplineView.svelte';
import type { SplineAt, TextEdit } from './spline/spline';
import type { OutputAsset, OutputFile, OutputItem, OutputText } from './types';
import { provideMemory, record, storedMemory, type PreviewMemory } from './memory';

interface Props {
output: OutputFile[];
Expand Down Expand Up @@ -49,6 +50,11 @@
spline?: SplineAt | null;
/** Applies the spline editor's edits to the source. */
onsplineedit?: (edits: TextEdit[]) => void;
/**
* Where each preview remembers its settings per declaration (mode,
* camera, cuts and so on). Without one, they're kept in this browser.
*/
memory?: PreviewMemory;
}
let {
output,
Expand All @@ -65,14 +71,40 @@
textures = {},
structures = {},
spline = null,
onsplineedit
onsplineedit,
memory
}: Props = $props();
let ownMemory: PreviewMemory | undefined;
const memorySource = {
get current(): PreviewMemory {
return memory ?? (ownMemory ??= storedMemory('mms.preview.memory'));
}
};
provideMemory(memorySource);
// With the cursor in a spline, the spline editor shows over the
// declaration's own preview, unless that tab is picked.
let splineTab = $state<'spline' | 'preview'>('spline');
// A jigsaw structure shows its connections or a simulated layout.
let jigsawTab = $state<'connections' | 'simulation'>('connections');
const itemInfo = $derived(itemContext(output, items, textures));
// The tabs picked for a declaration come back with it.
let tabsFor: string | null = null;
let tabsFrom: PreviewMemory | null = null;
$effect.pre(() => {
// Another project's memory (in the web editor) counts as another declaration.
const m = memorySource.current;
if (path === tabsFor && m === tabsFrom) return;
tabsFor = path;
tabsFrom = m;
const saved = path ? record(m.get(`pane:${path}`)) : undefined;
splineTab = saved?.spline === 'preview' ? 'preview' : 'spline';
jigsawTab = saved?.jigsaw === 'simulation' ? 'simulation' : 'connections';
});
function pickTab(spline: typeof splineTab, jigsaw: typeof jigsawTab) {
splineTab = spline;
jigsawTab = jigsaw;
if (path) memorySource.current.set(`pane:${path}`, { spline, jigsaw });
}

const file = $derived(output.find((f) => f.path === path) ?? null);
const book = $derived(bookAt(path, items) ? (items.find((it) => itemPath(it.id) === path) ?? null) : null);
Expand All @@ -97,14 +129,14 @@
role="tab"
aria-selected={splineTab === id}
class="-mb-px border-b-2 px-2 py-1 {splineTab === id ? 'border-accent font-medium' : 'border-transparent text-muted hover:text-ink'}"
onclick={() => (splineTab = id as typeof splineTab)}>{label}</button
onclick={() => pickTab(id as typeof splineTab, jigsawTab)}>{label}</button
>
{/each}
</div>
{/if}
<div class="min-h-0 flex-1">
{#if spline && splineTab === 'spline'}
<SplineView data={spline} onedit={onsplineedit} />
<SplineView data={spline} onedit={onsplineedit} memoryKey={path ? `spline:${path}` : undefined} />
{:else if book}
<BookView stack={book.text} {output} {page} />
{:else if text}
Expand All @@ -118,7 +150,7 @@
role="tab"
aria-selected={jigsawTab === id}
class="-mb-px border-b-2 px-2 py-1 {jigsawTab === id ? 'border-accent font-medium' : 'border-transparent text-muted hover:text-ink'}"
onclick={() => (jigsawTab = id as typeof jigsawTab)}>{label}</button
onclick={() => pickTab(splineTab, id as typeof jigsawTab)}>{label}</button
>
{/each}
</div>
Expand Down
1 change: 1 addition & 0 deletions packages/preview/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ export { simulate, type Simulation, type PlacedPiece } from './jigsaw/simulate';
export type { OutputAsset, OutputFile, OutputItem, OutputJigsaw, OutputText, SourceRange } from './types';
export { default as SplineView } from './spline/SplineView.svelte';
export { evaluate as evaluateSpline, type SplineAt, type SplineData, type TextEdit as SplineEdit } from './spline/spline';
export { forgetStoredMemory, memory as previewMemory, storedMemory, type PreviewMemory } from './memory';
45 changes: 38 additions & 7 deletions packages/preview/src/jigsaw/JigsawSim.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import { blockMesh, boxMesh, clip, edgeLines, fade, hit, ray, VoxelView, type Camera, type Rgb, type Slice } from './voxel';
import { blockColor } from '../preview/colors';
import type { OutputAsset, OutputFile } from '../types';
import { record, restore, useMemory, type PreviewMemory } from '../memory';

interface Props {
/** The jigsaw structure's output path. */
Expand All @@ -30,11 +31,6 @@

/** A depth set here, in place of the structure's size; null follows the size. */
let depth = $state<number | null>(null);
$effect(() => {
// Another structure starts again from its own size.
void path;
depth = null;
});

const sim: Simulation | null = $derived(simulate(path, output, assets, { seed, ...(depth !== null ? { depth } : {}) }));
const setDepth = (v: number) => {
Expand Down Expand Up @@ -105,6 +101,39 @@
let camera = $state<Camera>({ target: [0, 0, 0], yaw: Math.PI / 4, pitch: Math.PI / 5, distance: 60 });
let framedFor: Simulation | null = null;

// Each structure remembers its seed, view, slice, depth and camera (see
// memory.ts). One shown for the first time starts from its own size,
// framed by the camera.
const memory = useMemory();
let shownPath: string | null = null;
/** The structure whose camera is in place, so its first layout isn't framed over it. */
let framedPath: string | null = null;
let shownFrom: PreviewMemory | null = null;
$effect.pre(() => {
const m = memory.current; // another project's memory counts as another structure
if (path === shownPath && m === shownFrom) return;
shownPath = path;
shownFrom = m;
const saved = record(m.get(`jigsaw-sim:${path}`));
seed = typeof saved?.seed === 'number' && Number.isInteger(saved.seed) ? saved.seed : 0;
mode = saved?.mode === 'blocks' ? 'blocks' : 'boxes';
axis = (['x', 'y', 'z'] as const).find((a) => a === saved?.axis) ?? 'off';
lastAxis = axis; // keeps the slice where it was
at = typeof saved?.at === 'number' && Number.isFinite(saved.at) ? saved.at : 0;
depth = typeof saved?.depth === 'number' && Number.isFinite(saved.depth) ? Math.max(0, Math.min(MAX_DEPTH, Math.round(saved.depth))) : null;
const cam = saved?.camera ? restore<Camera>({ target: [0, 0, 0], yaw: camera.yaw, pitch: camera.pitch, distance: 60 }, saved.camera) : null;
framedFor = null;
if (cam && cam.target.length === 3 && cam.target.every(Number.isFinite) && cam.distance > 0) {
camera = cam;
framedPath = path; // stays where it was left, not framed again
} else framedPath = null;
});
$effect(() => {
const settings = { seed, mode, axis, at, depth, camera: $state.snapshot(camera) };
const m = memory.current;
if (path === shownPath && m === shownFrom) m.set(`jigsaw-sim:${path}`, settings);
});

function frame() {
const [lo, hi] = extent;
const size = Math.max(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]) + 1;
Expand Down Expand Up @@ -173,9 +202,11 @@
});
$effect(() => {
if (sim && sim !== framedFor && sim.pieces.length) {
// Frame the first layout; keep the camera when re-rolling.
if (!framedFor) frame();
// Frame the first layout; keep the camera when re-rolling, and
// where it was left when the structure comes back.
if (!framedFor && framedPath !== path) frame();
framedFor = sim;
framedPath = path;
}
});

Expand Down
141 changes: 141 additions & 0 deletions packages/preview/src/memory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
// What each preview remembers per declaration: the mode, camera, cuts,
// threshold and so on, so going back to a file shows it as it was left.
// The host decides where it lives: the web editor keeps it in this
// browser for each project, VS Code in the preview panel's own state.
// The previews reach it through PreviewPane's context.

import { getContext, setContext } from 'svelte';

/** Settings by key, such as `preview:<output path>`. Values are plain JSON. */
export interface PreviewMemory {
get<T>(key: string): T | undefined;
set(key: string, value: unknown): void;
/** Forgets everything, and doesn't save again. */
clear(): void;
}

/** The most declarations remembered; the ones left longest ago go first. */
export const MEMORY_LIMIT = 200;

type Entries = [string, unknown][];

/**
* A memory kept in a Map in least recently set order, which hands its
* entries to save at most every `wait` ms (a camera being dragged changes
* them every frame) and once more when the page goes away.
*/
export function memory(initial: Entries, save: (entries: Entries) => void, wait = 400): PreviewMemory {
const map = new Map<string, unknown>();
for (const e of Array.isArray(initial) ? initial : []) if (Array.isArray(e) && typeof e[0] === 'string') map.set(e[0], e[1]);
let timer: ReturnType<typeof setTimeout> | undefined;
const flush = () => {
clearTimeout(timer);
timer = undefined;
try {
save([...map]);
} catch {
// Not remembered past this page; still remembered while it's open.
}
};
let cleared = false;
const onHide = () => timer !== undefined && flush();
globalThis.addEventListener?.('pagehide', onHide);
return {
clear() {
cleared = true;
clearTimeout(timer);
timer = undefined;
map.clear();
globalThis.removeEventListener?.('pagehide', onHide);
},
get<T>(key: string) {
return map.get(key) as T | undefined;
},
set(key, value) {
if (cleared) return;
const json = JSON.stringify(value);
if (json === undefined) return;
const copy = JSON.parse(json);
if (map.has(key) && JSON.stringify(map.get(key)) === json) return;
map.delete(key);
map.set(key, copy);
while (map.size > MEMORY_LIMIT) map.delete(map.keys().next().value!);
if (timer === undefined) timer = setTimeout(flush, wait);
}
};
}

const stored = new Map<string, PreviewMemory>();
/**
* The memory kept in this browser's localStorage under `key`. There is one
* per key for the page's life, so going back to a project finds the
* settings it hasn't saved yet, and its pagehide listener isn't added twice.
*/
export function storedMemory(key: string): PreviewMemory {
let m = stored.get(key);
if (m) return m;
let initial: Entries = [];
try {
initial = JSON.parse(localStorage.getItem(key) ?? '[]');
} catch {
// Storage can be unavailable (private windows, some webviews) or hold something else.
}
m = memory(initial, (entries) => localStorage.setItem(key, JSON.stringify(entries)));
stored.set(key, m);
return m;
}

/** Forgets the memory under `key`, here and in localStorage (its project was deleted). */
export function forgetStoredMemory(key: string) {
stored.get(key)?.clear();
stored.delete(key);
try {
localStorage.removeItem(key);
} catch {
// Nothing was remembered.
}
}

const contextKey = Symbol('preview memory');

/** Gives the previews under this component a memory; `current` is read each time, so the host can switch it (another project). */
export function provideMemory(source: { readonly current: PreviewMemory }) {
setContext(contextKey, source);
}

/**
* The memory PreviewPane provides. A preview used on its own remembers in
* this browser, under a shared key.
*/
export function useMemory(): { readonly current: PreviewMemory } {
const source = getContext<{ readonly current: PreviewMemory } | undefined>(contextKey);
if (source) return source;
return { current: storedMemory('mms.preview.memory') };
}

/**
* `base` with what `saved` has for each of its keys, where it has the same
* type (objects field by field). A setting remembered by an older version
* that no longer fits keeps the base's value. A key whose base value is
* null takes any saved value but undefined.
*/
export function restore<T extends object>(base: T, saved: unknown): T {
if (!saved || typeof saved !== 'object' || Array.isArray(saved)) return base;
const s = saved as Record<string, unknown>;
const out = { ...base } as Record<string, unknown>;
for (const [k, b] of Object.entries(base)) {
const v = s[k];
if (v === undefined) continue;
if (b === null) out[k] = v;
else if (Array.isArray(b)) {
if (Array.isArray(v)) out[k] = v;
} else if (typeof b === 'object') out[k] = restore(b, v);
else if (typeof v === typeof b && (typeof v !== 'number' || Number.isFinite(v))) out[k] = v;
}
return out as T;
}

/** `value` if it's a plain object, else undefined. */
export function record(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
}
Loading
Loading