diff --git a/apps/web/src/lib/components/SelectionPanel.svelte b/apps/web/src/lib/components/SelectionPanel.svelte index 3845be1..1599a6e 100644 --- a/apps/web/src/lib/components/SelectionPanel.svelte +++ b/apps/web/src/lib/components/SelectionPanel.svelte @@ -97,8 +97,9 @@ const status = $derived(session.error !== "" ? session.error : session.message);
+
-

Works with the keyboard alone. {span} The block state panel then shows that block.

+

Works with the keyboard alone. {span} Set or Inspect shows that block in the block state panel.

{/snippet} @@ -217,7 +218,7 @@ const status = $derived(session.error !== "" ? session.error : session.message);

Corners, typed

@@ -300,7 +301,7 @@ const status = $derived(session.error !== "" ? session.error : session.message); diff --git a/apps/web/src/lib/editor-session.svelte.ts b/apps/web/src/lib/editor-session.svelte.ts index 5ab8e51..49956ab 100644 --- a/apps/web/src/lib/editor-session.svelte.ts +++ b/apps/web/src/lib/editor-session.svelte.ts @@ -6,6 +6,7 @@ // cells. After every change the sections core marked dirty go to the renderer to be re-meshed. import { + AIR, type Box, type Clipboard, type Command, @@ -279,7 +280,7 @@ export class EditSession { const p = this.inspected; if (p === null) return null; const b = this.volume.get(p[0], p[1], p[2]); - return b === undefined ? null : b; + return b === undefined || b === AIR ? null : b; } get paletteBlocks(): ReturnType { @@ -439,7 +440,9 @@ export class EditSession { this.canvas.focus({ preventScroll: true }); this.canvas.setPointerCapture(e.pointerId); this.error = ""; - this.begin(this.pick(e.clientX, e.clientY), e.clientX, e.clientY); + const hit = this.pick(e.clientX, e.clientY); + this.applyHover(hit); + this.begin(hit, e.clientX, e.clientY); } private begin(hit: Hover | null, x: number, y: number): void { @@ -593,14 +596,16 @@ export class EditSession { this.applyHover(this.pick(x, y)); } - /** Make a pick the hover, redrawing only if it names another cell. */ + /** Make a pick the hover, redrawing only if it names another cell or block. */ private applyHover(hit: Hover | null): void { const same = hit === null ? this.hover === null : this.hover !== null && keyOf(hit.position) === keyOf(this.hover.position) && - keyOf(hit.adjacent) === keyOf(this.hover.adjacent); + keyOf(hit.adjacent) === keyOf(this.hover.adjacent) && + keyOf(hit.normal) === keyOf(this.hover.normal) && + hit.block === this.hover.block; if (same) return; this.hover = hit; if (hit !== null) this.inspected = hit.position; @@ -615,10 +620,10 @@ export class EditSession { const hit = this.pick( x, y, - drag.tool === "erase" ? undefined : (cx, cy, cz) => drag.touched.has(`${cx},${cy},${cz}`), + drag.tool === "place" ? (cx, cy, cz) => drag.touched.has(`${cx},${cy},${cz}`) : undefined, ); - if (hit !== null) this.brushTo(drag, hit); this.hover = hit; + if (hit !== null) this.brushTo(drag, hit); break; } case "line": { @@ -783,6 +788,7 @@ export class EditSession { const hit = this.pick(x, ry); if (hit === null) return; this.error = ""; + this.hover = hit; this.begin(hit, x, ry); this.schedule(); } @@ -1360,6 +1366,7 @@ export class EditSession { if (drag.kind === "brush") { drag.stroke.cancel(); this.flush(); + this.syncHover(); } else if (drag.kind === "select") this.selection = drag.before; this.refreshHighlight(); } @@ -1444,6 +1451,7 @@ export class EditSession { this.error = ""; this.flush(); this.revision++; + this.syncHover(); this.refreshHighlight(); } @@ -1470,6 +1478,19 @@ export class EditSession { this.onEvent?.(event); } + /** Keep `hover` matching the volume after an edit or history step; returns whether it cleared to `null`. */ + private syncHover(): boolean { + const h = this.hover; + if (h === null) return false; + const b = this.volume.get(h.position[0], h.position[1], h.position[2]); + if (b === undefined || b === AIR) { + this.hover = null; + return true; + } + if (b !== h.block) this.hover = { ...h, block: b }; + return false; + } + /** Tell the renderer which sections to rebuild, keep the pick bounds covering the volume, and refresh the panels. */ private afterChange(command: Command): void { forEachChange(command, (x, y, z, _before, after) => { @@ -1492,6 +1513,15 @@ export class EditSession { }); this.flush(); this.revision++; + if ( + this.syncHover() || + (this.drag === null && + this.pending === null && + this.inspected !== null && + this.inspectedBlock === null) + ) { + this.refreshHighlight(); + } } private flush(): void { @@ -1601,6 +1631,27 @@ export class EditSession { return done; } + /** Point the block-state panel at a cell without editing it. Returns whether a block was there. */ + inspectAt(pos: Vec3): boolean { + if (pos.length !== 3 || !pos.every((n) => Number.isInteger(n) && Math.abs(n) <= 0x7fffffff)) { + this.error = "position must be integer coordinates"; + this.message = ""; + return false; + } + const cell: Vec3 = [pos[0] || 0, pos[1] || 0, pos[2] || 0]; + const b = this.volume.get(cell[0], cell[1], cell[2]); + if (b === undefined || b === AIR) { + this.inspected = null; + this.say(`No block at ${cellText(cell)}.`); + this.refreshHighlight(); + return false; + } + this.inspected = cell; + this.say(`${withoutNbt(b)} at ${cellText(cell)}`); + this.refreshHighlight(); + return true; + } + /** Make a cell the one the block-state panel shows, as if the pointer were over it. */ private pointAt(pos: Vec3): void { this.inspected = pos; diff --git a/apps/web/test/editor-session.test.ts b/apps/web/test/editor-session.test.ts new file mode 100644 index 0000000..afe199b --- /dev/null +++ b/apps/web/test/editor-session.test.ts @@ -0,0 +1,396 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +// Tests for keyboard coordinate inspection (`inspectAt`), `AIR` handling in `inspectedBlock`, +// and keeping `hover` synced across `applyHover`, `replace`, brush strokes, cancels and undo/redo. + +import { AIR, type Vec3, Volume } from "@voxwright/core"; +import type { WebglRenderer } from "@voxwright/render/webgl"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { EditSession, type Hover } from "../src/lib/editor-session.svelte.ts"; + +const STONE = "minecraft:stone"; +const PLANKS = "minecraft:oak_planks"; +const GOLD = "minecraft:gold_block"; +const STAIRS_NORTH = + "minecraft:oak_stairs[facing=north,half=bottom,shape=straight,waterlogged=false]"; +const STAIRS_EAST = + "minecraft:oak_stairs[facing=east,half=bottom,shape=straight,waterlogged=false]"; + +const frames: Array<() => void> = []; +const savedRaf = { raf: globalThis.requestAnimationFrame, caf: globalThis.cancelAnimationFrame }; + +beforeEach(() => { + frames.length = 0; + globalThis.requestAnimationFrame = (cb: FrameRequestCallback): number => { + frames.push(() => cb(0)); + return frames.length; + }; + globalThis.cancelAnimationFrame = (id: number): void => { + frames[id - 1] = () => {}; + }; +}); + +afterEach(() => { + globalThis.requestAnimationFrame = savedRaf.raf; + globalThis.cancelAnimationFrame = savedRaf.caf; +}); + +const runFrames = (): void => { + for (const f of frames.splice(0)) f(); +}; + +function makeVolume(): Volume { + const volume = new Volume(); + for (let x = 0; x < 16; x++) { + for (let z = 0; z < 16; z++) volume.set(x, 0, z, STONE); + } + volume.set(3, 0, 3, PLANKS); + return volume; +} + +function makeSession(options: { volume?: Volume } = {}) { + const volume = options.volume ?? makeVolume(); + const highlights: Array> = []; + const renderer = { + getPose: () => ({ distance: 40 }), + focusOn: () => {}, + frameCamera: () => {}, + // Fake top-down raycast over cell (floor(x / 10), _, floor(y / 10)). + rayFromClient: (x: number, y: number) => ({ + origin: [x / 10, 10, y / 10] as [number, number, number], + direction: [0, -1, 0] as [number, number, number], + }), + markDirty: () => {}, + highlight: (boxes: Array<{ min: Vec3; max: Vec3; style: string }>) => { + highlights.push(boxes); + }, + } as unknown as WebglRenderer; + const canvas = { + getBoundingClientRect: () => ({ + left: 0, + top: 0, + right: 200, + bottom: 200, + width: 200, + height: 200, + }), + focus: () => {}, + setPointerCapture: () => {}, + hasPointerCapture: () => true, + releasePointerCapture: () => {}, + } as unknown as HTMLCanvasElement; + const session = new EditSession({ + renderer, + canvas, + volume, + dataVersion: null, + packBlocks: [], + isOverCanvas: () => true, + }); + return { session, volume, highlights, canvas }; +} + +type PointerHandlers = { + onPointerDown(e: unknown): void; + onPointerMove(e: unknown): void; + onPointerUp(e: unknown): void; + onPointerLeave(e: unknown): void; + applyHover(hit: Hover | null): void; +}; + +const internal = (s: EditSession): PointerHandlers => s as unknown as PointerHandlers; + +const mouseEvent = (canvas: HTMLCanvasElement, x: number, y: number, buttons = 0) => ({ + target: canvas, + pointerType: "mouse", + pointerId: 1, + button: 0, + buttons, + clientX: x, + clientY: y, + shiftKey: false, + altKey: false, + stopPropagation: () => {}, + preventDefault: () => {}, +}); + +/** Center of cell (cx, cz) in client pixels; touch cursor sits 64 px below at y + 64. */ +const cellPx = (cx: number, cz: number): { x: number; y: number } => ({ + x: cx * 10 + 5, + y: cz * 10 + 5, +}); + +const hoverBoxes = (highlights: Array>) => + (highlights.at(-1) ?? []).filter((b) => b.style === "hover"); + +describe("inspectAt and air handling", () => { + it("inspects a solid block without modifying the volume or history, stripping NBT from the message", () => { + const { session, volume, highlights } = makeSession(); + const chestWithNbt = 'minecraft:chest[facing=north]{Items:[{Slot:0b,id:"minecraft:apple"}]}'; + volume.set(4, 1, 5, chestWithNbt); + const input: [number, number, number] = [4, 1, 5]; + + expect(session.inspectAt(input)).toBe(true); + input[0] = 99; + + expect(session.inspected).toEqual([4, 1, 5]); + expect(session.inspectedBlock).toBe(chestWithNbt); + expect(session.message).toBe("minecraft:chest[facing=north] at 4, 1, 5"); + expect(session.error).toBe(""); + expect(session.undoCount).toBe(0); + expect(hoverBoxes(highlights)).toEqual([{ min: [4, 1, 5], max: [4, 1, 5], style: "hover" }]); + }); + + it("clears inspected and highlight when inspecting an unset cell", () => { + const { session, highlights } = makeSession(); + expect(session.inspectAt([3, 0, 3])).toBe(true); + expect(hoverBoxes(highlights)).toHaveLength(1); + + session.error = "previous error"; + expect(session.inspectAt([8, 4, 8])).toBe(false); + expect(session.inspected).toBeNull(); + expect(session.inspectedBlock).toBeNull(); + expect(session.message).toBe("No block at 8, 4, 8."); + expect(session.error).toBe(""); + expect(hoverBoxes(highlights)).toEqual([]); + }); + + it("treats explicit minecraft:air as empty in inspectAt and inspectedBlock", () => { + const { session, volume, highlights } = makeSession(); + volume.set(2, 0, 2, AIR); + + expect(session.inspectAt([3, 0, 3])).toBe(true); + expect(session.inspectAt([2, 0, 2])).toBe(false); + expect(session.inspected).toBeNull(); + expect(session.inspectedBlock).toBeNull(); + expect(session.message).toBe("No block at 2, 0, 2."); + expect(hoverBoxes(highlights)).toEqual([]); + + // Erasing a cell writes minecraft:air; inspectedBlock must treat that cell as null too. + expect(session.eraseAt([3, 0, 3])).toBe(true); + expect(volume.get(3, 0, 3)).toBe(AIR); + expect(session.inspectedBlock).toBeNull(); + expect(hoverBoxes(highlights)).toEqual([]); + }); + + it("rejects non-integer, non-finite, out-of-range, and cleared coordinate inputs", () => { + const { session } = makeSession(); + expect(session.inspectAt([3, 0, 3])).toBe(true); + + const badCases: Vec3[] = [ + [1.5, 0, 0], + [0, Number.NaN, 0], + [0, 0, Number.POSITIVE_INFINITY], + [0x80000000, 0, 0], + [null as unknown as number, 0, 0], + ]; + for (const pos of badCases) { + session.message = "stale message"; + expect(session.inspectAt(pos)).toBe(false); + expect(session.error).toBe("position must be integer coordinates"); + expect(session.message).toBe(""); + expect(session.inspected).toEqual([3, 0, 3]); + } + }); +}); + +describe("hover syncing after edits, brush strokes, and undo/redo", () => { + it("applyHover refreshes when the block or normal changes on the same cell", () => { + const { session, volume, canvas } = makeSession(); + session.setTool("place"); + // Point at (3, 0, 3) by using z = 3. + const pt = cellPx(3, 3); + internal(session).onPointerMove(mouseEvent(canvas, pt.x, pt.y)); + runFrames(); + expect(session.hover).toEqual({ + position: [3, 0, 3], + adjacent: [3, 1, 3], + normal: [0, 1, 0], + block: PLANKS, + }); + + // Mutate the block in place, then wiggle the pointer on the same cell: applyHover must update. + volume.set(3, 0, 3, GOLD); + internal(session).onPointerMove(mouseEvent(canvas, pt.x + 1, pt.y + 1)); + runFrames(); + expect(session.hover?.block).toBe(GOLD); + + // Changing only normal on the same position & adjacent must also replace hover. + const prev = session.hover; + internal(session).applyHover({ + position: [3, 0, 3], + adjacent: [3, 1, 3], + normal: [1, 0, 0], + block: GOLD, + }); + expect(session.hover).not.toBe(prev); + expect(session.hover?.normal).toEqual([1, 0, 0]); + }); + + it("replaceSelection updates hover.block with a new object reference, or clears hover to null on air", () => { + const { session, highlights, canvas } = makeSession(); + session.setTool("place"); + const pt = cellPx(3, 3); + internal(session).onPointerMove(mouseEvent(canvas, pt.x, pt.y)); + runFrames(); + const before = session.hover; + expect(before?.block).toBe(PLANKS); + + session.setSelection({ min: [2, 0, 2], max: [4, 0, 4] }); + session.block = GOLD; + expect(session.replace(PLANKS)).toBe(true); + + expect(session.hover).not.toBeNull(); + expect(session.hover).not.toBe(before); + expect(session.hover).toEqual({ + position: [3, 0, 3], + adjacent: [3, 1, 3], + normal: [0, 1, 0], + block: GOLD, + }); + + // Replacing the hovered block with air drops hover and removes the hover/ghost highlights. + session.block = AIR; + expect(session.replace(GOLD)).toBe(true); + expect(session.hover).toBeNull(); + const last = highlights.at(-1) ?? []; + expect(last.some((b) => b.style === "hover" || b.style === "ghost")).toBe(false); + }); + + it("setProperty updates hover.block when the hovered block changes state", () => { + const { session, volume, canvas } = makeSession(); + volume.set(3, 0, 3, STAIRS_NORTH); + session.setTool("navigate"); + const pt = cellPx(3, 3); + internal(session).onPointerMove(mouseEvent(canvas, pt.x, pt.y)); + runFrames(); + const before = session.hover; + expect(before?.block).toBe(STAIRS_NORTH); + + expect(session.setProperty("facing", "east")).toBe(true); + expect(session.hover).not.toBe(before); + expect(session.hover?.block).toBe(STAIRS_EAST); + }); + + it("mouse paint click & drag keeps hover synced to the new block without stale overwrite", () => { + const { session, canvas } = makeSession(); + session.setTool("paint"); + session.block = GOLD; + + const p1 = cellPx(3, 3); + const p2 = cellPx(4, 3); + internal(session).onPointerMove(mouseEvent(canvas, p1.x, p1.y)); + runFrames(); + expect(session.hover?.block).toBe(PLANKS); + + internal(session).onPointerDown(mouseEvent(canvas, p1.x, p1.y, 1)); + expect(session.hover).toMatchObject({ position: [3, 0, 3], block: GOLD }); + + internal(session).onPointerMove(mouseEvent(canvas, p2.x, p2.y, 1)); + runFrames(); + expect(session.hover).toMatchObject({ position: [4, 0, 3], block: GOLD }); + + internal(session).onPointerUp(mouseEvent(canvas, p2.x, p2.y, 0)); + expect(session.hover).toMatchObject({ position: [4, 0, 3], block: GOLD }); + }); + + it("touch paint and erase strokes do not restore stale pre-edit hits over hover or reticle", () => { + const paint = makeSession(); + paint.session.setTool("paint"); + paint.session.block = GOLD; + const f1 = cellPx(3, 3); + const f2 = cellPx(4, 3); + paint.session.touchMove(f1.x, f1.y + 64); + runFrames(); + expect(paint.session.hover?.block).toBe(PLANKS); + paint.session.touchStrokeBegin(f1.x, f1.y + 64); + expect(paint.session.hover).toMatchObject({ position: [3, 0, 3], block: GOLD }); + + paint.session.touchMove(f2.x, f2.y + 64); + runFrames(); + expect(paint.session.hover).toMatchObject({ position: [4, 0, 3], block: GOLD }); + expect(paint.session.reticle?.hit).toMatchObject({ position: [4, 0, 3], block: GOLD }); + + const erase = makeSession(); + erase.session.setTool("erase"); + erase.session.touchMove(f1.x, f1.y + 64); + runFrames(); + expect(erase.session.hover?.position).toEqual([3, 0, 3]); + erase.session.touchStrokeBegin(f1.x, f1.y + 64); + expect(erase.session.hover).toBeNull(); + + erase.session.touchMove(f2.x, f2.y + 64); + runFrames(); + expect(erase.volume.get(4, 0, 3)).toBe(AIR); + expect(erase.session.hover).toBeNull(); + expect(erase.session.reticle?.hit).toBeNull(); + }); + + it("cancelling an active mouse brush stroke syncs hover back to the reverted block", () => { + const { session, canvas } = makeSession(); + session.setTool("paint"); + session.block = GOLD; + const p1 = cellPx(3, 3); + internal(session).onPointerMove(mouseEvent(canvas, p1.x, p1.y)); + runFrames(); + internal(session).onPointerDown(mouseEvent(canvas, p1.x, p1.y, 1)); + expect(session.hover?.block).toBe(GOLD); + + expect(session.perform({ type: "escape" })).toBe(true); + expect(session.hover?.block).toBe(PLANKS); + }); + + it("undo and redo sync hover.block and clear hover when undone to empty or air", () => { + const { session, canvas } = makeSession(); + session.setTool("place"); + const pt = cellPx(3, 3); + internal(session).onPointerMove(mouseEvent(canvas, pt.x, pt.y)); + runFrames(); + + session.setSelection({ min: [3, 0, 3], max: [3, 0, 3] }); + session.block = GOLD; + expect(session.replace(PLANKS)).toBe(true); + const afterReplace = session.hover; + expect(afterReplace?.block).toBe(GOLD); + + session.undo(); + expect(session.hover).not.toBe(afterReplace); + expect(session.hover?.block).toBe(PLANKS); + + const afterUndo = session.hover; + session.redo(); + expect(session.hover).not.toBe(afterUndo); + expect(session.hover?.block).toBe(GOLD); + + // Placing above (3, 0, 3), hovering the new block, and undoing clears hover and its highlight. + const { session: s2, highlights: h2, canvas: c2 } = makeSession(); + expect(s2.placeAt([5, 1, 5], GOLD)).toBe(true); + s2.setTool("place"); + const p5 = cellPx(5, 5); + internal(s2).onPointerMove(mouseEvent(c2, p5.x, p5.y)); + runFrames(); + expect(s2.hover).toMatchObject({ position: [5, 1, 5], block: GOLD }); + + s2.undo(); + expect(s2.hover).toBeNull(); + expect(s2.inspectedBlock).toBeNull(); + expect(hoverBoxes(h2)).toEqual([]); + }); + + it("undoing a block placed over explicit minecraft:air also clears hover and its highlight", () => { + const { session, volume, highlights, canvas } = makeSession(); + volume.set(5, 1, 5, AIR); + expect(session.placeAt([5, 1, 5], GOLD)).toBe(true); + session.setTool("place"); + const p5 = cellPx(5, 5); + internal(session).onPointerMove(mouseEvent(canvas, p5.x, p5.y)); + runFrames(); + expect(session.hover).toMatchObject({ position: [5, 1, 5], block: GOLD }); + + session.undo(); + expect(volume.get(5, 1, 5)).toBe(AIR); + expect(session.hover).toBeNull(); + expect(session.inspectedBlock).toBeNull(); + expect(hoverBoxes(highlights)).toEqual([]); + }); +}); diff --git a/packages/core/src/codecs/bedrock.ts b/packages/core/src/codecs/bedrock.ts index ea3c380..8071150 100644 --- a/packages/core/src/codecs/bedrock.ts +++ b/packages/core/src/codecs/bedrock.ts @@ -96,11 +96,20 @@ const SIDE_TO_BEDROCK: Readonly> = { tall: "tall", }; const SHELF_CHAIN = ["unconnected", "right", "center", "left"] as const; +const BELL_TO_BEDROCK: Readonly> = { + floor: "standing", + ceiling: "hanging", + single_wall: "side", + double_wall: "multiple", +}; +const BELL_TO_JAVA: Readonly> = Object.fromEntries( + Object.entries(BELL_TO_BEDROCK).map(([j, b]) => [b, j]), +); const HORIZONTAL = new Set(["north", "south", "east", "west"]); /** Blocks whose facing is a Bedrock `facing_direction` int. Everything else uses `cardinal_direction`. */ const FACING_DIRECTION_BLOCKS = - /^(barrel|hopper|dropper|dispenser|piston|sticky_piston|observer|ladder|.*_wall_sign|.*_wall_banner|.*_wall_hanging_sign)$/; + /^(barrel|hopper|dropper|dispenser|piston|sticky_piston|observer|ladder|end_rod|(?:.*_)?lightning_rod|.*_wall_sign|.*_wall_banner|.*_wall_hanging_sign)$/; const bare = (id: string): string => id.slice(id.indexOf(":") + 1); const withNs = (n: string): string => (n.includes(":") ? n : `minecraft:${n}`); @@ -193,6 +202,19 @@ export function bedrockToJava( const chain = Number(take("powered_shelf_type")); out.set("side_chain", SHELF_CHAIN[chain] ?? "unconnected"); if (chain !== 0) warnings.push(`${name}: side_chain value ${chain} is assumed, not verified`); + } else if ((name === "campfire" || name === "soul_campfire") && s.has("extinguished")) { + out.set("lit", Number(take("extinguished")) ? "false" : "true"); + } else if ( + name === "bell" && + (s.has("attachment") || s.has("direction") || s.has("toggle_bit")) + ) { + const att = String(take("attachment") ?? "standing"); + out.set( + "attachment", + Object.hasOwn(BELL_TO_JAVA, att) ? (BELL_TO_JAVA[att] as string) : "floor", + ); + out.set("facing", BED_DIR[Number(take("direction"))] ?? "north"); + out.set("powered", bool(take("toggle_bit"))); } // Connections: fences, panes and bars use 0/1, walls use none/short/tall. @@ -335,6 +357,29 @@ export function javaToBedrock(canonical: string): ToBedrockResult { ), ), ); + } else if (name === "campfire" || name === "soul_campfire") { + const facing = take("facing") ?? "north"; + if (HORIZONTAL.has(facing)) { + states.set("minecraft:cardinal_direction", str(facing)); + } else { + warnings.push(`${name}: facing=${facing} has no Bedrock cardinal_direction`); + } + states.set("extinguished", byte(take("lit") === "false" ? 1 : 0)); + if (p.get("signal_fire") === "false") take("signal_fire"); + } else if (name === "bell") { + const att = take("attachment") ?? "floor"; + const bedrockAtt = Object.hasOwn(BELL_TO_BEDROCK, att) ? BELL_TO_BEDROCK[att] : undefined; + if (bedrockAtt === undefined) { + warnings.push(`${name}: unknown attachment=${att}`); + } + states.set("attachment", str(bedrockAtt ?? "standing")); + const facing = take("facing") ?? "north"; + const dir = BED_DIR.indexOf(facing as (typeof BED_DIR)[number]); + if (dir === -1) { + warnings.push(`${name}: facing=${facing} has no Bedrock direction`); + } + states.set("direction", int(dir === -1 ? 2 : dir)); + states.set("toggle_bit", byte(flag(take("powered")))); } // Connections. Fences and panes carry booleans; walls carry none/low/tall. @@ -344,7 +389,7 @@ export function javaToBedrock(canonical: string): ToBedrockResult { if (v === undefined) continue; p.delete(side); if (isWall) states.set(`wall_connection_type_${side}`, str(SIDE_TO_BEDROCK[v] ?? "none")); - else states.set(`minecraft:connection_${side}`, int(flag(v))); + else states.set(`minecraft:connection_${side}`, byte(flag(v))); } if (isWall && p.has("up")) states.set("wall_post_bit", byte(flag(take("up")))); diff --git a/packages/core/test/mcstructure.test.ts b/packages/core/test/mcstructure.test.ts index 9e838f8..8df5841 100644 --- a/packages/core/test/mcstructure.test.ts +++ b/packages/core/test/mcstructure.test.ts @@ -4,12 +4,17 @@ import { AIR, bedrockToJava, CodecError, + type CompoundTag, canonicalize, javaToBedrock, + type ListTag, parseBlockString, readLitematic, readMcstructure, + readNbt, readStructureNbt, + TagId, + tagId, Volume, writeMcstructure, } from "../src/index.ts"; @@ -181,6 +186,307 @@ describe(".mcstructure", () => { } }); + it("writes minecraft:connection_* as NBT TAG_Byte (1) and keeps minecraft:corner", async () => { + const fence = "minecraft:oak_fence[east=true,north=false,south=true,west=false]"; + const pane = "minecraft:glass_pane[east=false,north=true,south=false,west=true]"; + const stairs = "minecraft:oak_stairs[facing=north,half=bottom,shape=outer_right]"; + + const fenceBedrock = javaToBedrock(fence); + expect(fenceBedrock.warnings).toEqual([]); + expect(fenceBedrock.block.states.get("minecraft:connection_east")).toEqual({ + kind: "byte", + value: 1, + }); + expect(fenceBedrock.block.states.get("minecraft:connection_north")).toEqual({ + kind: "byte", + value: 0, + }); + expect(fenceBedrock.block.states.get("minecraft:connection_south")).toEqual({ + kind: "byte", + value: 1, + }); + expect(fenceBedrock.block.states.get("minecraft:connection_west")).toEqual({ + kind: "byte", + value: 0, + }); + + const stairsBedrock = javaToBedrock(stairs); + expect(stairsBedrock.warnings).toEqual([]); + expect(stairsBedrock.block.states.get("minecraft:corner")).toEqual({ + kind: "string", + value: "outer_right", + }); + + const v = new Volume(); + v.set(0, 0, 0, fence); + v.set(1, 0, 0, pane); + v.set(2, 0, 0, stairs); + const { bytes, warnings } = writeMcstructure(v); + expect(warnings).toEqual([]); + + const root = readNbt(bytes, { endian: "little" }).tag; + const structure = root.value.get("structure") as CompoundTag; + const paletteRoot = structure.value.get("palette") as CompoundTag; + const def = paletteRoot.value.get("default") as CompoundTag; + const palette = def.value.get("block_palette") as ListTag; + + let seenConnections = 0; + for (const rawEntry of palette.value) { + const entry = rawEntry as CompoundTag; + const states = entry.value.get("states") as CompoundTag; + for (const [key, tag] of states.value) { + if (key.startsWith("minecraft:connection_")) { + expect(tag.type, key).toBe("byte"); + expect(tagId(tag), key).toBe(TagId.Byte); + seenConnections++; + } + } + } + expect(seenConnections).toBe(8); + + // Also verify the raw little-endian NBT wire tag byte (0x01 = TAG_Byte) before key length + name. + const keyBytes = Buffer.from("minecraft:connection_east", "utf8"); + const rawBuf = Buffer.from(bytes); + const keyOffset = rawBuf.indexOf(keyBytes); + expect(keyOffset).toBeGreaterThanOrEqual(3); + expect(rawBuf[keyOffset - 3]).toBe(TagId.Byte); + expect(rawBuf.readUInt16LE(keyOffset - 2)).toBe(keyBytes.length); + + const back = await readMcstructure(bytes); + expect(back.warnings).toEqual([]); + expect(cellsOf(back.volume)).toEqual(cellsOf(v)); + }); + + it("translates lightning_rod variants and end_rod across all 6 facings and powered states", async () => { + const dirs = ["down", "up", "north", "south", "west", "east"] as const; + const v = new Volume(); + let x = 0; + + for (let i = 0; i < dirs.length; i++) { + const dir = dirs[i] as string; + const endRod = `minecraft:end_rod[facing=${dir}]`; + const endRes = javaToBedrock(endRod); + expect(endRes.warnings, endRod).toEqual([]); + expect(endRes.block.states.get("facing_direction")).toEqual({ kind: "int", value: i }); + const endBack = bedrockToJava( + endRes.block.name, + new Map([...endRes.block.states].map(([k, val]) => [k, val.value])), + ); + expect(endBack.warnings, endRod).toEqual([]); + expect(endBack.state).toBe(canonicalize(endRod)); + v.set(x++, 0, 0, endRod); + + for (const block of ["minecraft:lightning_rod", "minecraft:waxed_exposed_lightning_rod"]) { + for (const powered of ["false", "true"]) { + const rod = `${block}[facing=${dir},powered=${powered}]`; + const res = javaToBedrock(rod); + expect(res.warnings, rod).toEqual([]); + expect(res.block.states.get("facing_direction")).toEqual({ kind: "int", value: i }); + expect(res.block.states.get("powered_bit")).toEqual({ + kind: "byte", + value: powered === "true" ? 1 : 0, + }); + const back = bedrockToJava( + res.block.name, + new Map([...res.block.states].map(([k, val]) => [k, val.value])), + ); + expect(back.warnings, rod).toEqual([]); + expect(back.state).toBe(canonicalize(rod)); + v.set(x++, 0, 0, rod); + } + } + } + + // Other copper variants and waterlogging also match and round-trip cleanly. + const extraRods = [ + "minecraft:exposed_lightning_rod[facing=up,powered=false]", + "minecraft:waxed_oxidized_lightning_rod[facing=north,powered=true,waterlogged=true]", + ]; + for (const rod of extraRods) v.set(x++, 0, 0, rod); + + const { bytes, warnings } = writeMcstructure(v); + expect(warnings).toEqual([]); + const readBack = await readMcstructure(bytes); + expect(readBack.warnings).toEqual([]); + expect(cellsOf(readBack.volume)).toEqual(cellsOf(v)); + + // Unhandled properties on lightning_rod still emit warnings. + expect(javaToBedrock("minecraft:lightning_rod[facing=up,extra=1]").warnings).toEqual([ + "lightning_rod: dropped Java property extra=1", + ]); + }); + + it("translates campfire and soul_campfire including lit, extinguished, and signal_fire", async () => { + // Omitted lit defaults to lit=true (extinguished=0); omitted facing defaults to north. + const bare = javaToBedrock("minecraft:campfire"); + expect(bare.warnings).toEqual([]); + expect(bare.block.states.get("minecraft:cardinal_direction")).toEqual({ + kind: "string", + value: "north", + }); + expect(bare.block.states.get("extinguished")).toEqual({ kind: "byte", value: 0 }); + + const unlitDefaultFacing = javaToBedrock("minecraft:campfire[lit=false]"); + expect(unlitDefaultFacing.warnings).toEqual([]); + expect(unlitDefaultFacing.block.states.get("minecraft:cardinal_direction")).toEqual({ + kind: "string", + value: "north", + }); + expect(unlitDefaultFacing.block.states.get("extinguished")).toEqual({ + kind: "byte", + value: 1, + }); + + // signal_fire=false is dropped cleanly; signal_fire=true warns; invalid facing warns. + const quietSignal = javaToBedrock("minecraft:campfire[facing=west,lit=true,signal_fire=false]"); + expect(quietSignal.warnings).toEqual([]); + expect(quietSignal.block.states.get("minecraft:cardinal_direction")).toEqual({ + kind: "string", + value: "west", + }); + expect(quietSignal.block.states.get("extinguished")).toEqual({ kind: "byte", value: 0 }); + + const loudSignal = javaToBedrock("minecraft:campfire[facing=south,lit=false,signal_fire=true]"); + expect(loudSignal.warnings).toEqual(["campfire: dropped Java property signal_fire=true"]); + expect(loudSignal.block.states.get("minecraft:cardinal_direction")).toEqual({ + kind: "string", + value: "south", + }); + expect(loudSignal.block.states.get("extinguished")).toEqual({ kind: "byte", value: 1 }); + + const soulLoud = javaToBedrock( + "minecraft:soul_campfire[facing=east,lit=true,signal_fire=true]", + ); + expect(soulLoud.warnings).toEqual(["soul_campfire: dropped Java property signal_fire=true"]); + + const badFacing = javaToBedrock("minecraft:campfire[facing=up,lit=true]"); + expect(badFacing.warnings).toEqual(["campfire: facing=up has no Bedrock cardinal_direction"]); + expect(badFacing.block.states.has("minecraft:cardinal_direction")).toBe(false); + expect(badFacing.block.states.get("extinguished")).toEqual({ kind: "byte", value: 0 }); + + // Round-trip lit and unlit campfires & soul_campfires through .mcstructure. + const v = new Volume(); + const cases = [ + ["minecraft:campfire[facing=north,lit=true]", "minecraft:campfire[facing=north,lit=true]"], + ["minecraft:campfire[facing=east,lit=false]", "minecraft:campfire[facing=east,lit=false]"], + [ + "minecraft:campfire[facing=south,lit=true,signal_fire=false]", + "minecraft:campfire[facing=south,lit=true]", + ], + [ + "minecraft:campfire[facing=west,lit=false,waterlogged=true]", + "minecraft:campfire[facing=west,lit=false,waterlogged=true]", + ], + [ + "minecraft:soul_campfire[facing=north,lit=true,signal_fire=false]", + "minecraft:soul_campfire[facing=north,lit=true]", + ], + [ + "minecraft:soul_campfire[facing=east,lit=false]", + "minecraft:soul_campfire[facing=east,lit=false]", + ], + ] as const; + + cases.forEach(([input], idx) => { + v.set(idx, 0, 0, input); + }); + const { bytes, warnings } = writeMcstructure(v); + expect(warnings).toEqual([]); + const readBack = await readMcstructure(bytes); + expect(readBack.warnings).toEqual([]); + cases.forEach(([, expected], idx) => { + expect(readBack.volume.get(idx, 0, 0)).toBe(expected); + }); + }); + + it("translates bell across all 4 attachments, 4 directions, and powered states", async () => { + const attachments = [ + ["floor", "standing"], + ["ceiling", "hanging"], + ["single_wall", "side"], + ["double_wall", "multiple"], + ] as const; + const directions = [ + ["south", 0], + ["west", 1], + ["north", 2], + ["east", 3], + ] as const; + + // Defaults when omitted: attachment=floor, facing=north, powered=false. + const bare = javaToBedrock("minecraft:bell"); + expect(bare.warnings).toEqual([]); + expect(bare.block.states.get("attachment")).toEqual({ kind: "string", value: "standing" }); + expect(bare.block.states.get("direction")).toEqual({ kind: "int", value: 2 }); + expect(bare.block.states.get("toggle_bit")).toEqual({ kind: "byte", value: 0 }); + expect(bare.block.states.has("minecraft:cardinal_direction")).toBe(false); + expect(bare.block.states.has("powered_bit")).toBe(false); + + const v = new Volume(); + let x = 0; + for (const [javaAtt, bedrockAtt] of attachments) { + for (const [facing, dirIdx] of directions) { + for (const powered of ["false", "true"]) { + const java = `minecraft:bell[attachment=${javaAtt},facing=${facing},powered=${powered}]`; + const res = javaToBedrock(java); + expect(res.warnings, java).toEqual([]); + expect(res.block.states.get("attachment")).toEqual({ + kind: "string", + value: bedrockAtt, + }); + expect(res.block.states.get("direction")).toEqual({ kind: "int", value: dirIdx }); + expect(res.block.states.get("toggle_bit")).toEqual({ + kind: "byte", + value: powered === "true" ? 1 : 0, + }); + expect(res.block.states.has("minecraft:cardinal_direction")).toBe(false); + expect(res.block.states.has("powered_bit")).toBe(false); + + const back = bedrockToJava( + res.block.name, + new Map([...res.block.states].map(([k, val]) => [k, val.value])), + ); + expect(back.warnings, java).toEqual([]); + expect(back.state).toBe(canonicalize(java)); + + v.set(x++, 0, 0, java); + } + } + } + + const { bytes, warnings } = writeMcstructure(v); + expect(warnings).toEqual([]); + const readBack = await readMcstructure(bytes); + expect(readBack.warnings).toEqual([]); + expect(cellsOf(readBack.volume)).toEqual(cellsOf(v)); + + // Warnings for invalid bell attachment / facing, and dropped Bedrock states. + const badAtt = javaToBedrock("minecraft:bell[attachment=wall,facing=east,powered=false]"); + expect(badAtt.warnings).toEqual(["bell: unknown attachment=wall"]); + expect(badAtt.block.states.get("attachment")).toEqual({ kind: "string", value: "standing" }); + expect(badAtt.block.states.get("direction")).toEqual({ kind: "int", value: 3 }); + + const badDir = javaToBedrock("minecraft:bell[attachment=ceiling,facing=up,powered=true]"); + expect(badDir.warnings).toEqual(["bell: facing=up has no Bedrock direction"]); + expect(badDir.block.states.get("attachment")).toEqual({ kind: "string", value: "hanging" }); + expect(badDir.block.states.get("direction")).toEqual({ kind: "int", value: 2 }); + expect(badDir.block.states.get("toggle_bit")).toEqual({ kind: "byte", value: 1 }); + + const extraBedrock = bedrockToJava( + "minecraft:bell", + new Map([ + ["attachment", "side"], + ["direction", 1], + ["toggle_bit", 1], + ["extra_bit", 1], + ]), + ); + expect(extraBedrock.state).toBe( + "minecraft:bell[attachment=single_wall,facing=west,powered=true]", + ); + expect(extraBedrock.warnings).toEqual(["bell: dropped Bedrock state extra_bit=1"]); + }); + it("rejects files that are not structures", async () => { await expect(readMcstructure(Uint8Array.from([1, 2, 3]))).rejects.toThrow(CodecError); expect(() => writeMcstructure(new Volume())).toThrow(CodecError); diff --git a/packages/mcbuilder/src/build.ts b/packages/mcbuilder/src/build.ts index 5abe3a4..6ca4fb0 100644 --- a/packages/mcbuilder/src/build.ts +++ b/packages/mcbuilder/src/build.ts @@ -84,6 +84,15 @@ function ints(what: string, p: unknown): Point { return p as unknown as Point; } +let defaultMaxDimensions: Dims = [256, 256, 256]; + +/** @internal Override default `maxDimensions` for `new Build()` calls during script loading. */ +export function setDefaultMaxDimensions(dims: Dims): Dims { + const prev = defaultMaxDimensions; + defaultMaxDimensions = [...dims] as unknown as Dims; + return prev; +} + export class Build { private readonly seedValue: Seed; private sharedRng: Rng | null = null; @@ -93,7 +102,7 @@ export class Build { constructor(options: BuildOptions = {}) { this.seedValue = options.seed ?? null; - this.voxelGrid = new VoxelGrid(options.maxDimensions ?? [256, 256, 256]); + this.voxelGrid = new VoxelGrid(options.maxDimensions ?? defaultMaxDimensions); if (options.views !== undefined) this.setViews(options.views); } diff --git a/packages/mcbuilder/src/materials.ts b/packages/mcbuilder/src/materials.ts index 318dcb7..6fe605f 100644 --- a/packages/mcbuilder/src/materials.ts +++ b/packages/mcbuilder/src/materials.ts @@ -98,6 +98,8 @@ export interface PatchesOptions { scale?: number; /** Change this to get a different layout from the same palette. */ salt?: string; + /** Optional seed salting the patch noise lattice. */ + seed?: Seed; } /** @@ -110,11 +112,13 @@ export function patches( ): MaterialFn { const scale = options.scale ?? 4; const salt = options.salt ?? ""; + const hasSeed = options.seed !== undefined && options.seed !== null; + const seed = options.seed; const es = entries(palette); if (!(scale > 0)) throw new McbuilderError(`patches: scale must be > 0, got ${scale}`); const lattice = (ix: number, iy: number, iz: number): number => - unitHash("patches", salt, ix, iy, iz); + hasSeed ? unitHash("patches", salt, ix, iy, iz, seed) : unitHash("patches", salt, ix, iy, iz); const smooth = (t: number): number => t * t * (3 - 2 * t); const noise = (x: number, y: number, z: number): number => { diff --git a/packages/mcbuilder/src/node/assets.ts b/packages/mcbuilder/src/node/assets.ts index b1cbeb4..4ddd126 100644 --- a/packages/mcbuilder/src/node/assets.ts +++ b/packages/mcbuilder/src/node/assets.ts @@ -76,6 +76,42 @@ const exists = (p: string): Promise => () => false, ); +export const defaultCacheRoot = (home: string): string => join(home, ".cache", "mcbuilder"); + +/** + * Candidate version directories holding `minecraft-data.json`, `version.json`, and `client/`. + * When `assetsDir` is set: `[resolve(assetsDir), join(resolve(assetsDir), mcVersion)]` + * (direct version directory first, then `/`). + * When `assetsDir` is `null`: `[join(defaultCacheRoot(home), mcVersion)]`. + */ +export function assetVersionCandidates( + assetsDir: string | null, + mcVersion: string, + home: string, +): string[] { + if (assetsDir !== null) { + const base = resolve(assetsDir); + return [base, join(base, mcVersion)]; + } + return [join(defaultCacheRoot(home), mcVersion)]; +} + +/** + * Return the first candidate version directory where `join(dir, marker)` exists, + * or `null` if none match. + */ +export async function findAssetVersionDir( + assetsDir: string | null, + mcVersion: string, + home: string, + marker: string, +): Promise { + for (const dir of assetVersionCandidates(assetsDir, mcVersion, home)) { + if (await exists(join(dir, marker))) return dir; + } + return null; +} + /** True iff every extracted subtree is present and non-empty. */ async function clientCacheComplete(clientDir: string): Promise { for (const prefix of CLIENT_PREFIXES) { diff --git a/packages/mcbuilder/src/node/cli.ts b/packages/mcbuilder/src/node/cli.ts index 373d4d7..b0821d2 100644 --- a/packages/mcbuilder/src/node/cli.ts +++ b/packages/mcbuilder/src/node/cli.ts @@ -7,7 +7,7 @@ // mcbuild run