diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 43aa23c7..5c6123d6 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -1,7 +1,8 @@ # Third-party notices Snapmaker Studio is MIT licensed and contains no third-party source code beyond -its declared package dependencies. This file records the other things a project +its declared package dependencies and the vendored 3D viewport recorded under +"Code included in the app" below. This file records the other things a project can owe: **facts learned from other people's documentation**, and the boundary Studio keeps around licences it cannot mix with. @@ -10,6 +11,65 @@ under. This file is Studio holding itself to it. --- +## Code included in the app + +### three.js · MIT + +`three` 0.186.1, pinned exactly, is a declared dependency of the desktop app and is +bundled into the lazily loaded 3D project view (`desktop/package.json`). Its types come +from `@types/three` 0.186.0 (MIT, development only, not shipped). + +> The MIT License +> +> Copyright © 2010-2026 three.js authors +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of this +> software and associated documentation files (the "Software"), to deal in the Software +> without restriction, including without limitation the rights to use, copy, modify, merge, +> publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons +> to whom the Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or +> substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +> INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +> PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +> FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +> OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +> DEALINGS IN THE SOFTWARE. + +### SlicerX viewport · Apache-2.0 + +**Made possible by SlicerX** — + +The read-only 3D project view draws with the framework-free viewport from + (`packages/ui/viewport`, Copyright (C) 2026 The +SlicerX contributors), vendored at commit `edb521fe41306dd60d01bda8a0f6bf8aa54fcb29` under +`desktop/src/vendor/slicerx/`, together with the SXPV and plate type definitions it imports +from `packages/contracts`. Both are Apache-2.0; the licence text and SlicerX's own NOTICE are +kept beside the source (`LICENSE-APACHE`, `NOTICE`). **Modified files:** seven of the vendored +viewport files (`palette.ts`, `stage.ts`, `summary.ts`, `toolchanger.ts`, `toolpaths.ts`, `types.ts`, +`viewport.ts`) differ from upstream in exactly one line, the import path of the contracts module +(`'@slicerx/contracts'` became `'../contracts/index'`). Each carries a clearly marked "MODIFIED BY +SNAPMAKER STUDIO" notice after its unchanged upstream header. Every local change, with the upstream +blob id and current sha256 of each file, is listed in `desktop/src/vendor/slicerx/UPDATING.md`, and a +test (`project-scene/vendor.integrity.test.ts`) checks that nothing else differs. + +What this does and does not include: only the viewport and the contract types are vendored. +SlicerX's slicing engine, profiles, printer pictures and other AGPL-licensed data are **not** +part of Studio. The vendored viewport still contains SlicerX's editing code (move, rotate, +scale, paint, cut, sketch) because its entry class imports it; Studio never calls it. The 3D +view is read-only and reaches the viewport only through +`desktop/src/components/project-scene/defaultViewport.ts` and `readOnlyViewport.ts` (see `UPDATING.md`). + +The installed app shows these credits itself: the 3D view panel carries "Made possible by SlicerX" with the link above and a +"Licenses for the 3D view" section with SlicerX's NOTICE, the Apache License 2.0 text and the three.js MIT text +(`desktop/src/components/project-scene/credits.ts`). This file is not shipped by the installer. "SlicerX" and its logo are +trademarks of the SlicerX project; Studio is not affiliated with or endorsed by SlicerX. + +--- + ## Knowledge credited ### U1 Print Hub — · MIT diff --git a/desktop/src/api.ts b/desktop/src/api.ts index 86781c03..22d2c834 100644 --- a/desktop/src/api.ts +++ b/desktop/src/api.ts @@ -26,6 +26,11 @@ async function apiInfo(): Promise { cached = await invoke("get_api_info"); return cached; } +// The engine's address and token for lib/scene.ts, whose calls need an AbortSignal the fixed-shape wrappers here do not take. +export async function engineConnection(): Promise<{ base: string; token: string }> { + const { port, token } = await apiInfo(); + return { base: `http://127.0.0.1:${port}`, token }; +} // Dev/screenshot-harness only: a sample file path from ?file= instead of the native picker. function devFilePath(): string | null { if ((import.meta as any).env?.DEV) return new URLSearchParams(location.search).get("file"); diff --git a/desktop/src/components/project-scene/ProjectScenePanel.test.tsx b/desktop/src/components/project-scene/ProjectScenePanel.test.tsx new file mode 100644 index 00000000..0d2285da --- /dev/null +++ b/desktop/src/components/project-scene/ProjectScenePanel.test.tsx @@ -0,0 +1,172 @@ +// @vitest-environment jsdom +import { StrictMode } from "react"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { SceneError, type SceneV1 } from "@/lib/scene"; +import { makeFakeFactory } from "./fakeViewport"; +import { offBedScene, scene } from "./sceneFixtures"; + +const fake = vi.hoisted(() => ({ current: null as null | ReturnType })); +const loader = vi.hoisted(() => ({ loadScene: vi.fn() })); +vi.mock("@/lib/scene", async (original) => ({ ...(await original()), loadScene: loader.loadScene })); +vi.mock("./defaultViewport", () => ({ + createSceneViewer: (...args: Parameters["factory"]>) => fake.current!.factory(...args), +})); + +import ProjectScenePanel, { progressText } from "./ProjectScenePanel"; + +function resolveWith(s: SceneV1) { + loader.loadScene.mockImplementation(async () => s); +} + +beforeEach(() => { + fake.current = makeFakeFactory(); + loader.loadScene.mockReset(); +}); +afterEach(() => cleanup()); + +describe("ProjectScenePanel", () => { + it("lists objects as real buttons, shows the engine's note, and selecting an object selects it in the view", async () => { + resolveWith(offBedScene()); + render(); + const second = await screen.findByRole("button", { name: /^Object 2/ }); + expect(second.getAttribute("aria-pressed")).toBe("false"); + expect(second.textContent).toContain("Placement note"); + fireEvent.click(second); + expect(second.getAttribute("aria-pressed")).toBe("true"); + expect(fake.current!.stats.calls).toContain("setSelection:b1"); + expect(screen.getByText(/Placement: Object 2, right edge 4\.5 mm past the bed edge/)).toBeTruthy(); + fireEvent.click(second); + expect(second.getAttribute("aria-pressed")).toBe("false"); + }); + + it("camera buttons switch the view and the slope toggle shows the fixed label", async () => { + resolveWith(scene()); + render(); + await screen.findByRole("button", { name: "Top" }); + fireEvent.click(screen.getByRole("button", { name: "Top" })); + expect(fake.current!.stats.calls).toContain("view:top"); + const slope = screen.getByRole("button", { name: "Slope view" }); + expect(slope.getAttribute("aria-pressed")).toBe("false"); + fireEvent.click(slope); + expect(slope.getAttribute("aria-pressed")).toBe("true"); + expect(screen.getByText("Geometric slope visualization - review supports in Orca.")).toBeTruthy(); + }); + + it("offers no editing control anywhere in the panel", async () => { + resolveWith(offBedScene()); + render(); + await screen.findByRole("button", { name: "Top" }); + const names = screen.getAllByRole("button").map((b) => b.textContent ?? "").join("|"); + expect(names).not.toMatch(/move|rotate|scale|paint|cut|arrange|delete|remove|save|edit|sketch|extrude|lay on face/i); + expect(document.querySelectorAll("input, select, textarea")).toHaveLength(0); + }); + + it("without WebGL keeps the object list and notes and offers Retry", async () => { + let fail = true; + fake.current = makeFakeFactory({ failCreate: () => fail }); + resolveWith(offBedScene()); + render(); + const retry = await screen.findByRole("button", { name: /Retry 3D view/ }); + expect(screen.getByRole("button", { name: /Object 1/ })).toBeTruthy(); + expect(screen.getByText(/Placement: Object 2/)).toBeTruthy(); + expect((screen.getByRole("button", { name: "Top" }) as HTMLButtonElement).disabled).toBe(true); + fail = false; + fireEvent.click(retry); + await waitFor(() => expect(screen.queryByRole("button", { name: /Retry 3D view/ })).toBeNull()); + expect((screen.getByRole("button", { name: "Top" }) as HTMLButtonElement).disabled).toBe(false); + }); + + it("shows a lost graphics connection with Retry and a different canvas afterwards", async () => { + resolveWith(scene()); + const { container } = render(); + await screen.findByRole("button", { name: "Top" }); + const first = container.querySelector("canvas"); + act(() => fake.current!.emit("error", { message: "lost" })); + const retry = await screen.findByRole("button", { name: /Retry 3D view/ }); + expect(screen.getByText(/graphics connection was lost/)).toBeTruthy(); + expect(container.querySelectorAll("canvas")).toHaveLength(0); + fireEvent.click(retry); + await waitFor(() => expect(container.querySelector("canvas")).not.toBeNull()); + expect(container.querySelector("canvas")).not.toBe(first); + }); + + it("explains an engine refusal in plain words and Try again loads again", async () => { + loader.loadScene.mockRejectedValueOnce(new SceneError("LIMIT_EXCEEDED")); + render(); + expect((await screen.findByRole("alert")).textContent).toContain("larger than the 3D view can show"); + loader.loadScene.mockImplementation(async () => scene()); + fireEvent.click(screen.getByRole("button", { name: /Try again/ })); + await screen.findByRole("button", { name: "Top" }); + }); + + it("carries the SlicerX credit with its link and the license texts, and shows the legend only when highlighting is on", async () => { + resolveWith(offBedScene()); + const { unmount } = render(); + await screen.findByRole("button", { name: "Top" }); + expect(screen.getByText(/^Made possible by SlicerX: https:\/\/slicerx\.app\/support$/)).toBeTruthy(); + expect(screen.getByRole("region", { name: "Apache License 2.0 (SlicerX viewport)" }).textContent).toContain("Apache License"); + expect(screen.getByRole("region", { name: "SlicerX notice (Apache-2.0)" }).textContent).toContain("Made possible by SlicerX"); + expect(screen.getByRole("region", { name: "three.js (MIT)" }).textContent).toContain("Copyright"); + expect(screen.getByText(/Studio keeps a 0\.5 mm margin/)).toBeTruthy(); + unmount(); + resolveWith(scene({ plates: [{ id: "1", ui_number: 1, origin_mm: null }, { id: "2", ui_number: 2, origin_mm: null }] })); + render(); + await screen.findByRole("button", { name: "Top" }); + expect(screen.queryByText(/Studio keeps a 0\.5 mm margin/)).toBeNull(); + }); + + it("shows a timeout in plain words with Try again instead of staying on the starting message", async () => { + loader.loadScene.mockRejectedValueOnce(new SceneError("TIMEOUT")); + render(); + expect((await screen.findByRole("alert")).textContent).toContain("took too long"); + expect(screen.queryByText("Starting the 3D view")).toBeNull(); + expect(screen.getByRole("button", { name: /Try again/ })).toBeTruthy(); + }); + + it("shows the scene's limits in words when highlighting is off", async () => { + const s = offBedScene(); + s.limitations = [{ code: "MULTI_PLATE_PLACEMENT_UNCHECKED", target_ids: [] }]; + s.plates.push({ id: "2", ui_number: 2, origin_mm: null }); + resolveWith(s); + render(); + await screen.findByRole("button", { name: "Top" }); + expect(screen.getAllByText(/more than one plate/).length).toBeGreaterThan(0); + expect(screen.queryByText("Placement note")).toBeNull(); + }); + + it("works under StrictMode with exactly one live canvas, and unmount removes it", async () => { + resolveWith(scene()); + const { container, unmount } = render(); + await screen.findByRole("button", { name: "Top" }); + expect(container.querySelectorAll("canvas")).toHaveLength(1); + expect(fake.current!.stats.liveContexts).toBe(1); + unmount(); + expect(fake.current!.stats.liveContexts).toBe(0); + expect(fake.current!.stats.liveListeners).toBe(0); + expect(document.querySelectorAll("canvas")).toHaveLength(0); + }); + + it("changing the path loads the new project and drops the old canvas", async () => { + resolveWith(scene()); + const { container, rerender } = render(); + await screen.findByRole("button", { name: "Top" }); + const first = container.querySelector("canvas"); + rerender(); + await waitFor(() => expect(container.querySelector("canvas")).not.toBe(first)); + expect(container.querySelectorAll("canvas")).toHaveLength(1); + expect(loader.loadScene).toHaveBeenCalledTimes(2); + expect(loader.loadScene.mock.calls.map((c) => c[0])).toEqual(["a.3mf", "b.3mf"]); + }); +}); + +describe("progressText", () => { + it("speaks plainly", () => { + expect(progressText(null)).toBe("Starting the 3D view"); + expect(progressText({ state: "queued", stage: null, completed: null, total: null })).toBe("Waiting for the engine"); + expect(progressText({ state: "running", stage: "parsing", completed: 1, total: 4 })).toBe("Reading the model (25%)"); + // Never 100%: at completed == total the figure is dropped, and a near-complete one stops at 99. + expect(progressText({ state: "running", stage: "encoding", completed: 4, total: 4 })).toBe("Preparing the view"); + expect(progressText({ state: "running", stage: "encoding", completed: 999, total: 1000 })).toBe("Preparing the view (99%)"); + }); +}); diff --git a/desktop/src/components/project-scene/ProjectScenePanel.tsx b/desktop/src/components/project-scene/ProjectScenePanel.tsx new file mode 100644 index 00000000..7421fe6e --- /dev/null +++ b/desktop/src/components/project-scene/ProjectScenePanel.tsx @@ -0,0 +1,219 @@ +import { useEffect, useRef, useState } from "react"; +import { Loader2, RotateCw } from "lucide-react"; +import { Card, CardContent } from "@/components/ui/card"; +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { loadScene, sceneErrorText } from "@/lib/scene"; +import { useTheme } from "@/store/theme"; +import { createSceneViewer } from "./defaultViewport"; +import { CAMERA_PRESETS, SLOPE_LABEL } from "./readOnlyViewport"; +import { CREDIT_SECTIONS, SLICERX_CREDIT } from "./credits"; +import { SceneController, type ViewerState } from "./sceneController"; + +const STAGE_TEXT: Record = { + reading: "Reading the file", + parsing: "Reading the model", + encoding: "Preparing the view", +}; + +export function progressText(p: ViewerState["progress"]): string { + if (!p) return "Starting the 3D view"; + if (p.state === "queued") return "Waiting for the engine"; + const stage = p.stage ? STAGE_TEXT[p.stage] : "Working"; + // Never "100%": the job is still working until it reports done, so the figure stops at 99 and disappears when complete. + return p.completed !== null && p.total && p.completed < p.total ? `${stage} (${Math.min(99, Math.round((p.completed / p.total) * 100))}%)` : stage; +} + +const TONE_TEXT = { placement: "Placement note", size: "Size note" } as const; +const TONE_CLASS = { + placement: "border-risk text-risk", + size: "border-repairable text-repairable", +} as const; + +const EMPTY: ViewerState = { + phase: "idle", progress: null, error: null, model: null, revision: null, graphics: "none", graphicsNote: null, + selectedId: null, preset: "bed", slope: false, +}; + +/** A read-only 3D view of the opened project, with the engine's placement and size notes. Never edits anything. */ +export default function ProjectScenePanel({ path, wide = false }: { path: string; wide?: boolean }) { + const theme = useTheme((s) => s.theme); + const themeRef = useRef(theme); + themeRef.current = theme; + const hostRef = useRef(null); + const controllerRef = useRef(null); + const [view, setView] = useState(EMPTY); + + // One controller per effect: StrictMode's mount, cleanup, mount makes two, and the first is fully disposed. + useEffect(() => { + const controller = new SceneController({ load: loadScene, viewportFactory: createSceneViewer, theme: themeRef.current }); + controllerRef.current = controller; + const off = controller.subscribe(() => setView(controller.getState())); + controller.setHost(hostRef.current); + controller.setPath(path); + return () => { + off(); + controller.dispose(); + if (controllerRef.current === controller) controllerRef.current = null; + }; + }, [path]); + + useEffect(() => { controllerRef.current?.setTheme(theme); }, [theme]); + + const c = () => controllerRef.current; + const model = view.model; + const noGraphics = view.graphics === "unavailable" || view.graphics === "lost"; + + return ( + + +
+

3D view of this project

+

+ Read-only: Studio never moves or changes your model here.{model ? ` ${model.summary}.` : ""} +

+
+ +
+
+
+
+ {view.phase === "loading" && ( +

+

+ )} + {view.phase === "failed" && view.error && ( +
+ {sceneErrorText(view.error)} + +
+ )} + {noGraphics && view.phase === "shown" && ( +
+

+ {view.graphics === "lost" + ? "The 3D drawing stopped (the graphics connection was lost)." + : "3D graphics are not available on this computer right now."}{" "} + The object list and notes still work. +

+ +
+ )} +
+ {view.graphicsNote &&

{view.graphicsNote}

} + +
+ {CAMERA_PRESETS.map((p) => ( + + ))} + +
+

{SLOPE_LABEL}

+
+ + {view.phase === "shown" && model && ( +
+
+

Objects

+ {model.objects.length === 0 ? ( +

This file lists no objects to show.

+ ) : ( +
    + {model.objects.map((o) => ( +
  • + +
  • + ))} +
+ )} +
+ +
+

Notes from Studio’s checks

+ {model.findings.length === 0 ? ( +

Studio made no placement or size notes for this project.

+ ) : ( +
    + {model.findings.map((f) => ( +
  • + {f.projectLevel ? ( +

    {f.text}

    + ) : ( + + )} +
  • + ))} +
+ )} + {model.gate.enabled && ( +

+ On the model, red marks a placement note and amber a size note. The bed outline turns orange for a placement note. + Studio keeps a {Number(model.marginMm.toFixed(2))} mm margin inside the bed edge. +

+ )} +
+ + {model.limitations.length > 0 && ( +
+

What this view cannot tell you

+
    + {model.limitations.map((t) =>
  • {t}
  • )} +
+
+ )} + {model.partial && ( +

Studio could not learn everything it needs from this file, so the view may be incomplete.

+ )} +
+ )} +
+
+

Review placement and supports in Snapmaker Orca.

+

{SLICERX_CREDIT}

+
+ Licenses for the 3D view +
+ {CREDIT_SECTIONS.map((s) => ( +
+

{s.title}

+
{s.text}
+
+ ))} +
+
+
+ + + ); +} diff --git a/desktop/src/components/project-scene/ProjectSceneSection.tsx b/desktop/src/components/project-scene/ProjectSceneSection.tsx new file mode 100644 index 00000000..14264b3f --- /dev/null +++ b/desktop/src/components/project-scene/ProjectSceneSection.tsx @@ -0,0 +1,30 @@ +import { Component, Suspense, lazy, type ReactNode } from "react"; +import { Card, CardContent } from "@/components/ui/card"; + +// The viewer (three.js and the vendored viewport) loads only when this section first renders, so it is not in the +// main bundle. +const ProjectScenePanel = lazy(() => import("./ProjectScenePanel")); + +class LoadBoundary extends Component<{ children: ReactNode }, { failed: boolean }> { + state = { failed: false }; + static getDerivedStateFromError() { return { failed: true }; } + render() { + if (!this.state.failed) return this.props.children; + return ( + + The 3D view could not be loaded. The rest of this page still works. + + ); + } +} + +/** Mount point used by the project pages. */ +export function ProjectSceneSection({ path, wide = false }: { path: string; wide?: boolean }) { + return ( + + Loading the 3D view}> + + + + ); +} diff --git a/desktop/src/components/project-scene/credits.ts b/desktop/src/components/project-scene/credits.ts new file mode 100644 index 00000000..0760f866 --- /dev/null +++ b/desktop/src/components/project-scene/credits.ts @@ -0,0 +1,36 @@ +// The licence and credit texts that must travel with the 3D view. They are bundled into the app (this file is part of the +// lazily loaded 3D view chunk) and shown in the panel, so every installed copy carries them without any installer change. +// The two vendored files are imported as plain text; this is the only file besides the facade and the adapter that may +// name the vendor tree, and only for these two assets (see readOnly.guard.test.ts). +import slicerxNotice from "@/vendor/slicerx/NOTICE?raw"; +import apacheLicense from "@/vendor/slicerx/LICENSE-APACHE?raw"; + +export const SLICERX_CREDIT = "Made possible by SlicerX: https://slicerx.app/support"; + +export const THREE_LICENSE = `The MIT License + +Copyright © 2010-2026 three.js authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE.`; + +export const CREDIT_SECTIONS: { title: string; text: string }[] = [ + { title: "SlicerX notice (Apache-2.0)", text: slicerxNotice }, + { title: "Apache License 2.0 (SlicerX viewport)", text: apacheLicense }, + { title: "three.js (MIT)", text: THREE_LICENSE }, +]; diff --git a/desktop/src/components/project-scene/defaultViewport.test.ts b/desktop/src/components/project-scene/defaultViewport.test.ts new file mode 100644 index 00000000..f3601c9e --- /dev/null +++ b/desktop/src/components/project-scene/defaultViewport.test.ts @@ -0,0 +1,76 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +// The vendored viewport is replaced by a stand-in that records what is created and what is called. This file proves what +// the real adapter (defaultViewport.ts) does with it: tool fixed to probe, clean-up when start-up fails half way. +const fake = vi.hoisted(() => ({ + log: [] as string[], live: 0, failOn: null as null | string, failCreate: false, + handlers: new Map void>>(), +})); + +vi.mock("@/vendor/slicerx/entry", () => ({ + createViewport: () => { + if (fake.failCreate) throw new Error("no webgl"); + fake.live++; + fake.log.push("create"); + const guard = (name: string) => { if (fake.failOn === name) throw new Error(`${name} failed`); }; + const rec = (name: string) => (..._a: unknown[]) => { fake.log.push(name); guard(name); }; + return { + setTool: rec("setTool"), setTheme: rec("setTheme"), setPlate: rec("setPlate"), setSelection: rec("setSelection"), + view: rec("view"), zoomBy: rec("zoomBy"), setRenderMode: rec("setRenderMode"), setOverhangAngle: rec("setOverhangAngle"), + setGuides: rec("setGuides"), setBedAlert: rec("setBedAlert"), + on: (event: string, cb: (p: never) => void) => { + guard(`on:${event}`); + let set = fake.handlers.get(event); + if (!set) fake.handlers.set(event, (set = new Set())); + set.add(cb); + fake.log.push(`on:${event}`); + return () => { set!.delete(cb); }; + }, + dispose: () => { fake.live--; fake.log.push("dispose"); }, + }; + }, +})); + +import { createSceneViewer } from "./defaultViewport"; +import { ViewerUnavailableError } from "./readOnlyViewport"; + +const canvas = {} as HTMLCanvasElement; +const listeners = () => [...fake.handlers.values()].reduce((n, s) => n + s.size, 0); + +beforeEach(() => { fake.log.length = 0; fake.live = 0; fake.failOn = null; fake.failCreate = false; fake.handlers.clear(); }); + +describe("createSceneViewer (the only adapter to the vendored viewport)", () => { + it("sets the tool to probe exactly once, before anything else is called, and hands out no setTool", () => { + const viewer = createSceneViewer(canvas, { theme: "dark" }); + expect(fake.log.filter((l) => l === "setTool")).toHaveLength(1); + expect(fake.log.indexOf("setTool")).toBe(1); + expect(Object.keys(viewer)).not.toContain("setTool"); + expect(Object.keys(viewer)).not.toContain("on"); + viewer.dispose(); + expect(fake.live).toBe(0); + }); + + it("reports unavailable graphics when the viewport cannot be created", () => { + fake.failCreate = true; + expect(() => createSceneViewer(canvas, { theme: "dark" })).toThrow(ViewerUnavailableError); + expect(fake.live).toBe(0); + }); + + it.each(["setTool", "setTheme", "on:pick", "on:select", "on:error", "on:degrade"])( + "disposes the partly built viewport when %s throws after it was created", + (name) => { + fake.failOn = name; + expect(() => createSceneViewer(canvas, { theme: "light" })).toThrow(); + expect(fake.log).toContain("create"); + expect(fake.log.filter((l) => l === "dispose")).toHaveLength(1); + expect(fake.live).toBe(0); + }, + ); + + it("leaves no registered viewport listener behind after a normal dispose", () => { + const viewer = createSceneViewer(canvas, { theme: "dark" }); + expect(listeners()).toBe(4); + viewer.dispose(); + expect(listeners()).toBe(0); + }); +}); diff --git a/desktop/src/components/project-scene/defaultViewport.ts b/desktop/src/components/project-scene/defaultViewport.ts new file mode 100644 index 00000000..7ec9e3b0 --- /dev/null +++ b/desktop/src/components/project-scene/defaultViewport.ts @@ -0,0 +1,44 @@ +// The one place that imports the vendored viewport at run time, and the only place that touches its tool. Only the lazily +// loaded panel imports this file, so three.js and the viewport stay out of the main bundle. The viewport lives in a closure +// here: callers get a `ReadOnlyViewport` (no setTool, no generic `on`, no handle). +import { createViewport, type Viewport } from "@/vendor/slicerx/entry"; +import { ViewerUnavailableError, createReadOnlyViewport, type InspectionPort, type SceneViewerFactory } from "./readOnlyViewport"; + +const LABEL = "3D view of the project. Drag to turn the view, scroll to zoom."; + +function portOf(raw: Viewport): InspectionPort { + return { + setPlate: (plate, opts) => raw.setPlate(plate, opts), + setSelection: (ids) => raw.setSelection(ids), + view: (preset, opts) => raw.view(preset, opts), + zoomBy: (factor, opts) => raw.zoomBy(factor, opts), + setRenderMode: (mode) => raw.setRenderMode(mode), + setOverhangAngle: (deg) => raw.setOverhangAngle(deg), + setTheme: (theme) => raw.setTheme(theme), + setGuides: (guides) => raw.setGuides(guides), + setBedAlert: (on) => raw.setBedAlert(on), + dispose: () => raw.dispose(), + onPick: (handler) => raw.on("pick", (e) => handler(e.objectId)), + onSelect: (handler) => raw.on("select", (e) => handler(e.ids)), + onError: (handler) => raw.on("error", (e) => handler(e.message)), + onDegrade: (handler) => raw.on("degrade", (e) => handler(e.message)), + }; +} + +export const createSceneViewer: SceneViewerFactory = (canvas, { theme }) => { + let raw: Viewport; + try { + raw = createViewport(canvas, { label: LABEL, quality: "balanced" }); + } catch { + throw new ViewerUnavailableError(); + } + try { + // "probe": a click reports what is under the cursor and moves, rotates, scales and paints nothing. + raw.setTool("probe"); + return createReadOnlyViewport(portOf(raw), theme); + } catch (error) { + // The renderer, its listeners and its GL context exist by now: release them rather than leave them behind. + try { raw.dispose(); } catch { /* nothing more to do */ } + throw error; + } +}; diff --git a/desktop/src/components/project-scene/fakeViewport.ts b/desktop/src/components/project-scene/fakeViewport.ts new file mode 100644 index 00000000..a96e21ce --- /dev/null +++ b/desktop/src/components/project-scene/fakeViewport.ts @@ -0,0 +1,71 @@ +// A stand-in for the vendored viewport, used by tests. `makeFakePort` is the inspection port the real adapter builds; +// `makeFakeFactory` wraps it in the real facade. Every call is recorded, so tests can prove what was (not) reached, and +// "contexts" and listeners are counted the way the real viewport acquires them. +import { createReadOnlyViewport, type InspectionPort, type SceneViewerFactory } from "./readOnlyViewport"; + +export type FakeStats = { + created: number; disposed: number; liveContexts: number; peakContexts: number; liveListeners: number; disposedDetached: number; + calls: string[]; +}; + +type Handler = (payload: never) => void; + +export function makeFakePort(canvas: HTMLCanvasElement, stats: FakeStats, handlers: Map>): InspectionPort { + stats.created++; + stats.liveContexts++; + stats.peakContexts = Math.max(stats.peakContexts, stats.liveContexts); + // The real viewport adds pointer listeners to its canvas; mimic that so leaks are visible. + const onDown = () => undefined; + canvas.addEventListener("pointerdown", onDown); + stats.liveListeners++; + let disposed = false; + const rec = (name: string) => { stats.calls.push(name); }; + const sub = (event: string, map: (p: never) => unknown, cb: (v: never) => void) => { + const handler: Handler = (p) => cb(map(p) as never); + let set = handlers.get(event); + if (!set) handlers.set(event, (set = new Set())); + set.add(handler); + stats.liveListeners++; + return () => { if (set!.delete(handler)) stats.liveListeners--; }; + }; + const port = { + setPlate: () => rec("setPlate"), + setSelection: (ids: string[]) => rec(`setSelection:${ids.join(",")}`), + view: (p: string) => rec(`view:${p}`), + zoomBy: () => rec("zoomBy"), + setRenderMode: (m: string) => rec(`setRenderMode:${m}`), + setOverhangAngle: () => rec("setOverhangAngle"), + setTheme: () => rec("setTheme"), + setGuides: () => rec("setGuides"), + setBedAlert: () => rec("setBedAlert"), + onPick: (cb: (id: string | null) => void) => sub("pick", (p: { objectId: string | null }) => p.objectId, cb), + onSelect: (cb: (ids: string[]) => void) => sub("select", (p: { ids: string[] }) => p.ids, cb), + onError: (cb: (m: string) => void) => sub("error", (p: { message: string }) => p.message, cb), + onDegrade: (cb: (m: string) => void) => sub("degrade", (p: { message: string }) => p.message, cb), + dispose: () => { + if (disposed) return; + disposed = true; + stats.disposed++; + if (!canvas.isConnected) stats.disposedDetached++; + stats.liveContexts--; + canvas.removeEventListener("pointerdown", onDown); + stats.liveListeners--; + for (const set of handlers.values()) stats.liveListeners -= set.size; + handlers.clear(); + }, + }; + return port as unknown as InspectionPort; +} + +export function makeFakeFactory(opts: { failCreate?: () => boolean } = {}) { + const stats: FakeStats = { + created: 0, disposed: 0, liveContexts: 0, peakContexts: 0, liveListeners: 0, disposedDetached: 0, calls: [], + }; + const handlers = new Map>(); + const emit = (event: string, payload: unknown) => { for (const h of [...(handlers.get(event) ?? [])]) (h as (p: unknown) => void)(payload); }; + const factory: SceneViewerFactory = (canvas, { theme }) => { + if (opts.failCreate?.()) throw new Error("no webgl"); + return createReadOnlyViewport(makeFakePort(canvas, stats, handlers), theme); + }; + return { factory, stats, emit }; +} diff --git a/desktop/src/components/project-scene/readOnly.guard.test.ts b/desktop/src/components/project-scene/readOnly.guard.test.ts new file mode 100644 index 00000000..7b5a2c9e --- /dev/null +++ b/desktop/src/components/project-scene/readOnly.guard.test.ts @@ -0,0 +1,179 @@ +/// +import { describe, expect, it } from "vitest"; + +// The vendored viewport still contains editing code (move, rotate, scale, paint, cut, sketch) because its entry class +// imports it. These checks prove Studio's own code cannot reach any of it. They scan ALL of src/ (not just this folder), +// so a bypass dropped into any component, route, store or lib file fails the build. +// +// What is enforced, and where: +// * the vendor tree is named only by three files: readOnlyViewport.ts (a type import), defaultViewport.ts (the value +// import of the entry file) and credits.ts (the NOTICE and LICENSE-APACHE texts, imported as plain text). No other file may mention it in any import, re-export, dynamic import() or string; +// * every dynamic import() must have a plain string-literal argument; +// * editing members (setTool, setCutPlane, ...) may not appear anywhere in src/ outside tests, except one literal +// `setTool("probe")` in defaultViewport.ts; +// * createViewport may appear only in defaultViewport.ts. +// Limit: this is a source scan. It cannot see a member name built at run time ("set" + "Tool"); code review covers that. +const files = import.meta.glob(["../../**/*.ts", "../../**/*.tsx", "!../../vendor/**", "!../../**/*.test.ts", "!../../**/*.test.tsx"], { + query: "?raw", import: "default", eager: true, +}) as Record; +const entry = import.meta.glob("../../vendor/slicerx/entry.ts", { query: "?raw", import: "default", eager: true }) as Record; + +// Vite names a file by its shortest path from this folder ("./x.ts", "../shell/y.tsx", "../../z.ts"); make them src-relative. +const norm = (p: string) => new URL(p, "file:///src/components/project-scene/").pathname.replace(/^\/src\//, ""); +const real: Record = Object.fromEntries(Object.entries(files).map(([k, v]) => [norm(k), v])); +const FACADE = "components/project-scene/readOnlyViewport.ts"; +const ADAPTER = "components/project-scene/defaultViewport.ts"; +const CREDITS = "components/project-scene/credits.ts"; +const CREDIT_ASSETS = ["@/vendor/slicerx/NOTICE?raw", "@/vendor/slicerx/LICENSE-APACHE?raw"]; + +const code = (s: string) => s.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, ""); + +const EDITING = [ + "setTool", "setPaintSettings", "setPaintData", "setPaintColors", "applyPaintEdits", "paintHeightRange", "performGapFill", + "setCutPlane", "setTransforms", "setPush", "setSketch", "setSketchCursor", "setBrimEars", "setBrimHoverRadius", "setDimensions", + "setPartStyle", "setEdgePreview", "setGapLines", "setRotateSpace", "setControls", "setProbeHover", "setProbeFaces", +]; + +/** Every way the scan knows to fail a file set. Returns readable violations; an empty list means the set is clean. */ +function scan(set: Record): string[] { + const out: string[] = []; + for (const [file, raw] of Object.entries(set)) { + const text = code(raw); + // 1. any quoted string that names the vendor tree or the SlicerX package. + for (const m of text.matchAll(/["'`]([^"'`\n]*)["'`]/g)) { + const spec = m[1]; + // Prose and URLs are not module specifiers (which never contain a space). + if (/^https?:/i.test(spec) || /\s/.test(spec) || !spec.includes("/") || !(/(^|\/)vendor(\/|$)/.test(spec) || /slicerx/i.test(spec))) continue; + const ok = ((file === FACADE || file === ADAPTER) && spec === "@/vendor/slicerx/entry") || (file === CREDITS && CREDIT_ASSETS.includes(spec)); + if (!ok) out.push(`${file}: names the vendor tree ("${spec}")`); + } + if (file === FACADE && /^import\s+(?!type\b)[^;]*["']@\/vendor\/slicerx\/entry["']/m.test(text)) out.push(`${file}: value import of the vendor entry`); + if (file === ADAPTER && !/^import \{ createViewport, type Viewport \} from "@\/vendor\/slicerx\/entry";$/m.test(text)) out.push(`${file}: unexpected vendor import form`); + // 2. dynamic import() needs a literal argument. + for (const m of text.matchAll(/\bimport\s*\(\s*([^)]*)\)/g)) { + if (!/^["'][^"'\n]*["']\s*$/.test(m[1].trim())) out.push(`${file}: dynamic import() with a computed argument`); + } + // 3. editing members, in any spelling that keeps the name (call, bracket access, destructuring, alias, string). + for (const name of EDITING) { + if (!text.includes(name)) continue; + if (name === "setTool" && file === ADAPTER) continue; // counted below + out.push(`${file}: mentions ${name}`); + } + // "arrange" is also ordinary English in the app's copy, so only member-style uses count: .arrange(, ["arrange"], { arrange } = x. + if (/\.\s*arrange\s*\(|\[\s*["'`]arrange["'`]\s*\]|\{[^{}]*\barrange\b[^{}]*\}\s*=[^=]/.test(text)) out.push(`${file}: mentions arrange`); + // 4. the raw factory. + if (text.includes("createViewport") && file !== ADAPTER) out.push(`${file}: mentions createViewport`); + } + const adapter = set[ADAPTER]; + if (adapter !== undefined) { + // In the adapter createViewport may appear exactly twice: in its import, and as ONE call expression. Re-exports, aliases, + // a second call or passing it on as a value all add an occurrence and fail. + const words = [...code(adapter).matchAll(/\bcreateViewport\b/g)].length; + const calls = [...code(adapter).matchAll(/\bcreateViewport\s*\(/g)].length; + if (words !== 2 || calls !== 1) out.push(`${ADAPTER}: createViewport must appear only in its import and in one call`); + const tools = [...code(adapter).matchAll(/setTool[^\n]*/g)].map((m) => m[0]); + if (tools.length !== 1 || !/^setTool\("probe"\);?$/.test(tools[0].trim())) out.push(`${ADAPTER}: setTool must appear once, as setTool("probe")`); + } + return out; +} + +describe("read-only guard (scans all of src/)", () => { + it("scans the files it means to", () => { + const names = Object.keys(real); + expect(names).toEqual(expect.arrayContaining([FACADE, ADAPTER, "api.ts", "App.tsx", "routes/DesignInsights.tsx", "components/project-scene/sceneController.ts"])); + expect(names.some((n) => n.startsWith("vendor/"))).toBe(false); + expect(names.some((n) => /\.test\.tsx?$/.test(n))).toBe(false); + expect(names.length).toBeGreaterThan(60); + expect(Object.keys(entry)).toHaveLength(1); + }); + + it("the real source tree is clean", () => { + expect(scan(real)).toEqual([]); + }); + + it("the entry file re-exports the factory and types, nothing editing", () => { + const text = code(Object.values(entry)[0]); + expect(text).toMatch(/export \{ createViewport \}/); + expect(text).not.toMatch(/gizmo|paint|cut|cadtools|rings|scaling|sketch|arrange|faces/i); + }); + + it("the facade's pass-through list names only inspection members", () => { + const text = code(real[FACADE]); + const block = /InspectionCalls\s*=\s*Pick<\s*Viewport,([\s\S]*?)>;/.exec(text)![1]; + const names = [...block.matchAll(/"(\w+)"/g)].map((m) => m[1]).sort(); + expect(names).toEqual([ + "dispose", "setBedAlert", "setGuides", "setOverhangAngle", "setPlate", "setRenderMode", "setSelection", "setTheme", "view", "zoomBy", + ]); + }); + + it("the view's code writes no file and calls no desktop shell command", () => { + const own = Object.entries(real).filter(([k]) => k.startsWith("components/project-scene/")).map(([, v]) => code(v)).join("\n"); + expect(own).not.toMatch(/@tauri-apps|from\s+["']@\/api["']|writeFile|createWritable|showSaveFilePicker|localStorage|indexedDB|XMLHttpRequest|\bfetch\(/); + }); +}); + +describe("the guard fails when a bypass is added (mutation tests)", () => { + const base = real; + const bypasses: [string, string, string][] = [ + ["a file in project-scene/sub/ imports the factory", "components/project-scene/sub/bypass.ts", + 'import { createViewport } from "@/vendor/slicerx/entry";\nexport const v = createViewport(document.createElement("canvas"));\nv.setTool("move");\n'], + ["a route imports the vendor entry", "routes/Bypass.tsx", + 'import { createViewport as cv } from "@/vendor/slicerx/entry";\nexport default function B() { return cv ? null : null; }\n'], + ["a route reaches into the viewport source by relative path", "routes/Bypass2.tsx", + 'import { CutGizmo } from "../vendor/slicerx/viewport/cutplane";\nexport const g = CutGizmo;\n'], + ["a dynamic import of the vendor tree", "routes/Bypass3.tsx", + 'export const load = () => import("@/vendor/slicerx/viewport/viewport");\n'], + ["a computed dynamic import", "lib/bypass.ts", 'const p = "@/ven" + "dor/slicerx/entry";\nexport const load = () => import(p);\n'], + ["credits.ts importing more than its two text assets", "components/project-scene/credits.ts", 'import x from "@/vendor/slicerx/viewport/viewport?raw";\nexport const y = x;\n'], + ["a re-export of the vendor entry", "lib/reexport.ts", 'export * from "@/vendor/slicerx/entry";\n'], + ["bracket access to setTool", "lib/bracket.ts", 'export const f = (v: any) => v["setTool"]("select");\n'], + ["destructuring an editing member", "lib/destructure.ts", "export const f = (v: any) => { const { setCutPlane } = v; return setCutPlane; };\n"], + ["an editing member alias", "lib/alias.ts", "export const f = (v: any) => { const t = v.setTransforms; return t; };\n"], + ["arrange", "lib/arr.ts", "export const f = (v: any) => v.arrange();\n"], + ]; + for (const [label, path, source] of bypasses) { + it(`fails when ${label}`, () => { + const violations = scan({ ...base, [path]: source }); + expect(violations.length).toBeGreaterThan(0); + expect(violations.join("\n")).toContain(path); + }); + } + + it("fails when the facade value-imports the vendor entry", () => { + const mutated = real[FACADE].replace('import type { Viewport } from "@/vendor/slicerx/entry";', 'import { Viewport } from "@/vendor/slicerx/entry";'); + expect(mutated).not.toBe(real[FACADE]); + expect(scan({ ...base, [FACADE]: mutated }).join("\n")).toContain("value import"); + }); + + it("fails when the adapter sets another tool, or the probe tool twice", () => { + const other = real[ADAPTER].replace('raw.setTool("probe");', 'raw.setTool("select");'); + expect(scan({ ...base, [ADAPTER]: other }).join("\n")).toContain("setTool must appear once"); + const twice = real[ADAPTER].replace('raw.setTool("probe");', 'raw.setTool("probe");\n raw.setTool("probe");'); + expect(scan({ ...base, [ADAPTER]: twice }).join("\n")).toContain("setTool must appear once"); + }); + + it("fails when the adapter re-exports, aliases or calls createViewport again", () => { + const base = real[ADAPTER]; + const variants = [ + `${base} +export { createViewport }; +`, + `${base} +export const make = createViewport; +`, + `${base} +const alias = createViewport; +export const other = alias; +`, + `${base} +export const second = (c: HTMLCanvasElement) => createViewport(c); +`, + ]; + for (const mutated of variants) expect(scan({ ...real, [ADAPTER]: mutated }).join(" ; ")).toContain("createViewport must appear only"); + }); + + it("fails when the adapter mentions an editing member other than the probe tool", () => { + const extra = real[ADAPTER].replace("dispose: () => raw.dispose(),", "dispose: () => raw.dispose(),\n setCutPlane: (c: never) => raw.setCutPlane(c),"); + expect(scan({ ...base, [ADAPTER]: extra }).join("\n")).toContain("setCutPlane"); + }); +}); diff --git a/desktop/src/components/project-scene/readOnlyViewport.test.ts b/desktop/src/components/project-scene/readOnlyViewport.test.ts new file mode 100644 index 00000000..57bf3e02 --- /dev/null +++ b/desktop/src/components/project-scene/readOnlyViewport.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it } from "vitest"; +import { createReadOnlyViewport, type InspectionPort, type ReadOnlyViewport } from "./readOnlyViewport"; +import { makeFakeFactory, makeFakePort, type FakeStats } from "./fakeViewport"; +import { buildModel, buildViewScene } from "./sceneModel"; +import { offBedScene } from "./sceneFixtures"; + +const canvas = () => ({ addEventListener() {}, removeEventListener() {}, isConnected: true }) as unknown as HTMLCanvasElement; +const fresh = () => { + const stats: FakeStats = { created: 0, disposed: 0, liveContexts: 0, peakContexts: 0, liveListeners: 0, disposedDetached: 0, calls: [] }; + const handlers = new Map void>>(); + const emit = (event: string, payload: unknown) => { for (const h of [...(handlers.get(event) ?? [])]) (h as (p: unknown) => void)(payload); }; + return { stats, emit, port: makeFakePort(canvas(), stats, handlers) }; +}; + +describe("read-only viewport facade", () => { + it("calls only inspection members of the port", () => { + const { port, stats } = fresh(); + const vp = createReadOnlyViewport(port, "dark"); + const s = offBedScene(); + vp.show(buildViewScene(s, buildModel(s))); + vp.setSelected(["b1"]); + vp.setCamera("top"); + vp.setSlopeView(true); + vp.setSlopeView(false); + vp.setTheme("light"); + const editing = /paint|cut|scale|rotate|transform|arrange|sketch|push|brim|setTool|setPartStyle/i; + expect(stats.calls.filter((c) => editing.test(c))).toEqual([]); + expect(stats.calls).toContain("view:top"); + expect(stats.calls).toContain("setRenderMode:overhang"); + }); + + it("exposes exactly the inspection surface and never the port or the raw viewport", () => { + const vp = createReadOnlyViewport(fresh().port, "light"); + expect(Object.keys(vp).sort()).toEqual( + ["dispose", "onPick", "onSelect", "onTrouble", "setCamera", "setSelected", "setSlopeView", "setTheme", "show"], + ); + for (const value of Object.values(vp)) expect(typeof value).toBe("function"); + }); + + it("does not type-check any editing call, setTool or a generic subscription (type-level test)", () => { + const vp = null as unknown as ReadOnlyViewport; + const port = null as unknown as InspectionPort; + const never = () => { + // @ts-expect-error no setTool on the facade + vp.setTool("move"); + // @ts-expect-error no setPlate on the facade + vp.setPlate({}); + // @ts-expect-error no paint settings on the facade + vp.setPaintSettings({}); + // @ts-expect-error no cut plane on the facade + vp.setCutPlane(null); + // @ts-expect-error no transforms on the facade + vp.setTransforms({}); + // @ts-expect-error no arrange on the facade + vp.arrange(); + // @ts-expect-error no generic event subscription on the facade + vp.on("transform", () => undefined); + // @ts-expect-error no raw handle + vp.viewport; + // @ts-expect-error camera presets are a closed set + vp.setCamera("paint"); + // @ts-expect-error the port has no setTool either + port.setTool("move"); + // @ts-expect-error the port has no generic on + port.on("transform", () => undefined); + // @ts-expect-error the port has no editing calls + port.setCutPlane(null); + }; + expect(typeof never).toBe("function"); + }); + + it("forwards picks, selection clears and trouble, stops after unsubscribe, and disposes once", () => { + const { port, stats, emit } = fresh(); + const vp = createReadOnlyViewport(port, "dark"); + const picks: (string | null)[] = []; + const selects: string[][] = []; + const fatals: boolean[] = []; + const off = vp.onPick((id) => picks.push(id)); + vp.onSelect((ids) => selects.push(ids)); + vp.onTrouble((t) => fatals.push(t.fatal)); + emit("pick", { objectId: "b1" }); + emit("select", { ids: [] }); + emit("error", { message: "x" }); + emit("degrade", { message: "slow" }); + off(); + emit("pick", { objectId: "b0" }); + expect(picks).toEqual(["b1"]); + expect(selects).toEqual([[]]); + expect(fatals).toEqual([true, false]); + vp.dispose(); + vp.dispose(); + expect(stats.disposed).toBe(1); + expect(stats.liveListeners).toBe(0); + vp.setCamera("top"); + expect(stats.calls.filter((c) => c === "view:top")).toEqual([]); + }); + + it("the fake factory builds the same facade", () => { + const { factory, stats } = makeFakeFactory(); + const vp = factory(canvas(), { theme: "dark" }); + vp.dispose(); + expect(stats.created).toBe(1); + expect(stats.disposed).toBe(1); + }); +}); diff --git a/desktop/src/components/project-scene/readOnlyViewport.ts b/desktop/src/components/project-scene/readOnlyViewport.ts new file mode 100644 index 00000000..ae3023e8 --- /dev/null +++ b/desktop/src/components/project-scene/readOnlyViewport.ts @@ -0,0 +1,122 @@ +// The read-only facade. Studio code never holds the vendored SlicerX viewport. The vendored source ships editing code +// (move, rotate, scale, paint, cut, sketch) and that code is still in the bundle, so the boundary is structural: +// * defaultViewport.ts is the only file that imports the viewport's factory. It sets the tool to "probe" (a click only +// reports what is under the cursor), keeps the viewport inside a closure, and hands out an `InspectionPort`; +// * this file turns that port into `ReadOnlyViewport`. The port has no setTool and no generic `on`: only the named +// inspection calls below and four named subscriptions; +// * readOnly.guard.test.ts scans all of src/ so no other file can import the vendor tree or name an editing call. +import type { Viewport } from "@/vendor/slicerx/entry"; +import type { ViewScene } from "./sceneModel"; + +/** The members of the vendored viewport the port may forward. Editing members, setTool and the generic `on` are absent. */ +export type InspectionCalls = Pick< + Viewport, + "setPlate" | "setSelection" | "view" | "zoomBy" | "setRenderMode" | "setOverhangAngle" | "setTheme" | "setGuides" + | "setBedAlert" | "dispose" +>; +export type InspectionPort = InspectionCalls & { + onPick(handler: (objectId: string | null) => void): () => void; + onSelect(handler: (ids: string[]) => void): () => void; + onError(handler: (message: string) => void): () => void; + onDegrade(handler: (message: string) => void): () => void; +}; +/** Builds a read-only viewer on a fresh canvas. Throws if graphics cannot start; never leaves a half-built viewer behind. */ +export type SceneViewerFactory = (canvas: HTMLCanvasElement, options: { theme: ThemeMode }) => ReadOnlyViewport; + +export type CameraPreset = "iso" | "top" | "front" | "back" | "left" | "right" | "fit" | "bed"; +export const CAMERA_PRESETS: { id: CameraPreset; label: string }[] = [ + { id: "iso", label: "Corner view" }, + { id: "top", label: "Top" }, + { id: "front", label: "Front" }, + { id: "back", label: "Back" }, + { id: "left", label: "Left" }, + { id: "right", label: "Right" }, + { id: "bed", label: "Whole bed" }, + { id: "fit", label: "Zoom to objects" }, +]; + +/** Shown next to the slope toggle. The wording is fixed. */ +export const SLOPE_LABEL = "Geometric slope visualization - review supports in Orca."; +/** Degrees from vertical where the slope view starts to color a face. A display setting, not a print rule. */ +const SLOPE_ANGLE_DEG = 45; + +export type ThemeMode = "light" | "dark"; +const THEMES: Record = { + dark: { bgTop: "#253b47", bgBottom: "#101c25", bgGlow: "#2d4754", selection: "#bd93f9", floorGrid: "#8babb7" }, + light: { bgTop: "#eff4f6", bgBottom: "#d3e0e6", bgGlow: "#ffffff", selection: "#6d3fd0", floorGrid: "#6d8793" }, +}; + +export type Trouble = { message: string; fatal: boolean }; + +export interface ReadOnlyViewport { + show(scene: ViewScene): void; + setSelected(ids: string[]): void; + setCamera(preset: CameraPreset): void; + setSlopeView(on: boolean): void; + setTheme(mode: ThemeMode): void; + /** A click on an object reports its id, a click on empty space reports null. Returns an unsubscribe function. */ + onPick(handler: (id: string | null) => void): () => void; + /** The viewer cleared or changed its own selection (for example Escape). */ + onSelect(handler: (ids: string[]) => void): () => void; + /** Graphics trouble. `fatal` means the drawing surface is gone and the view must be rebuilt on a new canvas. */ + onTrouble(handler: (t: Trouble) => void): () => void; + dispose(): void; +} + +export class ViewerUnavailableError extends Error { + constructor() { + super("3D graphics are not available"); + this.name = "ViewerUnavailableError"; + } +} + +export function createReadOnlyViewport(port: InspectionPort, theme: ThemeMode): ReadOnlyViewport { + port.setTheme({ scene: THEMES[theme] }); + const picks = new Set<(id: string | null) => void>(); + const selects = new Set<(ids: string[]) => void>(); + const troubles = new Set<(t: Trouble) => void>(); + const offs = [ + port.onPick((id) => { for (const h of [...picks]) h(id); }), + port.onSelect((ids) => { for (const h of [...selects]) h(ids); }), + port.onError((message) => { for (const h of [...troubles]) h({ message, fatal: true }); }), + port.onDegrade((message) => { for (const h of [...troubles]) h({ message, fatal: false }); }), + ]; + let disposed = false; + return { + show(scene) { + if (disposed) return; + port.setPlate({ + bed: scene.bed, + objects: scene.objects.map((o) => ({ + id: o.id, name: o.name, transform: o.transform, + parts: o.parts.map((p) => ({ name: p.name, positions: p.positions, indices: p.indices, color: p.color })), + })), + }); + port.setGuides(scene.marginLoop ? { loops: [{ points: scene.marginLoop, soft: true }] } : {}); + port.setBedAlert(scene.bedAlert); + port.view("bed", { animate: false }); + // An object placed past the bed edge has to stay in frame, so back the camera away a little. + if (scene.bedAlert) port.zoomBy(0.7, { animate: false }); + }, + setSelected(ids) { if (!disposed) port.setSelection([...ids]); }, + setCamera(preset) { if (!disposed) port.view(preset); }, + setSlopeView(on) { + if (disposed) return; + port.setRenderMode(on ? "overhang" : "studio"); + if (on) port.setOverhangAngle(SLOPE_ANGLE_DEG); + }, + setTheme(mode) { if (!disposed) port.setTheme({ scene: THEMES[mode] }); }, + onPick(handler) { picks.add(handler); return () => { picks.delete(handler); }; }, + onSelect(handler) { selects.add(handler); return () => { selects.delete(handler); }; }, + onTrouble(handler) { troubles.add(handler); return () => { troubles.delete(handler); }; }, + dispose() { + if (disposed) return; + disposed = true; + for (const off of offs) off(); + picks.clear(); + selects.clear(); + troubles.clear(); + port.dispose(); + }, + }; +} diff --git a/desktop/src/components/project-scene/sceneController.test.ts b/desktop/src/components/project-scene/sceneController.test.ts new file mode 100644 index 00000000..86c21128 --- /dev/null +++ b/desktop/src/components/project-scene/sceneController.test.ts @@ -0,0 +1,310 @@ +// @vitest-environment jsdom +import { beforeEach, describe, expect, it } from "vitest"; +import { SceneController, type ControllerDeps } from "./sceneController"; +import { makeFakeFactory } from "./fakeViewport"; +import { offBedScene, scene } from "./sceneFixtures"; +import { SceneError, loadScene, resetSceneSession, type LoadSceneOptions, type SceneTransport, type SceneV1 } from "@/lib/scene"; + +// The scene client keeps one session per app run; every test starts as at app start. +beforeEach(() => resetSceneSession()); + +function abortError() { const e = new Error("aborted"); e.name = "AbortError"; return e; } + +/** A loader the test settles by hand. Aborting rejects with an AbortError, like the real one. */ +function manualLoader() { + const pending: { path: string; opts: LoadSceneOptions; resolve: (s: SceneV1) => void; reject: (e: unknown) => void }[] = []; + const load: ControllerDeps["load"] = (path, opts) => new Promise((resolve, reject) => { + pending.push({ path, opts, resolve, reject }); + opts.signal.addEventListener("abort", () => reject(abortError()), { once: true }); + }); + return { load, pending }; +} +/** A loader that IGNORES abort, like a transport that cannot recall a request: every answer is delivered when the test says, however late. */ +function manualLoaderIgnoringAbort() { + const pending: { path: string; opts: LoadSceneOptions; resolve: (s: SceneV1) => void; reject: (e: unknown) => void }[] = []; + const load: ControllerDeps["load"] = (path, opts) => new Promise((resolve, reject) => { pending.push({ path, opts, resolve, reject }); }); + return { load, pending }; +} +const flush = () => new Promise((r) => setTimeout(r, 0)); +const host = () => { const el = document.createElement("div"); document.body.appendChild(el); return el; }; + +describe("SceneController", () => { + it("loads, shows the objects and builds one fresh canvas", async () => { + const { load, pending } = manualLoader(); + const { factory, stats } = makeFakeFactory(); + const c = new SceneController({ load, viewportFactory: factory, theme: "dark" }); + const el = host(); + c.setHost(el); + c.setPath("a.3mf"); + expect(c.getState().phase).toBe("loading"); + pending[0].resolve(offBedScene()); + await flush(); + expect(c.getState().phase).toBe("shown"); + expect(c.getState().graphics).toBe("working"); + expect(c.getState().model?.objects).toHaveLength(2); + expect(el.querySelectorAll("canvas")).toHaveLength(1); + expect(stats.created).toBe(1); + c.dispose(); + expect(el.querySelectorAll("canvas")).toHaveLength(0); + }); + + it("drops late successful answers from a loader that ignores abort: A, then B, then A again shows only the last A", async () => { + const { load, pending } = manualLoaderIgnoringAbort(); + const { factory, stats } = makeFakeFactory(); + const c = new SceneController({ load, viewportFactory: factory, theme: "dark" }); + c.setHost(host()); + c.setPath("a.3mf"); + c.setPath("b.3mf"); + c.setPath("a.3mf"); + expect(pending.map((p) => p.path)).toEqual(["a.3mf", "b.3mf", "a.3mf"]); + expect(pending[0].opts.signal.aborted).toBe(true); + expect(pending[1].opts.signal.aborted).toBe(true); + // The first two were aborted, but their (successful) answers still arrive, late and out of order. + pending[1].resolve(scene({ revision: "2".repeat(64) })); + pending[0].resolve(scene({ revision: "1".repeat(64) })); + await flush(); + expect(c.getState().phase).toBe("loading"); + expect(c.getState().revision).toBeNull(); + expect(stats.created).toBe(0); // neither stale answer built a viewer + pending[2].resolve(scene({ revision: "3".repeat(64) })); + await flush(); + expect(c.getState().revision).toBe("3".repeat(64)); + expect(stats.created).toBe(1); + // A stale failure arriving after the view is shown changes nothing either. + pending[0].reject(new SceneError("LIMIT_EXCEEDED")); + await flush(); + expect(c.getState()).toMatchObject({ phase: "shown", error: null }); + c.dispose(); + }); + + it("ignores a result that arrives after dispose and creates no canvas", async () => { + const { load, pending } = manualLoader(); + const { factory, stats } = makeFakeFactory(); + const c = new SceneController({ load, viewportFactory: factory, theme: "dark" }); + const el = host(); + c.setHost(el); + c.setPath("a.3mf"); + c.dispose(); + expect(pending[0].opts.signal.aborted).toBe(true); + pending[0].resolve(scene()); + await flush(); + expect(stats.created).toBe(0); + expect(el.querySelectorAll("canvas")).toHaveLength(0); + }); + + it("reports engine failures as codes the panel turns into plain words, and retry starts a new load", async () => { + const { load, pending } = manualLoader(); + const c = new SceneController({ load, viewportFactory: makeFakeFactory().factory, theme: "dark" }); + c.setHost(host()); + c.setPath("a.3mf"); + pending[0].reject(new SceneError("LIMIT_EXCEEDED")); + await flush(); + expect(c.getState()).toMatchObject({ phase: "failed", error: "LIMIT_EXCEEDED" }); + c.retryLoad(); + expect(c.getState().phase).toBe("loading"); + expect(pending).toHaveLength(2); + c.dispose(); + }); + + it("shows no graphics but keeps the lists when WebGL cannot start, and Retry builds a new canvas", async () => { + const { load, pending } = manualLoader(); + let fail = true; + const { factory, stats } = makeFakeFactory({ failCreate: () => fail }); + const c = new SceneController({ load, viewportFactory: factory, theme: "dark" }); + const el = host(); + c.setHost(el); + c.setPath("a.3mf"); + pending[0].resolve(offBedScene()); + await flush(); + expect(c.getState().graphics).toBe("unavailable"); + expect(c.getState().model?.objects).toHaveLength(2); + expect(el.querySelectorAll("canvas")).toHaveLength(0); + fail = false; + c.startGraphics(); + expect(c.getState().graphics).toBe("working"); + expect(stats.created).toBe(1); + c.dispose(); + }); + + it("moves to a lost state on a fatal graphics error, removes the canvas, and Retry uses a different canvas", async () => { + const { load, pending } = manualLoader(); + const { factory, stats, emit } = makeFakeFactory(); + const c = new SceneController({ load, viewportFactory: factory, theme: "dark" }); + const el = host(); + c.setHost(el); + c.setPath("a.3mf"); + pending[0].resolve(scene()); + await flush(); + const first = el.querySelector("canvas"); + emit("error", { message: "lost" }); + expect(c.getState().graphics).toBe("lost"); + expect(el.querySelectorAll("canvas")).toHaveLength(0); + expect(stats.liveContexts).toBe(0); + c.startGraphics(); + const second = el.querySelector("canvas"); + expect(second).not.toBe(first); + expect(stats.liveContexts).toBe(1); + c.dispose(); + }); + + it("selects the whole object from a pick and from the list", async () => { + const { load, pending } = manualLoader(); + const { factory, stats, emit } = makeFakeFactory(); + const c = new SceneController({ load, viewportFactory: factory, theme: "dark" }); + c.setHost(host()); + c.setPath("a.3mf"); + pending[0].resolve(scene()); + await flush(); + emit("pick", { objectId: "b1" }); + expect(c.getState().selectedId).toBe("b1"); + expect(stats.calls).toContain("setSelection:b1"); + c.selectFromList(null); + expect(c.getState().selectedId).toBeNull(); + c.setCamera("front"); + c.setSlope(true); + expect(stats.calls).toEqual(expect.arrayContaining(["view:front", "setRenderMode:overhang"])); + c.dispose(); + }); + + it("50 mount/dispose cycles leave no canvas, no listener and at most one live context", async () => { + const { factory, stats } = makeFakeFactory(); + const el = host(); + for (let i = 0; i < 50; i++) { + const c = new SceneController({ + load: async () => scene(), viewportFactory: factory, theme: i % 2 ? "light" : "dark", + }); + c.setHost(el); + c.setPath(`p${i}.3mf`); + await flush(); + expect(stats.liveContexts).toBeLessThanOrEqual(1); + c.dispose(); + } + expect(stats.created).toBe(50); + expect(stats.disposed).toBe(50); + expect(stats.liveContexts).toBe(0); + expect(stats.liveListeners).toBe(0); + expect(stats.peakContexts).toBe(1); + expect(el.querySelectorAll("canvas")).toHaveLength(0); + expect(document.querySelectorAll("canvas")).toHaveLength(0); + }); + + it("survives a StrictMode style start, dispose, start on the same host", async () => { + const { factory, stats } = makeFakeFactory(); + const el = host(); + const aborted: boolean[] = []; + const load: ControllerDeps["load"] = (_p, opts) => new Promise((resolve, reject) => { + opts.signal.addEventListener("abort", () => { aborted.push(true); reject(abortError()); }, { once: true }); + setTimeout(() => resolve(scene()), 5); + }); + const first = new SceneController({ load, viewportFactory: factory, theme: "dark" }); + first.setHost(el); + first.setPath("a.3mf"); + first.dispose(); + const second = new SceneController({ load, viewportFactory: factory, theme: "dark" }); + second.setHost(el); + second.setPath("a.3mf"); + await new Promise((r) => setTimeout(r, 20)); + expect(aborted).toEqual([true]); + expect(second.getState().phase).toBe("shown"); + expect(el.querySelectorAll("canvas")).toHaveLength(1); + expect(stats.liveContexts).toBe(1); + second.dispose(); + expect(stats.liveContexts).toBe(0); + }); + + it("disposes the viewer while its canvas is attached even when the host was removed first", async () => { + const { load, pending } = manualLoader(); + const { factory, stats } = makeFakeFactory(); + const c = new SceneController({ load, viewportFactory: factory, theme: "dark" }); + const el = host(); + c.setHost(el); + c.setPath("a.3mf"); + pending[0].resolve(scene()); + await flush(); + el.remove(); // what React does to a route's DOM before its passive cleanups run + c.dispose(); + expect(stats.disposed).toBe(1); + expect(stats.disposedDetached).toBe(0); + expect(document.querySelectorAll("canvas")).toHaveLength(0); + }); + + it("shows a failure with Retry when the engine never answers the start, and Retry works afterwards", async () => { + let answer = false; + const job = (state: string, revision: string | null) => ({ job_id: "j", request_id: "r", state, stage: null, completed: null, total: null, error: null, revision }); + const transport: SceneTransport = (route) => { + if (route === "session") return Promise.resolve({ status: 200, body: { client_id: "session-ctl", ttl_s: 900 } }); + if (route === "start") { + // Until `answer` is set it never answers, and ignores its signal. + return answer ? Promise.resolve({ status: 200, body: job("succeeded", "a".repeat(64)) }) : new Promise(() => undefined); + } + if (route === "result") return Promise.resolve({ status: 200, body: scene() }); + return Promise.resolve({ status: 200, body: job("cancelled", null) }); + }; + const { factory } = makeFakeFactory(); + const c = new SceneController({ + load: (path, opts) => loadScene(path, { ...opts, transport, startTimeoutMs: 30, sleep: () => Promise.resolve() }), + viewportFactory: factory, theme: "dark", + }); + c.setHost(host()); + c.setPath("a.3mf"); + expect(c.getState().phase).toBe("loading"); + await new Promise((r) => setTimeout(r, 120)); + expect(c.getState()).toMatchObject({ phase: "failed", error: "TIMEOUT" }); + answer = true; + c.retryLoad(); + await new Promise((r) => setTimeout(r, 60)); + expect(c.getState().phase).toBe("shown"); + c.dispose(); + }, 10000); + + it("reports a scene whose geometry cannot be decoded as a load problem, not as missing graphics", async () => { + const { load, pending } = manualLoader(); + const { factory, stats } = makeFakeFactory(); + const c = new SceneController({ load, viewportFactory: factory, theme: "dark" }); + c.setHost(host()); + c.setPath("a.3mf"); + const bad = scene(); + bad.meshes[0].positions_f32le_base64 = "AAAA"; // wrong size for the counts + pending[0].resolve(bad); + await flush(); + expect(c.getState()).toMatchObject({ phase: "failed", error: "BAD_RESPONSE" }); + expect(stats.created).toBe(0); + expect(document.querySelectorAll("canvas")).toHaveLength(0); + c.dispose(); + }); + + it("clears the list selection when the viewer clears its own (Escape), and ignores echoes of its own selections", async () => { + const { load, pending } = manualLoader(); + const { factory, emit } = makeFakeFactory(); + const c = new SceneController({ load, viewportFactory: factory, theme: "dark" }); + c.setHost(host()); + c.setPath("a.3mf"); + pending[0].resolve(scene()); + await flush(); + c.selectFromList("b1"); + emit("select", { ids: ["b1"] }); + expect(c.getState().selectedId).toBe("b1"); + emit("select", { ids: [] }); + expect(c.getState().selectedId).toBeNull(); + c.dispose(); + }); + + it("never throws out of dispose even if the viewport's dispose throws", async () => { + const { load, pending } = manualLoader(); + const { factory } = makeFakeFactory(); + const wrapped: ControllerDeps["viewportFactory"] = (canvas, o) => { + const vp = factory(canvas, o); + const original = vp.dispose; + vp.dispose = () => { original(); throw new Error("boom"); }; + return vp; + }; + const c = new SceneController({ load, viewportFactory: wrapped, theme: "dark" }); + const el = host(); + c.setHost(el); + c.setPath("a.3mf"); + pending[0].resolve(scene()); + await flush(); + expect(() => c.dispose()).not.toThrow(); + expect(el.querySelectorAll("canvas")).toHaveLength(0); + }); +}); diff --git a/desktop/src/components/project-scene/sceneController.ts b/desktop/src/components/project-scene/sceneController.ts new file mode 100644 index 00000000..2987aa55 --- /dev/null +++ b/desktop/src/components/project-scene/sceneController.ts @@ -0,0 +1,273 @@ +// Lifecycle of one project view: load the scene from the engine, build a FRESH canvas for it, and tear everything down +// again. Framework-free so it can be tested without React or WebGL. One controller per React effect. +// +// Rules this file keeps: +// * every load gets its own AbortController and a new generation number; a result from an older generation, path or +// controller is dropped (so A -> B -> A cannot show A's first answer for the second A); +// * disposing aborts the load, which also tells the engine to cancel (see loadScene); +// * a canvas is never reused: each graphics start creates a canvas, and dispose removes it; +// * late callbacks after dispose do nothing. +import { SceneError, isAbort, type LoadSceneOptions, type SceneErrorCode, type SceneProgress, type SceneV1 } from "@/lib/scene"; +import type { CameraPreset, ReadOnlyViewport, SceneViewerFactory, ThemeMode } from "./readOnlyViewport"; +import { buildModel, buildViewScene, type SceneModel, type ViewScene } from "./sceneModel"; + +export type GraphicsState = "none" | "working" | "unavailable" | "lost"; +export type ViewerState = { + phase: "idle" | "loading" | "shown" | "failed"; + progress: SceneProgress | null; + error: SceneErrorCode | null; + model: SceneModel | null; + revision: string | null; + graphics: GraphicsState; + /** A non-fatal note from the graphics layer, for example that it slowed itself down. */ + graphicsNote: string | null; + selectedId: string | null; + preset: CameraPreset; + slope: boolean; +}; + +export type ControllerDeps = { + load: (path: string, opts: LoadSceneOptions) => Promise; + viewportFactory: SceneViewerFactory; + theme: ThemeMode; +}; + +const INITIAL: ViewerState = { + phase: "idle", progress: null, error: null, model: null, revision: null, graphics: "none", graphicsNote: null, + selectedId: null, preset: "bed", slope: false, +}; + +export class SceneController { + private state: ViewerState = INITIAL; + private readonly listeners = new Set<() => void>(); + private disposed = false; + private generation = 0; + private path: string | null = null; + private abort: AbortController | null = null; + private scene: SceneV1 | null = null; + private viewScene: ViewScene | null = null; + private host: HTMLElement | null = null; + private canvas: HTMLCanvasElement | null = null; + private viewer: ReadOnlyViewport | null = null; + private offs: (() => void)[] = []; + private theme: ThemeMode; + + constructor(private readonly deps: ControllerDeps) { + this.theme = deps.theme; + } + + getState = (): ViewerState => this.state; + subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener); + return () => { this.listeners.delete(listener); }; + }; + + private set(patch: Partial): void { + if (this.disposed) return; + this.state = { ...this.state, ...patch }; + for (const l of [...this.listeners]) l(); + } + + /** Starts (or restarts) loading for a path. Any earlier load is cancelled first. */ + setPath(path: string | null): void { + if (this.disposed) return; + this.cancelLoad(); + this.teardownGraphics(); + this.scene = null; + this.viewScene = null; + this.path = path; + this.set({ ...INITIAL }); + if (!path) return; + const generation = ++this.generation; + const abort = new AbortController(); + this.abort = abort; + this.set({ phase: "loading" }); + this.deps.load(path, { + signal: abort.signal, + onProgress: (p) => { if (this.current(generation, path)) this.set({ progress: p }); }, + }).then( + (scene) => { + if (!this.current(generation, path)) return; + this.abort = null; + this.scene = scene; + let model: SceneModel; + try { + model = buildModel(scene); + } catch { + this.set({ phase: "failed", error: "BAD_RESPONSE" }); + return; + } + this.set({ phase: "shown", model, revision: scene.revision, progress: null }); + this.startGraphics(); + }, + (error: unknown) => { + if (!this.current(generation, path)) return; + this.abort = null; + if (isAbort(error)) return; + this.set({ phase: "failed", error: error instanceof SceneError ? error.code : "INTERNAL", progress: null }); + }, + ); + } + + private current(generation: number, path: string): boolean { + return !this.disposed && generation === this.generation && path === this.path; + } + + retryLoad(): void { + if (this.path) this.setPath(this.path); + } + + /** The element the canvas goes into. Passing null (or a new element) removes the current canvas. */ + setHost(host: HTMLElement | null): void { + if (this.disposed || host === this.host) return; + this.teardownGraphics(); + this.host = host; + if (host && this.state.phase === "shown") this.startGraphics(); + } + + /** Builds a brand new canvas and viewer. Used on first show and by the Retry button. */ + startGraphics(): void { + if (this.disposed || !this.host || !this.scene || !this.state.model) return; + this.teardownGraphics(); + // Decode the geometry first: a scene the engine sent badly is a load problem with its own message, not a graphics one. + let viewScene: ViewScene; + try { + viewScene = this.viewScene ?? (this.viewScene = buildViewScene(this.scene, this.state.model)); + } catch (error) { + this.set({ phase: "failed", error: error instanceof SceneError ? error.code : "BAD_RESPONSE", graphics: "none" }); + return; + } + const canvas = this.host.ownerDocument.createElement("canvas"); + canvas.style.cssText = "display:block;width:100%;height:100%"; + this.host.appendChild(canvas); + this.canvas = canvas; + let viewer: ReadOnlyViewport; + try { + viewer = this.deps.viewportFactory(canvas, { theme: this.theme }); + } catch { + this.removeCanvas(); + this.set({ graphics: "unavailable", graphicsNote: null }); + return; + } + this.viewer = viewer; + this.offs.push( + viewer.onPick((id) => this.select(id)), + // The viewer cleared its own selection (Escape): keep the list in step. Selections we make ourselves are not echoed. + viewer.onSelect((ids) => { if (ids.length === 0 && this.state.selectedId !== null) this.set({ selectedId: null }); }), + viewer.onTrouble((t) => { + if (this.viewer !== viewer) return; + if (t.fatal) { + this.teardownGraphics(); + this.set({ graphics: "lost", graphicsNote: null }); + } else { + this.set({ graphicsNote: t.message }); + } + }), + ); + try { + viewer.show(viewScene); + viewer.setSlopeView(this.state.slope); + viewer.setSelected(this.state.selectedId ? this.meshIdsUnder(this.state.selectedId) : []); + if (this.state.preset !== "bed") viewer.setCamera(this.state.preset); + } catch { + this.teardownGraphics(); + this.set({ graphics: "unavailable" }); + return; + } + this.set({ graphics: "working", graphicsNote: null }); + } + + /** A click in the 3D view: select the whole top-level object it belongs to, in the view and in the list. */ + select(id: string | null): void { + if (this.disposed) return; + this.selectFromList(id ? this.topLevelId(id) : null); + } + + private topLevelId(id: string): string { + const byId = new Map((this.scene?.nodes ?? []).map((n) => [n.id, n])); + let cur = byId.get(id); + for (let guard = 0; cur && cur.parent_id !== null && guard < 80; guard++) { + const parent = byId.get(cur.parent_id); + if (!parent) break; + cur = parent; + } + return cur?.id ?? id; + } + + /** Every drawn piece (node with a mesh) at or under a top-level object. */ + private meshIdsUnder(topId: string): string[] { + const nodes = this.scene?.nodes ?? []; + const kids = new Map(); + for (const n of nodes) if (n.parent_id !== null) kids.set(n.parent_id, [...(kids.get(n.parent_id) ?? []), n.id]); + const byId = new Map(nodes.map((n) => [n.id, n])); + const out: string[] = []; + const stack = [topId]; + const seen = new Set(); + while (stack.length) { + const id = stack.pop()!; + if (seen.has(id)) continue; + seen.add(id); + if (byId.get(id)?.mesh_key) out.push(id); + for (const k of kids.get(id) ?? []) stack.push(k); + } + return out; + } + + selectFromList(id: string | null): void { + if (this.disposed) return; + this.set({ selectedId: id }); + this.viewer?.setSelected(id ? this.meshIdsUnder(id) : []); + } + + setCamera(preset: CameraPreset): void { + if (this.disposed) return; + this.set({ preset }); + this.viewer?.setCamera(preset); + } + + setSlope(on: boolean): void { + if (this.disposed) return; + this.set({ slope: on }); + this.viewer?.setSlopeView(on); + } + + setTheme(theme: ThemeMode): void { + if (this.disposed || theme === this.theme) return; + this.theme = theme; + this.viewer?.setTheme(theme); + } + + private cancelLoad(): void { + this.abort?.abort(); + this.abort = null; + } + + private removeCanvas(): void { + this.canvas?.remove(); + this.canvas = null; + } + + private teardownGraphics(): void { + for (const off of this.offs.splice(0)) off(); + const viewer = this.viewer; + this.viewer = null; + // three's OrbitControls removes one of its document-level listeners through canvas.getRootNode(). React removes a + // route's DOM before passive cleanups run, so a canvas that is already detached would leave that listener behind. + // Dispose with the canvas attached: put a detached one back (in the page body) just for the call. + const canvas = this.canvas; + if (viewer && canvas && !canvas.isConnected) canvas.ownerDocument.body.appendChild(canvas); + try { viewer?.dispose(); } catch { /* disposal must never throw out of cleanup */ } + this.removeCanvas(); + } + + dispose(): void { + if (this.disposed) return; + this.cancelLoad(); + this.teardownGraphics(); + this.disposed = true; + this.generation++; + this.listeners.clear(); + this.scene = null; + this.host = null; + } +} diff --git a/desktop/src/components/project-scene/sceneFixtures.ts b/desktop/src/components/project-scene/sceneFixtures.ts new file mode 100644 index 00000000..f9588155 --- /dev/null +++ b/desktop/src/components/project-scene/sceneFixtures.ts @@ -0,0 +1,64 @@ +// Anonymous scene/1 fixtures for tests and screenshots. Shapes follow backend/tests/fixtures/scene/golden-scene-1.json. +import type { SceneMesh, SceneNode, SceneV1 } from "@/lib/scene"; + +const b64 = (bytes: Uint8Array) => btoa(Array.from(bytes, (b) => String.fromCharCode(b)).join("")); + +export function cubeMesh(objectId = "1", size = 20, part = "3D/3dmodel.model"): SceneMesh { + const s = size; + const positions = [0, 0, 0, s, 0, 0, s, s, 0, 0, s, 0, 0, 0, s, s, 0, s, s, s, s, 0, s, s]; + const indices = [ + 0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4, 1, 2, 6, 1, 6, 5, 2, 3, 7, 2, 7, 6, 3, 0, 4, 3, 4, 7, + ]; + return { + key: { part, object_id: objectId }, vertex_count: 8, triangle_count: 12, + positions_f32le_base64: b64(new Uint8Array(new Float32Array(positions).buffer)), + indices_u32le_base64: b64(new Uint8Array(new Uint32Array(indices).buffer)), + volumes: [{ id: "v0", triangle_start: 0, triangle_count: 12, role: "part", source: "object" }], + }; +} + +export function matrixAt(x: number, y: number, z = 0): number[] { + return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1]; +} + +export function node(id: string, objectId: string, x: number, y: number, extra: Partial = {}): SceneNode { + const m = matrixAt(x, y); + return { + id, parent_id: null, resource: { part: "3D/3dmodel.model", object_id: objectId }, + mesh_key: { part: "3D/3dmodel.model", object_id: objectId }, + local_to_parent_mm: m, world_mm: m, mirrored: false, role_context: null, build_index: 0, + instance_ref: { build_index: 0, component_path: [] }, + plate: { state: "known", plate_id: "1", source: "plate_config" }, + placement_state: "known", printable: true, has_non_part_volumes: false, + bounds_mm: { min: [x, y, 0], max: [x + 20, y + 20, 20] }, finding_ids: [], ...extra, + }; +} + +export function scene(extra: Partial = {}): SceneV1 { + return { + schema: "scene/1", revision: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + status: "complete", units: "mm", axes: "right-handed-z-up", + sources: [{ part: "3D/3dmodel.model", unit: "millimeter", mm_per_unit: 1 }], + bed: { polygon_mm: [[0.5, 1], [270.5, 1], [270.5, 271], [0.5, 271]], height_mm: 270.05, edge_margin_mm: 0.5, policy: "u1_template" }, + meshes: [cubeMesh("1"), cubeMesh("2")], + nodes: [node("b0", "1", 100, 100), node("b1", "2", 140, 100)], + plates: [{ id: "1", ui_number: 1, origin_mm: null }], + findings: [], limitations: [], + counts: { nodes: 2, meshes: 2, vertices: 16, triangles: 24, rendered_triangles: 24, plates: 1, findings: 0, limitations: 0 }, + limits: {}, + ...extra, + }; +} + +/** One object 4.5 mm past the right edge, flagged by an engine finding keyed to its node id. */ +export function offBedScene(): SceneV1 { + const far = node("b1", "2", 255, 100, { bounds_mm: { min: [255, 100, 0], max: [275, 120, 20] }, finding_ids: ["f0"] }); + return scene({ + nodes: [node("b0", "1", 100, 100), far], + findings: [{ + id: "f0", engine: "scene", schema: "scene/1", pointer: "/nodes/1", scope: "instance", kind: "placement", target_ids: ["b1"], + value: { code: "PLACEMENT_OUTSIDE_BED", overhang_mm: { left: 0, right: 5, front: 0, back: 0 } }, + }], + counts: { nodes: 2, meshes: 2, vertices: 16, triangles: 24, rendered_triangles: 24, plates: 1, findings: 1, limitations: 0 }, + }); +} diff --git a/desktop/src/components/project-scene/sceneModel.test.ts b/desktop/src/components/project-scene/sceneModel.test.ts new file mode 100644 index 00000000..beca87d4 --- /dev/null +++ b/desktop/src/components/project-scene/sceneModel.test.ts @@ -0,0 +1,209 @@ +import { BufferAttribute, BufferGeometry, Mesh, MeshBasicMaterial, Raycaster, Vector3 } from "three"; +import { describe, expect, it } from "vitest"; +import { buildModel, buildViewScene, findingText, highlightGate, limitationText, COLORS } from "./sceneModel"; +import { node, offBedScene, scene, cubeMesh } from "./sceneFixtures"; +import type { LimitationCode, SceneFinding, SceneV1 } from "@/lib/scene"; + +const finding = (over: Partial = {}): SceneFinding => ({ + id: "f0", engine: "scene", schema: "scene/1", pointer: "/nodes/1", scope: "instance", kind: "placement", target_ids: ["b1"], + value: { code: "PLACEMENT_OUTSIDE_BED", overhang_mm: { left: 0, right: 5, front: 0, back: 0 } }, ...over, +}); + +describe("highlight gate", () => { + it("is open for one plate, millimeters, known placement and the real bed", () => { + expect(highlightGate(scene())).toEqual({ enabled: true, reasons: [], covered: [] }); + }); + it.each<[string, Partial]>([ + ["inch source", { sources: [{ part: "3D/3dmodel.model", unit: "inch", mm_per_unit: 25.4 }] }], + ["two plates", { plates: [{ id: "1", ui_number: 1, origin_mm: null }, { id: "2", ui_number: 2, origin_mm: null }] }], + ["unknown placement", { nodes: [node("b0", "1", 0, 0, { placement_state: "unknown" }), node("b1", "2", 1, 1)] }], + ["fallback bed", { bed: { ...scene().bed, policy: "fallback" } }], + ["unit limitation", { limitations: [{ code: "UNSUPPORTED_UNIT", target_ids: [] }] }], + ])("closes for %s and says why in words", (_name, extra) => { + const gate = highlightGate(scene(extra)); + expect(gate.enabled).toBe(false); + expect(gate.reasons[0]).toMatch(/^Highlighting is off because/); + }); +}); + +describe("findings and highlighting", () => { + it("highlights only the node an engine finding names, and turns the bed alert on", () => { + const s = offBedScene(); + const model = buildModel(s); + expect([...model.highlighted.entries()]).toEqual([["b1", "placement"]]); + expect(model.objects.map((o) => o.tone)).toEqual([null, "placement"]); + expect(buildViewScene(s, model).bedAlert).toBe(true); + const colors = buildViewScene(s, model).objects.map((o) => o.parts[0].color); + expect(colors).toEqual([COLORS.part, COLORS.placement]); + }); + + it("does not highlight geometry that merely looks off the bed when the engine named nothing", () => { + const s = scene({ nodes: [node("b0", "1", 400, 400), node("b1", "2", 140, 100)] }); + const model = buildModel(s); + expect(model.highlighted.size).toBe(0); + expect(buildViewScene(s, model).bedAlert).toBe(false); + }); + + it("keeps a finding project-level when its target is not exactly one known node", () => { + const s = scene({ findings: [finding({ target_ids: ["nope"] })] }); + const row = buildModel(s).findings[0]; + expect(row.projectLevel).toBe(true); + expect(row.selectId).toBeNull(); + expect(buildModel(s).highlighted.size).toBe(0); + }); + + it("keeps findings project-level and highlights nothing when the gate is closed", () => { + const s = offBedScene(); + s.plates.push({ id: "2", ui_number: 2, origin_mm: null }); + const model = buildModel(s); + expect(model.gate.enabled).toBe(false); + expect(model.highlighted.size).toBe(0); + expect(model.findings[0].projectLevel).toBe(true); + expect(model.limitations[0]).toMatch(/more than one plate/); + expect(model.limitations.filter((l) => /more than one plate/.test(l))).toHaveLength(1); + }); + + it("highlights every drawn piece under a named assembly", () => { + const parent = node("p0", "9", 100, 100, { mesh_key: null }); + const a = node("p0.0", "1", 100, 100, { parent_id: "p0" }); + const b = node("p0.1", "2", 110, 100, { parent_id: "p0" }); + const s = scene({ nodes: [parent, a, b], findings: [finding({ target_ids: ["p0"] })] }); + const model = buildModel(s); + expect([...model.highlighted.keys()].sort()).toEqual(["p0.0", "p0.1"]); + expect(model.objects).toHaveLength(1); + expect(model.findings[0].selectId).toBe("p0"); + }); + + it("treats a finding as object-level only when it has exactly one known target", () => { + const parent = node("p0", "9", 100, 100, { mesh_key: null }); + const a = node("p0.0", "1", 100, 100, { parent_id: "p0" }); + const b = node("p0.1", "2", 110, 100, { parent_id: "p0" }); + const other = node("o1", "3", 200, 100); + // One target: object-level. + const one = buildModel(scene({ nodes: [parent, a, b, other], findings: [finding({ target_ids: ["p0.0"] })] })); + expect(one.findings[0].projectLevel).toBe(false); + expect(one.findings[0].selectId).toBe("p0"); + expect([...one.highlighted.keys()]).toEqual(["p0.0"]); + // Several targets under the SAME top-level object: still project-level, nothing highlighted or selected. + const same = buildModel(scene({ nodes: [parent, a, b, other], findings: [finding({ target_ids: ["p0.0", "p0.1"] })] })); + expect(same.findings[0].projectLevel).toBe(true); + expect(same.findings[0].selectId).toBeNull(); + expect(same.highlighted.size).toBe(0); + // Two different objects: no first-target guess, nothing highlighted, nothing selected. + const mixed = buildModel(scene({ nodes: [parent, a, b, other], findings: [finding({ target_ids: ["p0.0", "o1"] })] })); + expect(mixed.findings[0].projectLevel).toBe(true); + expect(mixed.findings[0].selectId).toBeNull(); + expect(mixed.highlighted.size).toBe(0); + // One known target and one unknown id: also project-level. + const unknown = buildModel(scene({ nodes: [parent, a, b, other], findings: [finding({ target_ids: ["p0.0", "ghost"] })] })); + expect(unknown.findings[0].projectLevel).toBe(true); + }); + + it("lets a placement note outrank a size note on the same node", () => { + const s = scene({ findings: [finding({ id: "f1", kind: "size", value: { code: "SIZE_EXCEEDS_BED", overhang_mm: null } }), finding()] }); + expect(buildModel(s).highlighted.get("b1")).toBe("placement"); + }); +}); + +describe("gate wording", () => { + it("says what a stand-in position means, once, and merges the other reasons with their fuller limitation text", () => { + const stl = buildModel(scene({ nodes: [node("b0", "1", 0, 0, { placement_state: "unknown" })], limitations: [{ code: "UNKNOWN_PLACEMENT", target_ids: ["b0"] }] })); + expect(stl.limitations).toEqual([ + "Highlighting is off because the file does not say where some objects sit, so they are drawn at a stand-in position that is not their real place.", + ]); + const plates = buildModel(scene({ plates: [{ id: "1", ui_number: 1, origin_mm: null }, { id: "2", ui_number: 2, origin_mm: null }], limitations: [{ code: "MULTI_PLATE_PLACEMENT_UNCHECKED", target_ids: [] }] })); + expect(plates.limitations).toEqual([ + "Highlighting is off because this project has more than one plate. All plates are drawn on one bed, so objects may look closer together than they are.", + ]); + const inch = buildModel(scene({ sources: [{ part: "3D/3dmodel.model", unit: "inch", mm_per_unit: 25.4 }], limitations: [{ code: "NON_MM_SOURCE_UNIT", target_ids: [] }] })); + expect(inch.limitations).toEqual(["Highlighting is off because this project is not written in millimeters. It is converted to millimeters for the view."]); + const bad = buildModel(scene({ limitations: [{ code: "UNSUPPORTED_UNIT", target_ids: [] }] })); + expect(bad.limitations).toHaveLength(1); + expect(bad.limitations[0]).toContain("does not recognize"); + }); + + it("carries the scene's margin for the legend", () => { + expect(buildModel(scene()).marginMm).toBe(0.5); + }); +}); + +describe("wording", () => { + it("separates the physical bed edge from the 0.5 mm margin", () => { + const f = finding({ value: { code: "PLACEMENT_OUTSIDE_BED", overhang_mm: { left: 0.3, right: 5, front: 0, back: 0 } } }); + const text = findingText(f, "Object 2", 0.5); + expect(text).toContain("right edge 4.5 mm past the bed edge"); + expect(text).toContain("left edge inside the bed but within the 0.5 mm margin Studio keeps"); + }); + + it("says Placement for position and never claims a fit, readiness, a guarantee or 100%", () => { + const s = offBedScene(); + s.findings.push(finding({ id: "f1", kind: "size", value: { code: "SIZE_EXCEEDS_BED", overhang_mm: null } })); + const model = buildModel(s); + const all = [ + ...model.findings.map((f) => f.text), ...model.limitations, model.summary, + ...(Object.keys({ a: 1 }) as string[]), + ...(["UNKNOWN_VOLUME_ROLE", "UNKNOWN_PLACEMENT", "PLATE_MEMBERSHIP_AMBIGUOUS", "PLATE_MEMBERSHIP_UNKNOWN", "PLATES_UNAVAILABLE", + "BED_TEMPLATE_UNAVAILABLE", "REPEATED_INSTANCE_PLACEMENT_UNVERIFIED", "NON_MM_SOURCE_UNIT", "UNSUPPORTED_UNIT", + "MULTI_PLATE_PLACEMENT_UNCHECKED", "NO_BUILD_ITEMS"] as LimitationCode[]).map(limitationText), + ].join("\n").toLowerCase(); + expect(model.findings[0].text.startsWith("Placement:")).toBe(true); + expect(all).not.toMatch(/\bfits?\b|ready|guarantee|100%|\bsafe\b|best|clean|optimi/); + }); +}); + +describe("geometry for the viewer", () => { + it("moves the bed corner to the origin and keeps the rest of each world matrix", () => { + const s = scene(); + const v = buildViewScene(s, buildModel(s)); + expect(v.bed).toEqual({ widthMm: 270, depthMm: 270, heightMm: 270.05 }); + expect(v.objects[0].transform.slice(12, 15)).toEqual([99.5, 99, 0]); + expect(v.marginLoop?.[0]).toEqual([0.5, 0.5, 0.05]); + }); + + it("draws non-part volumes in a neutral color and a non-part instance entirely neutral", () => { + const mesh = cubeMesh("1"); + mesh.volumes = [ + { id: "v0", triangle_start: 0, triangle_count: 6, role: "part", source: "bambu_part" }, + { id: "v1", triangle_start: 6, triangle_count: 6, role: "negative", source: "bambu_part" }, + ]; + const s = scene({ meshes: [mesh, cubeMesh("2")], nodes: [node("b0", "1", 0, 0), node("b1", "2", 50, 0, { role_context: "modifier" })] }); + const v = buildViewScene(s, buildModel(s)); + expect(v.objects[0].parts.map((p) => p.color)).toEqual([COLORS.part, COLORS.other]); + expect(v.objects[1].parts.map((p) => p.color)).toEqual([COLORS.other]); + }); + + it("keeps the triangle order of a mirrored instance, and a real reflection still picks the top face", () => { + // A true reflection across X: negative determinant, world matrix column-major, translation (60, 40, 0). + const reflect = [-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 60, 40, 0, 1]; + const mirroredNode = node("b1", "1", 60, 40, { mirrored: true, world_mm: reflect, local_to_parent_mm: reflect }); + const s = scene({ nodes: [node("b0", "1", 0, 0), mirroredNode] }); + const v = buildViewScene(s, buildModel(s)); + const plain = v.objects[0].parts[0].indices, mirrored = v.objects[1].parts[0].indices; + expect(Array.from(mirrored)).toEqual(Array.from(plain)); // not reversed a second time + + const pick = (o: (typeof v.objects)[number], x: number, y: number) => { + const geometry = new BufferGeometry(); + geometry.setAttribute("position", new BufferAttribute(o.parts[0].positions, 3)); + geometry.setIndex(new BufferAttribute(o.parts[0].indices, 1)); + const mesh = new Mesh(geometry, new MeshBasicMaterial()); // default side: front faces only + mesh.matrixAutoUpdate = false; + mesh.matrix.fromArray(o.transform); + mesh.updateMatrixWorld(true); + const hits = new Raycaster(new Vector3(x, y, 100), new Vector3(0, 0, -1)).intersectObject(mesh); + return { det: mesh.matrixWorld.determinant(), hits }; + }; + // The view moves the bed corner (0.5, 1) to the origin, so the mirrored cube spans x 59.5-39.5.. in view space. + const view = v.objects[1].transform; + const { det, hits } = pick(v.objects[1], view[12] - 10, view[13] + 10); + expect(det).toBeLessThan(0); + expect(hits.length).toBeGreaterThan(0); + expect(hits[0].point.z).toBeCloseTo(20, 5); // the top face, not the bottom at 0 + expect(hits[0].face!.normal.z).toBeGreaterThan(0); + // Control: with the triangles reversed as well (the old behavior) the same ray lands on the bottom face, so this test can fail. + const reversed = { ...v.objects[1], parts: [{ ...v.objects[1].parts[0], indices: Uint32Array.from(mirrored, (_, i) => mirrored[i - (i % 3) + [0, 2, 1][i % 3]]) }] }; + expect(pick(reversed, view[12] - 10, view[13] + 10).hits[0].point.z).toBeCloseTo(0, 5); + // The unmirrored instance behaves the same way. + const plainHit = pick(v.objects[0], v.objects[0].transform[12] + 10, v.objects[0].transform[13] + 10); + expect(plainHit.hits[0].point.z).toBeCloseTo(20, 5); + }); +}); diff --git a/desktop/src/components/project-scene/sceneModel.ts b/desktop/src/components/project-scene/sceneModel.ts new file mode 100644 index 00000000..a395605e --- /dev/null +++ b/desktop/src/components/project-scene/sceneModel.ts @@ -0,0 +1,299 @@ +// Turns a scene/1 document into what the read-only project view shows: object rows, finding rows, plain-language notes +// about what the scene cannot prove, and the geometry handed to the viewer. Pure functions: no DOM, no WebGL. +// Highlighting comes ONLY from engine findings keyed to instance ids. Nothing here measures bounds or decides placement. +import { + decodeMesh, type LimitationCode, type SceneFinding, type SceneNode, type SceneV1, type VolumeRole, +} from "@/lib/scene"; + +export type Tone = "placement" | "size"; +export type ViewPart = { name: string; positions: Float32Array; indices: Uint32Array; color: string }; +export type ViewObject = { id: string; name: string; transform: number[]; parts: ViewPart[] }; +export type ViewScene = { + bed: { widthMm: number; depthMm: number; heightMm: number }; + objects: ViewObject[]; + /** The 0.5 mm policy margin, as a closed outline inside the physical bed edge (bed frame, mm). */ + marginLoop: [number, number, number][] | null; + /** True when at least one object is highlighted as past the bed edge; turns the bed outline to the alert color. */ + bedAlert: boolean; +}; + +export const COLORS = { + part: "#68c6dc", + placement: "#f26b5b", + size: "#f3b461", + other: "#9aa5b1", +} as const; + +export type HighlightGate = { enabled: boolean; reasons: string[]; /** Limitation codes whose wording is already given by a reason, so they are not listed twice. */ covered: LimitationCode[] }; + +const LIMITATION_TEXT: Record = { + UNKNOWN_VOLUME_ROLE: "Some parts of an object have a role the file does not state, so they are drawn in gray and left out of any size or placement note.", + UNKNOWN_PLACEMENT: "The file does not say where some objects sit, so they are drawn at a stand-in position.", + PLATE_MEMBERSHIP_AMBIGUOUS: "The file does not make clear which plate some objects belong to.", + PLATE_MEMBERSHIP_UNKNOWN: "The file does not say which plate some objects belong to.", + PLATES_UNAVAILABLE: "The plate layout could not be read from this file.", + BED_TEMPLATE_UNAVAILABLE: "Studio could not load its printer bed outline, so no placement notes are shown.", + REPEATED_INSTANCE_PLACEMENT_UNVERIFIED: "This project repeats an object. Each copy is drawn where the file puts it, but Studio does not make placement notes for repeated copies.", + NON_MM_SOURCE_UNIT: "This project is not written in millimeters. It is converted for the view, and placement notes are turned off.", + UNSUPPORTED_UNIT: "This project declares a unit Studio does not recognize. It is drawn as millimeters and no size or placement notes are made.", + MULTI_PLATE_PLACEMENT_UNCHECKED: "This project has more than one plate. Studio does not know how the plates are spaced, so it does not check placement.", + NO_BUILD_ITEMS: "This file lists no build items, so its objects are drawn without a known position.", +}; +export function limitationText(code: LimitationCode): string { + return LIMITATION_TEXT[code] ?? "Studio could not read part of this file, so the view is incomplete."; +} + +/** Geometric highlighting is allowed only when the scene can prove it: millimeters, one plate, known placement, real bed. */ +export function highlightGate(scene: SceneV1): HighlightGate { + const reasons: string[] = []; + const covered: LimitationCode[] = []; + const codes = new Set(scene.limitations.map((l) => l.code)); + if (scene.sources.some((s) => s.unit !== "millimeter") || codes.has("NON_MM_SOURCE_UNIT") || codes.has("UNSUPPORTED_UNIT")) { + if (codes.has("UNSUPPORTED_UNIT")) { + reasons.push("Highlighting is off because this project declares a unit Studio does not recognize. It is drawn as if it were in millimeters."); + covered.push("UNSUPPORTED_UNIT"); + } else { + reasons.push("Highlighting is off because this project is not written in millimeters. It is converted to millimeters for the view."); + } + covered.push("NON_MM_SOURCE_UNIT"); + } + if (scene.plates.length > 1 || codes.has("MULTI_PLATE_PLACEMENT_UNCHECKED")) { + reasons.push("Highlighting is off because this project has more than one plate. All plates are drawn on one bed, so objects may look closer together than they are."); + covered.push("MULTI_PLATE_PLACEMENT_UNCHECKED"); + } + if (scene.nodes.some((n) => n.mesh_key !== null && n.placement_state !== "known") || codes.has("UNKNOWN_PLACEMENT")) { + reasons.push("Highlighting is off because the file does not say where some objects sit, so they are drawn at a stand-in position that is not their real place."); + covered.push("UNKNOWN_PLACEMENT"); + } + if (scene.bed.policy !== "u1_template" || codes.has("BED_TEMPLATE_UNAVAILABLE")) { + reasons.push("Highlighting is off because Studio could not load its printer bed outline, so no placement notes are shown."); + covered.push("BED_TEMPLATE_UNAVAILABLE"); + } + return { enabled: reasons.length === 0, reasons, covered }; +} + +const EDGE_ORDER = ["left", "right", "front", "back"] as const; + +function mm(value: number): string { + return value.toFixed(1); +} + +/** Words for one finding. "Placement" is about position; the scene never says a model "fits". */ +export function findingText(finding: SceneFinding, label: string, marginMm: number): string { + if (finding.value.code === "SIZE_EXCEEDS_BED") { + return `Size: ${label} is larger than the usable bed area, which is the bed minus a ${mm(marginMm)} mm margin on every edge.`; + } + const over = finding.value.overhang_mm; + if (!over) return `Placement: ${label} reaches past the bed edge.`; + const parts: string[] = []; + for (const edge of EDGE_ORDER) { + const value = over[edge]; + if (!(value > 0)) continue; + // The engine measures past the margin line. The physical edge is one margin further out. + if (value > marginMm) parts.push(`${edge} edge ${mm(value - marginMm)} mm past the bed edge`); + else parts.push(`${edge} edge inside the bed but within the ${mm(marginMm)} mm margin Studio keeps`); + } + return `Placement: ${label}, ${parts.join("; ") || "reaches past the bed edge"}.`; +} + +export type ObjectRow = { + id: string; label: string; plateText: string; roleText: string; tone: Tone | null; hasGeometry: boolean; +}; +export type FindingRow = { + id: string; text: string; tone: Tone; targetIds: string[]; projectLevel: boolean; + /** The top-level object row to select when this note is chosen; null for a project-level note. */ + selectId: string | null; +}; +export type SceneModel = { + gate: HighlightGate; + objects: ObjectRow[]; + findings: FindingRow[]; + limitations: string[]; + /** Node ids (with geometry) to draw highlighted, by tone. Empty when the gate is off. */ + highlighted: Map; + summary: string; + partial: boolean; + /** The policy margin inside the bed edge, from the scene. */ + marginMm: number; +}; + +function childrenOf(nodes: SceneNode[]): Map { + const map = new Map(); + for (const n of nodes) { + if (n.parent_id === null) continue; + const list = map.get(n.parent_id); + if (list) list.push(n); else map.set(n.parent_id, [n]); + } + return map; +} + +function subtree(root: SceneNode, kids: Map): SceneNode[] { + const out: SceneNode[] = []; + const stack = [root]; + const seen = new Set(); + while (stack.length) { + const n = stack.pop()!; + if (seen.has(n.id)) continue; + seen.add(n.id); + out.push(n); + for (const k of kids.get(n.id) ?? []) stack.push(k); + } + return out; +} + +export function buildModel(scene: SceneV1): SceneModel { + const gate = highlightGate(scene); + const byId = new Map(scene.nodes.map((n) => [n.id, n])); + const kids = childrenOf(scene.nodes); + const tops = scene.nodes.filter((n) => n.parent_id === null); + const labelOf = new Map(); + tops.forEach((n, i) => labelOf.set(n.id, `Object ${i + 1}`)); + // A nested node is named after the object it sits in. + const topOf = (n: SceneNode): SceneNode => { + let cur = n; + for (let guard = 0; cur.parent_id !== null && guard < 80; guard++) { + const parent = byId.get(cur.parent_id); + if (!parent) break; + cur = parent; + } + return cur; + }; + const nameOf = (n: SceneNode) => labelOf.get(topOf(n).id) ?? "An object"; + + const highlighted = new Map(); + const findings: FindingRow[] = []; + for (const f of scene.findings) { + if (f.kind !== "placement" && f.kind !== "size") continue; + const tone: Tone = f.kind === "placement" ? "placement" : "size"; + const targets = f.target_ids.map((id) => byId.get(id)); + // Object-level only when the finding names exactly ONE target and it is a known node. A finding with several targets + // stays project-level even if they share a top-level object: the engine did not single one out, so nothing is + // highlighted or selected on its behalf. Unknown ids stay project-level too. + const exact = f.scope === "instance" && targets.length === 1 && targets[0] !== undefined; + const known = exact ? (targets as SceneNode[]) : []; + const label = exact ? nameOf(known[0]) : "An object"; + const projectLevel = !exact || !gate.enabled; + findings.push({ + id: f.id, tone, text: findingText(f, label, scene.bed.edge_margin_mm), + targetIds: projectLevel ? [] : known.map((n) => n.id), projectLevel, + selectId: projectLevel ? null : topOf(known[0]).id, + }); + if (!projectLevel) { + for (const n of known) { + for (const d of subtree(n, kids)) { + if (d.mesh_key === null) continue; + // Placement outranks size when both apply to the same node. + if (tone === "placement" || !highlighted.has(d.id)) highlighted.set(d.id, tone); + } + } + } + } + + const toneOfTop = (top: SceneNode): Tone | null => { + let found: Tone | null = null; + for (const d of subtree(top, kids)) { + const t = highlighted.get(d.id); + if (t === "placement") return t; + if (t) found = t; + } + return found; + }; + const plateNumber = new Map(scene.plates.map((p) => [p.id, p.ui_number])); + const objects: ObjectRow[] = tops.map((n) => { + const sub = subtree(n, kids); + return { + id: n.id, + label: labelOf.get(n.id) ?? "Object", + plateText: n.plate.state === "known" ? `Plate ${plateNumber.get(n.plate.plate_id ?? "") ?? n.plate.plate_id}` : n.plate.state === "ambiguous" ? "Plate unclear" : "Plate unknown", + roleText: n.role_context && n.role_context !== "part" ? roleWords(n.role_context) : "Part", + tone: toneOfTop(n), + hasGeometry: sub.some((d) => d.mesh_key !== null), + }; + }); + + const limitations = [...gate.reasons]; + for (const l of scene.limitations) { + if (gate.covered.includes(l.code)) continue; + const text = limitationText(l.code); + if (!limitations.includes(text)) limitations.push(text); + } + const shown = objects.filter((o) => o.hasGeometry).length; + const summary = `${shown} ${shown === 1 ? "object" : "objects"}, ${scene.counts.rendered_triangles.toLocaleString("en-US")} triangles`; + return { + gate, objects, findings, limitations, highlighted, summary, partial: scene.status === "partial", marginMm: scene.bed.edge_margin_mm, + }; +} + +export function roleWords(role: VolumeRole): string { + switch (role) { + case "part": return "Part"; + case "modifier": return "Modifier"; + case "negative": return "Negative volume"; + case "support_enforcer": return "Support enforcer"; + case "support_blocker": return "Support blocker"; + default: return "Role unknown"; + } +} + +// ---- Geometry for the viewer --------------------------------------------------------------------------------------- + +// A mirrored instance (negative-determinant world matrix) keeps its triangle order. three.js reads the sign of the matrix +// determinant and flips the front face itself when drawing, and ray picking works in the mesh's own space. Reversing the +// triangles as well would turn the faces inward a second time. + +const meshId = (k: { part: string; object_id: string }) => `${k.part}\u0000${k.object_id}`; + +export function buildViewScene(scene: SceneV1, model: SceneModel): ViewScene { + const xs = scene.bed.polygon_mm.map((p) => p[0]); + const ys = scene.bed.polygon_mm.map((p) => p[1]); + const minX = Math.min(...xs), maxX = Math.max(...xs), minY = Math.min(...ys), maxY = Math.max(...ys); + const decoded = new Map>(); + const meshes = new Map(scene.meshes.map((m) => [meshId(m.key), m])); + const byId = new Map(scene.nodes.map((n) => [n.id, n])); + const labelOf = new Map(model.objects.map((o) => [o.id, o.label])); + const topOf = (n: SceneNode): SceneNode => { + let cur = n; + for (let guard = 0; cur.parent_id !== null && guard < 80; guard++) { + const parent = byId.get(cur.parent_id); + if (!parent) break; + cur = parent; + } + return cur; + }; + + const objects: ViewObject[] = []; + for (const node of scene.nodes) { + if (!node.mesh_key) continue; + const mesh = meshes.get(meshId(node.mesh_key)); + if (!mesh) continue; + let data = decoded.get(meshId(mesh.key)); + if (!data) { data = decodeMesh(mesh); decoded.set(meshId(mesh.key), data); } + const tone = model.highlighted.get(node.id); + const contextRole = node.role_context; + const indices = data.indices; + const parts: ViewPart[] = mesh.volumes.map((v) => { + const role = contextRole ?? v.role; + const color = role !== "part" ? COLORS.other : tone ? COLORS[tone] : COLORS.part; + return { + name: roleWords(role), positions: data!.positions, color, + indices: indices.subarray(v.triangle_start * 3, (v.triangle_start + v.triangle_count) * 3), + }; + }).filter((p) => p.indices.length > 0); + if (!parts.length) continue; + const transform = node.world_mm.slice(); + transform[12] -= minX; + transform[13] -= minY; + objects.push({ id: node.id, name: labelOf.get(topOf(node).id) ?? "Object", transform, parts }); + } + + const margin = scene.bed.edge_margin_mm; + const w = maxX - minX, d = maxY - minY; + const marginLoop: [number, number, number][] | null = margin > 0 && w > 2 * margin && d > 2 * margin + ? [[margin, margin, 0.05], [w - margin, margin, 0.05], [w - margin, d - margin, 0.05], [margin, d - margin, 0.05]] + : null; + return { + bed: { widthMm: w, depthMm: d, heightMm: scene.bed.height_mm ?? 270 }, + objects, marginLoop, + bedAlert: [...model.highlighted.values()].includes("placement"), + }; +} diff --git a/desktop/src/components/project-scene/vendor.integrity.test.ts b/desktop/src/components/project-scene/vendor.integrity.test.ts new file mode 100644 index 00000000..3adc0d6e --- /dev/null +++ b/desktop/src/components/project-scene/vendor.integrity.test.ts @@ -0,0 +1,91 @@ +/// +import { describe, expect, it } from "vitest"; + +// Checks the vendored SlicerX tree against its own record (vendor/slicerx/UPDATING.md): verbatim files are byte-for-byte +// upstream, the seven patched files differ from upstream ONLY by the import path and the modification notice, every sha256 +// in the table is current, and no other file carries a notice. Needs no network: the upstream blob ids are in the table. +const raw = import.meta.glob( + ["../../vendor/slicerx/viewport/*.ts", "../../vendor/slicerx/contracts/*.ts", "../../vendor/slicerx/LICENSE-APACHE", "../../vendor/slicerx/NOTICE", "../../vendor/slicerx/UPDATING.md"], + { query: "?raw", import: "default", eager: true }, +) as Record; + +const base = (p: string) => new URL(p, "file:///src/components/project-scene/").pathname.replace(/^\/src\/vendor\/slicerx\//, ""); +const files: Record = Object.fromEntries(Object.entries(raw).map(([k, v]) => [base(k), v])); + +const hex = (buf: ArrayBuffer) => Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, "0")).join(""); +const digest = async (algo: string, data: Uint8Array) => hex(await crypto.subtle.digest(algo, data as unknown as ArrayBuffer)); +const bytes = (s: string) => new TextEncoder().encode(s); +async function gitBlob(text: string): Promise { + const body = bytes(text); + const head = bytes(`blob ${body.length}\0`); + const all = new Uint8Array(head.length + body.length); + all.set(head, 0); + all.set(body, head.length); + return digest("SHA-1", all); +} + +const PATCHED = ["palette", "stage", "summary", "toolchanger", "toolpaths", "types", "viewport"].map((n) => `viewport/${n}.ts`); +const NOTICE_START = "// MODIFIED BY SNAPMAKER STUDIO (DVOpenLabs/snapmaker-studio)"; +const RULE = "// " + "-".repeat(111); +const NOTICE_BLOCK = [ + RULE, + "// MODIFIED BY SNAPMAKER STUDIO (DVOpenLabs/snapmaker-studio): the only change in this file is the import path of the", + "// contracts module ('@slicerx/contracts' -> '../contracts/index'). Upstream: slicerx-oss/slicerx @", + "// edb521fe41306dd60d01bda8a0f6bf8aa54fcb29 (Apache-2.0). See ../UPDATING.md.", + RULE, + "", +].join("\n"); + +type Row = { file: string; blob: string; sha: string; status: string }; +const rows: Row[] = [...files["UPDATING.md"].matchAll(/^\| `([^`]+)` \| `[^`]+` \| ([0-9a-f]{12}) \| ([0-9a-f]{12}) \| (.*) \|$/gm)] + .map((m) => ({ file: m[1], blob: m[2], sha: m[3], status: m[4] })); + +describe("vendored SlicerX tree", () => { + it("has a table row for every vendored file and no row for a missing one", () => { + const vendored = Object.keys(files).filter((k) => k !== "UPDATING.md" && k !== "contracts/index.ts").sort(); // index.ts is Studio-authored + expect(rows.map((r) => r.file).sort()).toEqual(vendored); + expect(rows).toHaveLength(41); + }); + + it("every sha256 in the table is the file as stored", async () => { + for (const r of rows) expect((await digest("SHA-256", bytes(files[r.file]))).slice(0, 12), r.file).toBe(r.sha); + }); + + it("verbatim files are byte-for-byte upstream", async () => { + for (const r of rows.filter((x) => !PATCHED.includes(x.file))) { + expect(r.status, r.file).toBe("verbatim"); + expect((await gitBlob(files[r.file])).slice(0, 12), r.file).toBe(r.blob); + } + }); + + it("the seven patched files keep the upstream header, carry the notice after it, and differ from upstream only by import path and notice", async () => { + for (const file of PATCHED) { + const text = files[file]; + const row = rows.find((r) => r.file === file)!; + expect(row.status, file).toContain("patched"); + const lines = text.split("\n"); + expect(lines[0], file).toBe("// SPDX-License-Identifier: Apache-2.0"); + expect(lines[1], file).toBe("// Copyright (C) 2026 The SlicerX contributors"); + const at = lines.findIndex((l) => l.startsWith(NOTICE_START)); + expect(at, file).toBeGreaterThan(2); // after the upstream header, not before it + expect(text.split(NOTICE_START).length - 1, file).toBe(1); + expect(text, file).toContain(NOTICE_BLOCK); + // Undo the two documented changes and the result must be the upstream file. + const restored = text.replace(NOTICE_BLOCK, "").split("'../contracts/index'").join("'@slicerx/contracts'"); + expect((await gitBlob(restored)).slice(0, 12), file).toBe(row.blob); + } + }); + + it("no other vendored file carries a modification notice, and none still imports the unpublished package", () => { + for (const [file, text] of Object.entries(files)) { + if (file === "UPDATING.md" || PATCHED.includes(file)) continue; + expect(text.includes("MODIFIED BY SNAPMAKER STUDIO"), file).toBe(false); + } + for (const file of PATCHED) expect(files[file].includes("from '@slicerx/contracts'"), file).toBe(false); + }); + + it("keeps the upstream license and notice text", () => { + expect(files["LICENSE-APACHE"]).toContain("Apache License"); + expect(files["NOTICE"]).toContain("Made possible by SlicerX"); + }); +}); diff --git a/desktop/src/lib/recovery/workspace.ts b/desktop/src/lib/recovery/workspace.ts index 5fd8b896..d43b4907 100644 --- a/desktop/src/lib/recovery/workspace.ts +++ b/desktop/src/lib/recovery/workspace.ts @@ -26,7 +26,7 @@ export function planWorkspaceCheckpoint(record: JobRecord | null, verified = tru } if (!record) { return { project: null, tracked: [], unavailable: [], canSave: false, - why: "No project is open. Prepare one from Creative import (or open a project) and its files appear here." }; + why: "No project is open. Prepare one from the Creative tool, or open a project, and its files appear here." }; } const tracked: TrackedFile[] = [{ role: "original", name: record.original.name, path: record.original.path }]; const unavailable: UnavailableFile[] = []; diff --git a/desktop/src/lib/scene.test.ts b/desktop/src/lib/scene.test.ts new file mode 100644 index 00000000..99cbcafc --- /dev/null +++ b/desktop/src/lib/scene.test.ts @@ -0,0 +1,615 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { + SceneError, currentSceneClientId, decodeMesh, isAbort, loadScene, newRequestId, sceneErrorText, + resetSceneSession, type SceneMesh, type SceneTransport, +} from "./scene"; + +vi.mock("@/api", () => ({ engineConnection: vi.fn() })); + +// Every test starts with no session, as at app start. +beforeEach(() => resetSceneSession()); + +const REVISION = "a".repeat(64); +const status = (state: string, extra: Record = {}) => ({ + job_id: "job-1", request_id: "req", state, stage: null, completed: null, total: null, error: null, revision: null, ...extra, +}); +// What /scene/start really answers (backend scene_jobs.py): identity and state only, no stage, progress or error. +const started = (state: string, extra: Record = {}) => ({ + job_id: "job-1", request_id: "req", state, revision: null, replaced_job_id: null, ...extra, +}); +const scene = { schema: "scene/1", revision: REVISION, nodes: [], findings: [], limitations: [] }; +const noSleep = () => Promise.resolve(); + +type Call = { route: string; body: unknown }; +function transportFor( + script: Partial { status: number; body: unknown }))[]>>, +): { transport: SceneTransport; calls: Call[] } { + const calls: Call[] = []; + const queues = Object.fromEntries(Object.entries(script).map(([k, v]) => [k, [...(v as unknown[])]])); + const transport: SceneTransport = async (route, body) => { + calls.push({ route, body }); + const q = queues[route] as ({ status: number; body: unknown } | (() => { status: number; body: unknown }))[] | undefined; + if (!q?.length) return route === "session" ? { status: 200, body: { client_id: "session-scripted", ttl_s: 900 } } : { status: 200, body: status("cancelled") }; + const next = q.length > 1 ? q.shift()! : q[0]; + return typeof next === "function" ? next() : next; + }; + return { transport, calls }; +} + +describe("loadScene", () => { + it("follows a job from queued to the finished scene and asks for the revision it saw", async () => { + const { transport, calls } = transportFor({ + start: [{ status: 200, body: started("queued") }], + status: [{ status: 200, body: status("running", { stage: "parsing", completed: 1, total: 4 }) }, + { status: 200, body: status("succeeded", { revision: REVISION }) }], + result: [{ status: 200, body: scene }], + }); + const seen: string[] = []; + const out = await loadScene("p.3mf", { + signal: new AbortController().signal, transport, sleep: noSleep, onProgress: (p) => seen.push(p.state), + }); + expect(out.schema).toBe("scene/1"); + expect(seen).toEqual(["queued", "running", "succeeded"]); + expect(calls.find((c) => c.route === "result")?.body).toEqual({ job_id: "job-1", client_id: "session-scripted", expected_revision: REVISION }); + // Every status and result call carries the session's client id. + expect(calls.filter((c) => c.route === "status" || c.route === "result").every((c) => (c.body as { client_id?: string }).client_id === "session-scripted")).toBe(true); + expect(calls.some((c) => c.route === "cancel")).toBe(false); + }); + + it("uses a fresh request id for every generation", async () => { + const ids = new Set(); + for (let i = 0; i < 20; i++) { + const { transport, calls } = transportFor({ + start: [{ status: 200, body: started("succeeded", { revision: REVISION }) }], + result: [{ status: 200, body: scene }], + }); + await loadScene("p.3mf", { signal: new AbortController().signal, transport, sleep: noSleep }); + ids.add((calls[0].body as { request_id: string }).request_id); + } + expect(ids.size).toBe(20); + expect(newRequestId()).not.toBe(newRequestId()); + }); + + it("tells the engine to cancel by client id and request id when the caller aborts, and stops with an AbortError", async () => { + const controller = new AbortController(); + const { transport, calls } = transportFor({ + start: [{ status: 200, body: started("running") }], + status: [{ status: 200, body: status("running") }], + }); + const sleep = vi.fn(async () => { controller.abort(); }); + const failure = await loadScene("p.3mf", { signal: controller.signal, transport, sleep }).catch((e) => e); + expect(isAbort(failure)).toBe(true); + const startBody = calls.find((c) => c.route === "start")!.body as { request_id: string; client_id: string; seq: number }; + const cancels = calls.filter((c) => c.route === "cancel"); + expect(cancels).toEqual([{ route: "cancel", body: { client_id: currentSceneClientId(), request_id: startBody.request_id, seq: startBody.seq } }]); + expect(Object.keys(cancels[0].body as object).sort()).toEqual(["client_id", "request_id", "seq"]); // no job_id + }); + + it("cancels a request whose start was answered just before the caller aborted", async () => { + const controller = new AbortController(); + const { transport, calls } = transportFor({ start: [{ status: 200, body: started("queued") }] }); + const wrapped: SceneTransport = async (route, body, signal) => { + const r = await transport(route, body, signal); + if (route === "start") controller.abort(); + return r; + }; + const failure = await loadScene("p.3mf", { signal: controller.signal, transport: wrapped, sleep: noSleep }).catch((e) => e); + expect(isAbort(failure)).toBe(true); + expect(calls.map((c) => c.route)).toEqual(["session", "start", "cancel"]); + expect((calls[2].body as { request_id: string }).request_id).toBe((calls[1].body as { request_id: string }).request_id); + }); + + it("does not start anything when it is already aborted", async () => { + const controller = new AbortController(); + controller.abort(); + const { transport, calls } = transportFor({}); + const failure = await loadScene("p.3mf", { signal: controller.signal, transport }).catch((e) => e); + expect(isAbort(failure)).toBe(true); + expect(calls).toEqual([]); + }); + + it.each([ + ["LIMIT_EXCEEDED", "larger than the 3D view can show"], + ["SOURCE_CHANGED", "changed while it was being read"], + ["TIMEOUT", "took too long"], + ])("reports a failed job as %s in plain words", async (code, words) => { + const { transport } = transportFor({ + // A request id the engine still holds comes back already failed, with no reason in the start answer; the reason is in the status. + start: [{ status: 200, body: started("failed") }], + status: [{ status: 200, body: status("failed", { error: { code, message: "C:\\private\\path.3mf" } }) }], + }); + const failure = (await loadScene("p.3mf", { signal: new AbortController().signal, transport, sleep: noSleep }).catch((e) => e)) as SceneError; + expect(failure).toBeInstanceOf(SceneError); + expect(failure.code).toBe(code); + expect(sceneErrorText(failure.code)).toContain(words); + expect(sceneErrorText(failure.code)).not.toContain("private"); + }); + + it("maps an HTTP refusal to its error code and an unknown code to INTERNAL", async () => { + const refused = transportFor({ start: [{ status: 422, body: { error: "UNSUPPORTED_FORMAT" } }] }); + const a = (await loadScene("p.obj", { signal: new AbortController().signal, transport: refused.transport }).catch((e) => e)) as SceneError; + expect(a.code).toBe("UNSUPPORTED_FORMAT"); + const odd = transportFor({ start: [{ status: 409, body: { error: "SOMETHING_NEW" } }] }); + const b = (await loadScene("p.3mf", { signal: new AbortController().signal, transport: odd.transport }).catch((e) => e)) as SceneError; + expect(b.code).toBe("INTERNAL"); + }); + + it("rejects a result that is not scene/1", async () => { + const { transport } = transportFor({ + start: [{ status: 200, body: started("succeeded", { revision: REVISION }) }], + result: [{ status: 200, body: { schema: "scene/2", nodes: [] } }], + }); + const failure = (await loadScene("p.3mf", { signal: new AbortController().signal, transport, sleep: noSleep }).catch((e) => e)) as SceneError; + expect(failure.code).toBe("BAD_RESPONSE"); + }); + + it("reports a cancelled job as CANCELLED", async () => { + const { transport } = transportFor({ start: [{ status: 200, body: started("cancelled") }] }); + const failure = (await loadScene("p.3mf", { signal: new AbortController().signal, transport }).catch((e) => e)) as SceneError; + expect(failure.code).toBe("CANCELLED"); + }); +}); + +describe("a start that never answers", () => { + it("times out with TIMEOUT, cancels the request by id, and does not block later loads", async () => { + const calls: { route: string; body: unknown }[] = []; + let starts = 0; + // The first start ignores its signal on purpose: the caller must still get away. + const transport: SceneTransport = (route, body) => { + calls.push({ route, body }); + if (route === "session") return Promise.resolve({ status: 200, body: { client_id: "session-t", ttl_s: 900 } }); + if (route === "start" && ++starts === 1) return new Promise(() => undefined); + if (route === "start") return Promise.resolve({ status: 200, body: started("succeeded", { job_id: "j2", revision: REVISION }) }); + if (route === "result") return Promise.resolve({ status: 200, body: scene }); + return Promise.resolve({ status: 200, body: status("cancelled") }); + }; + const failure = (await loadScene("a.3mf", { signal: new AbortController().signal, transport, sleep: noSleep, startTimeoutMs: 20 }).catch((e) => e)) as SceneError; + expect(failure).toBeInstanceOf(SceneError); + expect(failure.code).toBe("TIMEOUT"); + expect(sceneErrorText(failure.code)).toContain("took too long"); + const firstStart = calls.find((c) => c.route === "start")!.body as { request_id: string; seq: number }; + expect(calls.find((c) => c.route === "cancel")!.body).toEqual({ client_id: "session-t", request_id: firstStart.request_id, seq: firstStart.seq }); + const next = await loadScene("a.3mf", { signal: new AbortController().signal, transport, sleep: noSleep, startTimeoutMs: 20 }); + expect(next.schema).toBe("scene/1"); + expect(calls.filter((c) => c.route === "start")).toHaveLength(2); // the hung start and the new one: no re-send protocol + }); + + it("is released at once when the caller aborts, even if the transport never answers", async () => { + const controller = new AbortController(); + const transport: SceneTransport = (route) => (route === "start" ? new Promise(() => undefined) : route === "session" ? Promise.resolve({ status: 200, body: { client_id: "session-t", ttl_s: 900 } }) : Promise.resolve({ status: 200, body: scene })); + const pending = loadScene("a.3mf", { signal: controller.signal, transport, sleep: noSleep, startTimeoutMs: 60000 }).catch((e) => e); + await Promise.resolve(); + controller.abort(); + expect(isAbort(await pending)).toBe(true); + }); + + it("gives up on a status answer that never comes and cancels the request", async () => { + const calls: string[] = []; + const transport: SceneTransport = (route) => { + calls.push(route); + if (route === "session") return Promise.resolve({ status: 200, body: { client_id: "session-t", ttl_s: 900 } }); + if (route === "start") return Promise.resolve({ status: 200, body: started("running") }); + if (route === "status") return new Promise(() => undefined); + return Promise.resolve({ status: 200, body: status("cancelled") }); + }; + const failure = (await loadScene("a.3mf", { signal: new AbortController().signal, transport, sleep: noSleep, requestTimeoutMs: 20 }).catch((e) => e)) as SceneError; + expect(failure.code).toBe("TIMEOUT"); + expect(calls).toContain("cancel"); + }); +}); + +// ---- The session contract with the engine ------------------------------------------------------------------------------ +// A stand-in engine that follows the session contract as the real engine implements it: POST /scene/session opens a session; +// starts carry client_id and a strictly increasing seq; requests are keyed by (session, request id). An exact retry (same +// session, same seq, same request id) returns the current job while it exists. Otherwise a start whose seq is not higher than +// the highest seen is refused (STALE_START). Cancellation is a "dead-through" mark: a cancel for seq N refuses every start of +// that session with seq N or lower (CANCELLED_BEFORE_START), and cancels the running job only if its seq is exactly N. An +// unknown or expired session gives 409 SESSION_EXPIRED; more sessions than allowed gives 503 SESSION_LIMIT; a newer start +// replaces the running job (replaced_job_id only within one session). NOTE: the comment above `SUPERSEDED` in scene.ts still +// says a retry of a processed start is refused as stale; the real engine answers an exact retry with the same job (the client +// never sends one), and this stand-in follows the real engine. +// Delivery of any call can be held and released by hand, so every ordering below is deterministic: no timers, no sleeping. +type Job = { id: string; request: string; session: string; seq: number; state: "running" | "succeeded" | "cancelled" }; +type Reply = { status: number; body: unknown }; +function makeEngine(options: { maxSessions?: number } = {}) { + const sessions = new Map(); + const jobs: Job[] = []; + const byRequest = new Map(); // keyed by session and request id + let running: Job | null = null; + let opened = 0; + const log: { route: string; body: Record }[] = []; + const held: { match: (route: string, body: Record) => boolean; release: () => void; gate: Promise }[] = []; + const hold = (match: (route: string, body: Record) => boolean) => { + let release: () => void = () => undefined; + const gate = new Promise((r) => { release = r; }); + const h = { match, release, gate }; + held.push(h); + return h; + }; + const expire = (clientId: string) => { sessions.delete(clientId); }; + const handle = (route: string, body: Record): Reply => { + if (route === "session") { + if (options.maxSessions !== undefined && sessions.size >= options.maxSessions) return { status: 503, body: { error: "SESSION_LIMIT" } }; + const id = `session-${++opened}`; + sessions.set(id, { highest: 0, deadThrough: 0 }); + return { status: 200, body: { client_id: id, ttl_s: 900 } }; + } + if (route === "start") { + const s = sessions.get(String(body.client_id)); + if (!s) return { status: 409, body: { error: "SESSION_EXPIRED" } }; + const seq = Number(body.seq), request = String(body.request_id); + if (seq <= s.deadThrough) return { status: 409, body: { error: "CANCELLED_BEFORE_START" } }; + const existing = byRequest.get(`${String(body.client_id)}|${request}`); + if (existing && existing.seq === seq) return { status: 200, body: started(existing.state, { job_id: existing.id, request_id: request }) }; // an exact retry + if (seq <= s.highest) return { status: 409, body: { error: "STALE_START" } }; + s.highest = seq; + let replaced: string | null = null; + if (running) { running.state = "cancelled"; if (running.session === String(body.client_id)) replaced = running.id; } // replaced_job_id only within one session + const job: Job = { id: `job-${jobs.length + 1}`, request, session: String(body.client_id), seq, state: "running" }; + jobs.push(job); + byRequest.set(`${String(body.client_id)}|${request}`, job); + running = job; + return { status: 200, body: started("running", { job_id: job.id, request_id: request, replaced_job_id: replaced }) }; + } + // A job that belongs to a session is visible only with the SAME session's client_id; foreign, missing and unknown all look alike. + const jobOf = () => jobs.find((j) => j.id === body.job_id && j.session === body.client_id); + if (route === "status") { + const j = jobOf(); + if (!j) return { status: 404, body: { error: "EXPIRED" } }; + if (j.state === "running") j.state = "succeeded"; // the engine finishes on the first status call + return { status: 200, body: status(j.state, { job_id: j.id, request_id: j.request, revision: j.state === "succeeded" ? REVISION : null }) }; + } + if (route === "result") { + const j = jobOf(); + if (!j) return { status: 404, body: { error: "EXPIRED" } }; + return j.state === "succeeded" ? { status: 200, body: { ...scene, revision: REVISION } } : { status: 409, body: { error: "CANCELLED" } }; + } + // cancel + const s = sessions.get(String(body.client_id)); + if (!s) return { status: 409, body: { error: "SESSION_EXPIRED" } }; + s.deadThrough = Math.max(s.deadThrough, Number(body.seq)); + const j = byRequest.get(`${String(body.client_id)}|${String(body.request_id)}`); + if (j && j.seq === Number(body.seq) && j.state === "running") j.state = "cancelled"; // only the exact attempt + return { status: 200, body: status("cancelled") }; + }; + const transport: SceneTransport = async (route, body) => { + const b = body as Record; + log.push({ route, body: b }); + const h = held.find((x) => x.match(route, b)); + if (h) { + held.splice(held.indexOf(h), 1); + await h.gate; + } + return handle(route, b); + }; + return { + transport, log, hold, jobs, expire, + starts: () => log.filter((l) => l.route === "start").map((l) => l.body), + sessionOpens: () => log.filter((l) => l.route === "session").length, + }; +} +const flushMicrotasks = async () => { for (let i = 0; i < 20; i++) await Promise.resolve(); }; +const opts = (signal: AbortSignal, transport: SceneTransport) => ({ signal, transport, sleep: noSleep }); + +describe("sessions", () => { + it("opens ONE session lazily, shared by concurrent loads, and every start carries it with a seq that starts at 1", async () => { + const engine = makeEngine(); + expect(currentSceneClientId()).toBeNull(); + const holdOpen = engine.hold((route) => route === "session"); + const aSignal = new AbortController(); + const a = loadScene("a.3mf", opts(aSignal.signal, engine.transport)).catch((e) => e); + const b = loadScene("b.3mf", opts(new AbortController().signal, engine.transport)); + await flushMicrotasks(); + expect(engine.sessionOpens()).toBe(1); // both loads wait on the same open + holdOpen.release(); + aSignal.abort(); // A is abandoned before it learns the session, so it never sends a start + expect(isAbort(await a)).toBe(true); + await b; + await loadScene("c.3mf", opts(new AbortController().signal, engine.transport)); + expect(engine.sessionOpens()).toBe(1); + const starts = engine.starts(); + expect(new Set(starts.map((s) => s.client_id))).toEqual(new Set(["session-1"])); + expect(currentSceneClientId()).toBe("session-1"); + expect(starts.map((s) => s.path)).toEqual(["b.3mf", "c.3mf"]); + expect(starts.map((s) => Number(s.seq))).toEqual([1, 2]); + expect(new Set(starts.map((s) => s.request_id)).size).toBe(2); + }); + + it("a load aborted before the session is known sends nothing, and the next load uses the same session", async () => { + const engine = makeEngine(); + const holdOpen = engine.hold((route) => route === "session"); + const first = new AbortController(); + const a = loadScene("same.3mf", opts(first.signal, engine.transport)).catch((e) => e); // StrictMode's first mount + await flushMicrotasks(); + first.abort(); + expect(isAbort(await a)).toBe(true); + const b = loadScene("same.3mf", opts(new AbortController().signal, engine.transport)); // the second mount + await flushMicrotasks(); + holdOpen.release(); + expect((await b).schema).toBe("scene/1"); + expect(engine.sessionOpens()).toBe(1); + expect(engine.starts()).toHaveLength(1); // the abandoned mount never reached the engine + expect(engine.log.filter((l) => l.route === "cancel")).toHaveLength(0); + }); + + it("an abandoned start A delivered AFTER the wanted start B cannot cancel or replace B, and B loads", async () => { + const engine = makeEngine(); + const aSignal = new AbortController(); + await loadScene("warm.3mf", opts(new AbortController().signal, engine.transport)); // opens the session + const holdA = engine.hold((route, body) => route === "start" && body.path === "a.3mf"); + const a = loadScene("a.3mf", opts(aSignal.signal, engine.transport)).catch((e) => e); + await flushMicrotasks(); // A's start is issued and held on the way to the engine + aSignal.abort(); // the user (or an unmount) abandons A + expect(isAbort(await a)).toBe(true); + const loaded = await loadScene("b.3mf", opts(new AbortController().signal, engine.transport)); // B reaches the engine first + expect(loaded.schema).toBe("scene/1"); + holdA.release(); // A's late start finally arrives + await flushMicrotasks(); + const starts = engine.starts(); + expect(starts.map((s) => s.path)).toEqual(["warm.3mf", "a.3mf", "b.3mf"]); + expect(starts.map((s) => Number(s.seq))).toEqual([1, 2, 3]); + expect(engine.jobs.map((j) => j.state)).toEqual(["cancelled", "succeeded"]); // warm (replaced by B) and B; A registered nothing + const cancels = engine.log.filter((l) => l.route === "cancel"); + expect(cancels).toHaveLength(1); + expect(Object.keys(cancels[0].body).sort()).toEqual(["client_id", "request_id", "seq"]); + expect(cancels[0].body).toEqual({ client_id: "session-1", request_id: starts[1].request_id, seq: starts[1].seq }); + }); + + it("cancel before start: the cancel reaches the engine first, and the late start is refused and registers nothing", async () => { + const engine = makeEngine(); + await loadScene("warm.3mf", opts(new AbortController().signal, engine.transport)); + const jobsBefore = engine.jobs.length; + const holdStart = engine.hold((route, body) => route === "start" && body.path === "a.3mf"); + const aSignal = new AbortController(); + const a = loadScene("a.3mf", opts(aSignal.signal, engine.transport)).catch((e) => e); + await flushMicrotasks(); + aSignal.abort(); + await a; + await flushMicrotasks(); // the cancel was delivered while the start is still on its way + expect(engine.log.filter((l) => l.route === "cancel")).toHaveLength(1); + holdStart.release(); + await flushMicrotasks(); + expect(engine.jobs).toHaveLength(jobsBefore); // the late start created no job + expect(engine.jobs.every((j) => j.state !== "running" || j.request !== engine.starts()[1].request_id)).toBe(true); + }); + + it("gives every start attempt a higher seq, retries included", async () => { + const engine = makeEngine(); + for (let i = 0; i < 3; i++) await loadScene(`p${i}.3mf`, opts(new AbortController().signal, engine.transport)); + const refusing: SceneTransport = async (route, body) => (route === "start" ? { status: 422, body: { error: "UNSUPPORTED_FORMAT" } } : engine.transport(route, body)); + const failure = await loadScene("x.obj", opts(new AbortController().signal, refusing)).catch((e) => e); + expect((failure as SceneError).code).toBe("UNSUPPORTED_FORMAT"); + await loadScene("again.3mf", opts(new AbortController().signal, engine.transport)); // the user presses Try again + const seqs = engine.starts().map((s) => Number(s.seq)); + expect(seqs).toEqual([1, 2, 3, 5]); // the refused start used seq 4 + expect(new Set(engine.starts().map((s) => s.request_id)).size).toBe(4); + }); + + it("an expired session opens a NEW session, restarts ONCE with seq back at 1 and a fresh request id, and loads", async () => { + const engine = makeEngine(); + await loadScene("a.3mf", opts(new AbortController().signal, engine.transport)); + engine.expire("session-1"); // the engine restarted, or the session sat idle too long + const loaded = await loadScene("b.3mf", opts(new AbortController().signal, engine.transport)); + expect(loaded.schema).toBe("scene/1"); + expect(engine.sessionOpens()).toBe(2); + const starts = engine.starts(); + expect(starts.map((s) => [s.client_id, Number(s.seq)])).toEqual([["session-1", 1], ["session-1", 2], ["session-2", 1]]); + expect(starts[2].request_id).not.toBe(starts[1].request_id); + expect(currentSceneClientId()).toBe("session-2"); + }); + + it("repeated expiry stops after one restart and is reported: no loop", async () => { + const engine = makeEngine(); + const alwaysExpired: SceneTransport = async (route, body) => { + const reply = await engine.transport(route, body); + if (route === "session") engine.expire(String((reply.body as { client_id: string }).client_id)); + return reply; + }; + const failure = (await loadScene("a.3mf", opts(new AbortController().signal, alwaysExpired)).catch((e) => e)) as SceneError; + expect(failure.code).toBe("SESSION_EXPIRED"); + expect(sceneErrorText(failure.code)).toContain("Try again"); + expect(engine.sessionOpens()).toBe(2); + expect(engine.starts()).toHaveLength(2); + }); + + it("an abandoned start delivered after its session expired never revives: it opens nothing and its answer is dropped", async () => { + const engine = makeEngine(); + await loadScene("warm.3mf", opts(new AbortController().signal, engine.transport)); + const holdA = engine.hold((route, body) => route === "start" && body.path === "a.3mf"); + const aSignal = new AbortController(); + const a = loadScene("a.3mf", opts(aSignal.signal, engine.transport)).catch((e) => e); + await flushMicrotasks(); + aSignal.abort(); + expect(isAbort(await a)).toBe(true); + engine.expire("session-1"); + const loaded = await loadScene("b.3mf", opts(new AbortController().signal, engine.transport)); // opens session-2 and loads + expect(loaded.schema).toBe("scene/1"); + const opensBefore = engine.sessionOpens(); + holdA.release(); // A's late start meets an unknown session + await flushMicrotasks(); + expect(engine.sessionOpens()).toBe(opensBefore); // A did not trigger a new session or a restart + expect(engine.starts().filter((s) => s.path === "a.3mf")).toHaveLength(1); + expect(engine.jobs.filter((j) => j.session === "session-2").map((j) => j.state)).toEqual(["succeeded"]); + }); + + it("an engine at its session limit gives SESSION_LIMIT in plain words, and a later load works once there is room", async () => { + const engine = makeEngine({ maxSessions: 0 }); + const failure = (await loadScene("a.3mf", opts(new AbortController().signal, engine.transport)).catch((e) => e)) as SceneError; + expect(failure.code).toBe("SESSION_LIMIT"); + expect(sceneErrorText("SESSION_LIMIT")).toContain("as many 3D views as it allows"); + expect(engine.starts()).toHaveLength(0); + expect(engine.sessionOpens()).toBe(1); // no loop + const roomy = makeEngine(); + expect((await loadScene("a.3mf", opts(new AbortController().signal, roomy.transport))).schema).toBe("scene/1"); + }); + + it("cancel on an expired session is ignored: the load still ends with an AbortError", async () => { + const engine = makeEngine(); + const controller = new AbortController(); + const slowSleep = async () => { engine.expire("session-1"); controller.abort(); }; + const failure = await loadScene("a.3mf", { signal: controller.signal, transport: engine.transport, sleep: slowSleep }).catch((e) => e); + expect(isAbort(failure)).toBe(true); + await flushMicrotasks(); + expect(engine.log.filter((l) => l.route === "cancel")).toHaveLength(1); // sent, answered SESSION_EXPIRED, nothing thrown + }); +}); + +describe("job credentials", () => { + it("status and result carry the session client id; the engine hides a job from any other client id (EXPIRED)", async () => { + const engine = makeEngine(); + await loadScene("a.3mf", opts(new AbortController().signal, engine.transport)); + const calls = engine.log.filter((l) => l.route === "status" || l.route === "result"); + expect(calls.length).toBeGreaterThan(0); + expect(calls.every((c) => c.body.client_id === "session-1" && typeof c.body.job_id === "string")).toBe(true); + // The same job id with a foreign, a missing or an unknown client id is "EXPIRED", never "forbidden". + for (const body of [{ job_id: "job-1", client_id: "someone-else" }, { job_id: "job-1" }, { job_id: "job-999", client_id: "session-1" }]) { + for (const route of ["status", "result"] as const) { + expect(await engine.transport(route, body)).toEqual({ status: 404, body: { error: "EXPIRED" } }); + } + } + expect(sceneErrorText("EXPIRED")).toContain("Try again"); + }); + + it("cancel by request cancels a job only when its seq is exactly the cancelled seq", async () => { + const engine = makeEngine(); + await loadScene("a.3mf", opts(new AbortController().signal, engine.transport)); // job-1, seq 1, finished + const hold = engine.hold((route, body) => route === "status" && body.job_id === "job-2"); + const running = loadScene("b.3mf", opts(new AbortController().signal, engine.transport)).catch((e) => e); // job-2, seq 2, running + await flushMicrotasks(); + // A stale cancel for the earlier attempt (seq 1) must leave the running job alone. + await engine.transport("cancel", { client_id: "session-1", request_id: engine.starts()[0].request_id, seq: 1 }); + expect(engine.jobs.find((j) => j.id === "job-2")!.state).toBe("running"); + await engine.transport("cancel", { client_id: "session-1", request_id: engine.starts()[1].request_id, seq: 2 }); + expect(engine.jobs.find((j) => j.id === "job-2")!.state).toBe("cancelled"); + hold.release(); + await running; + }); + + it("a cancel is dead-through: it refuses its seq and every lower seq, never a higher one", async () => { + const engine = makeEngine(); + await loadScene("warm.3mf", opts(new AbortController().signal, engine.transport)); // session-1, seq 1 + await engine.transport("cancel", { client_id: "session-1", request_id: "never-started", seq: 5 }); + for (const seq of [2, 4, 5]) { + expect(await engine.transport("start", { path: "x.3mf", request_id: `r-${seq}`, client_id: "session-1", seq })).toEqual({ status: 409, body: { error: "CANCELLED_BEFORE_START" } }); + } + expect((await engine.transport("start", { path: "x.3mf", request_id: "r-6", client_id: "session-1", seq: 6 })).status).toBe(200); + }); + + it("after an admitted start is rejected (WORKER_WEDGED, UNSUPPORTED_FORMAT) the next try uses a fresh request id and a higher seq", async () => { + const engine = makeEngine(); + let reject: { status: number; code: string } | null = { status: 503, code: "WORKER_WEDGED" }; + const flaky: SceneTransport = async (route, body) => { + if (route === "start" && reject) { + await engine.transport(route, body); // the engine admitted it (seq consumed), then failed it + const r = reject; reject = null; + return { status: r.status, body: { error: r.code } }; + } + return engine.transport(route, body); + }; + const failure = (await loadScene("a.3mf", opts(new AbortController().signal, flaky)).catch((e) => e)) as SceneError; + expect(failure.code).toBe("WORKER_WEDGED"); + const ok = await loadScene("a.3mf", opts(new AbortController().signal, flaky)); // the user presses Try again + expect(ok.schema).toBe("scene/1"); + const [first, second] = engine.starts(); + expect(second.request_id).not.toBe(first.request_id); + expect(Number(second.seq)).toBeGreaterThan(Number(first.seq)); + // An exact retry of the admitted start returns the current job (the client never sends one: every retry is fresh). + const retry = await engine.transport("start", first); + expect(retry.status).toBe(200); + expect((retry.body as { job_id: string }).job_id).toBe(engine.jobs[0].id); + }); +}); + +describe("a wanted request that is replaced or refused", () => { + it("restarts ONCE with a fresh request id and the next seq, then loads", async () => { + const bodies: Record[] = []; + let starts = 0; + const transport: SceneTransport = async (route, body) => { + if (route === "session") return { status: 200, body: { client_id: "session-x", ttl_s: 900 } }; + if (route === "start") { + bodies.push(body as Record); + return { status: 200, body: ++starts === 1 ? started("cancelled") : started("succeeded", { revision: REVISION }) }; + } + if (route === "result") return { status: 200, body: scene }; + return { status: 200, body: status("cancelled") }; + }; + const out = await loadScene("b.3mf", opts(new AbortController().signal, transport)); + expect(out.schema).toBe("scene/1"); + expect(bodies).toHaveLength(2); + expect(bodies[1].request_id).not.toBe(bodies[0].request_id); + expect(Number(bodies[1].seq)).toBe(Number(bodies[0].seq) + 1); + }); + + it.each([["CANCELLED_BEFORE_START"], ["STALE_START"]])("also restarts once when a start is refused as %s", async (code) => { + let starts = 0; + const transport: SceneTransport = async (route) => { + if (route === "session") return { status: 200, body: { client_id: "session-x", ttl_s: 900 } }; + if (route === "start") return ++starts === 1 ? { status: 409, body: { error: code } } : { status: 200, body: started("succeeded", { revision: REVISION }) }; + if (route === "result") return { status: 200, body: scene }; + return { status: 200, body: status("cancelled") }; + }; + expect((await loadScene("b.3mf", opts(new AbortController().signal, transport))).schema).toBe("scene/1"); + expect(starts).toBe(2); + }); + + it("repeated replacement stops after the second attempt and reports it: no loop", async () => { + let starts = 0; + const transport: SceneTransport = async (route) => { + if (route === "session") return { status: 200, body: { client_id: "session-x", ttl_s: 900 } }; + if (route === "start") { ++starts; return { status: 200, body: started("cancelled") }; } + return { status: 200, body: status("cancelled") }; + }; + const failure = (await loadScene("b.3mf", opts(new AbortController().signal, transport)).catch((e) => e)) as SceneError; + expect(failure.code).toBe("CANCELLED"); + expect(starts).toBe(2); + let refused = 0; + const stale: SceneTransport = async (route) => { + if (route === "session") return { status: 200, body: { client_id: "session-x", ttl_s: 900 } }; + if (route === "start") { ++refused; return { status: 409, body: { error: "STALE_START" } }; } + return { status: 200, body: status("cancelled") }; + }; + expect(((await loadScene("b.3mf", opts(new AbortController().signal, stale)).catch((e) => e)) as SceneError).code).toBe("STALE_START"); + expect(refused).toBe(2); + }); + + it("does not restart when the caller left", async () => { + const controller = new AbortController(); + let starts = 0; + const transport: SceneTransport = async (route) => { + if (route === "session") return { status: 200, body: { client_id: "session-x", ttl_s: 900 } }; + if (route === "start") { ++starts; controller.abort(); return { status: 200, body: started("cancelled") }; } + return { status: 200, body: status("cancelled") }; + }; + expect(isAbort(await loadScene("b.3mf", opts(controller.signal, transport)).catch((e) => e))).toBe(true); + expect(starts).toBe(1); + }); + + it("gives the new refusals plain wording", () => { + expect(sceneErrorText("STALE_START")).toBe("A newer request for the 3D view replaced this one."); + expect(sceneErrorText("CANCELLED_BEFORE_START")).toBe("This 3D view request was cancelled before it started."); + expect(sceneErrorText("SESSION_EXPIRED")).toContain("Try again"); + }); +}); + + +describe("decodeMesh", () => { + const b64 = (bytes: Uint8Array) => btoa(Array.from(bytes, (b) => String.fromCharCode(b)).join("")); + const mesh = (positions: number[], indices: number[]): SceneMesh => ({ + key: { part: "3D/3dmodel.model", object_id: "1" }, vertex_count: positions.length / 3, triangle_count: indices.length / 3, + positions_f32le_base64: b64(new Uint8Array(new Float32Array(positions).buffer)), + indices_u32le_base64: b64(new Uint8Array(new Uint32Array(indices).buffer)), volumes: [], + }); + + it("round-trips little-endian floats and indices", () => { + const out = decodeMesh(mesh([0, 0, 0, 10, 0, 0, 0, 10.5, 0], [0, 1, 2])); + expect(Array.from(out.positions)).toEqual([0, 0, 0, 10, 0, 0, 0, 10.5, 0]); + expect(Array.from(out.indices)).toEqual([0, 1, 2]); + }); + + it("refuses an index past the vertex list and a size that disagrees with the counts", () => { + expect(() => decodeMesh(mesh([0, 0, 0, 1, 0, 0, 0, 1, 0], [0, 1, 3]))).toThrow(SceneError); + const short = mesh([0, 0, 0, 1, 0, 0, 0, 1, 0], [0, 1, 2]); + short.vertex_count = 4; + expect(() => decodeMesh(short)).toThrow(SceneError); + }); +}); diff --git a/desktop/src/lib/scene.ts b/desktop/src/lib/scene.ts new file mode 100644 index 00000000..5d39db86 --- /dev/null +++ b/desktop/src/lib/scene.ts @@ -0,0 +1,434 @@ +// Client for the engine's scene/1 contract (backend/snapstudio_core/data/scene-1.schema.json). Read-only: it asks the +// engine to describe a project, follows the job, and hands back the finished scene. Nothing here edits a file. +import { engineConnection } from "@/api"; + +export type UnitName = "micron" | "millimeter" | "centimeter" | "inch" | "foot" | "meter"; +export type VolumeRole = "part" | "modifier" | "negative" | "support_enforcer" | "support_blocker" | "unknown"; +export type ResourceKey = { part: string; object_id: string }; +export type Bounds = { min: number[]; max: number[] } | null; + +export type SceneVolume = { + id: string; triangle_start: number; triangle_count: number; role: VolumeRole; + source: "prusa_range" | "bambu_part" | "object" | null; +}; +export type SceneMesh = { + key: ResourceKey; vertex_count: number; triangle_count: number; + positions_f32le_base64: string; indices_u32le_base64: string; volumes: SceneVolume[]; +}; +export type ScenePlateRef = { state: "known" | "ambiguous" | "unknown"; plate_id: string | null; source: "plate_config" | null }; +export type SceneNode = { + id: string; parent_id: string | null; resource: ResourceKey; mesh_key: ResourceKey | null; + local_to_parent_mm: number[]; world_mm: number[]; mirrored: boolean; role_context: VolumeRole | null; + build_index: number | null; instance_ref: { build_index: number | null; component_path: number[] }; + plate: ScenePlateRef; placement_state: "known" | "unknown"; printable: boolean | null; + has_non_part_volumes: boolean; bounds_mm: Bounds; finding_ids: string[]; +}; +export type SceneFinding = { + id: string; engine: string; schema: string; pointer: string; scope: "project" | "plate" | "instance"; + kind: "placement" | "size" | "note"; target_ids: string[]; + value: { + code: "PLACEMENT_OUTSIDE_BED" | "SIZE_EXCEEDS_BED"; + overhang_mm: { left: number; right: number; front: number; back: number } | null; + }; +}; +export type LimitationCode = + | "UNKNOWN_VOLUME_ROLE" | "UNKNOWN_PLACEMENT" | "PLATE_MEMBERSHIP_AMBIGUOUS" | "PLATE_MEMBERSHIP_UNKNOWN" + | "PLATES_UNAVAILABLE" | "BED_TEMPLATE_UNAVAILABLE" | "REPEATED_INSTANCE_PLACEMENT_UNVERIFIED" + | "NON_MM_SOURCE_UNIT" | "UNSUPPORTED_UNIT" | "MULTI_PLATE_PLACEMENT_UNCHECKED" | "NO_BUILD_ITEMS"; +export type SceneLimitation = { code: LimitationCode; target_ids: string[] }; +export type SceneBed = { + polygon_mm: number[][]; height_mm: number | null; edge_margin_mm: number; policy: "u1_template" | "fallback"; +}; +export type SceneV1 = { + schema: "scene/1"; revision: string; status: "complete" | "partial"; units: "mm"; axes: "right-handed-z-up"; + sources: { part: string; unit: UnitName; mm_per_unit: number }[]; + bed: SceneBed; meshes: SceneMesh[]; nodes: SceneNode[]; + plates: { id: string; ui_number: number | null; origin_mm: number[] | null }[]; + findings: SceneFinding[]; limitations: SceneLimitation[]; + counts: Record<"nodes" | "meshes" | "vertices" | "triangles" | "rendered_triangles" | "plates" | "findings" | "limitations", number>; + limits: Record; +}; + +export type JobState = "queued" | "running" | "succeeded" | "failed" | "cancelled"; +export type JobStage = "reading" | "parsing" | "encoding" | null; +export type SceneErrorCode = + | "INVALID_REQUEST" | "UNSUPPORTED_FORMAT" | "INVALID_ARCHIVE" | "INVALID_GEOMETRY" | "UNRESOLVED_REFERENCE" + | "LIMIT_EXCEEDED" | "SOURCE_CHANGED" | "CANCELLED" | "TIMEOUT" | "EXPIRED" | "NOT_READY" | "WORKER_WEDGED" | "INTERNAL" + // Client-side only: the engine could not be reached, or sent something that is not a scene/1 document. + | "UNREACHABLE" | "BAD_RESPONSE" + // The engine refused a start as out of order (a newer one was seen from this client) or as already cancelled. + | "STALE_START" | "CANCELLED_BEFORE_START" + // The engine does not know this client session (restarted, or idle too long), or will not open another one. + | "SESSION_EXPIRED" | "SESSION_LIMIT"; +export type JobStatus = { + job_id: string; request_id: string; state: JobState; stage: JobStage; completed: number | null; total: number | null; + error: { code: SceneErrorCode; message: string } | null; revision: string | null; +}; +export type SceneProgress = { state: JobState; stage: JobStage; completed: number | null; total: number | null }; + +export class SceneError extends Error { + readonly code: SceneErrorCode; + constructor(code: SceneErrorCode) { + super(code); + this.name = "SceneError"; + this.code = code; + } +} + +// Plain-language text for each failure. The engine's own message is never shown: it can carry file names. +const ERROR_TEXT: Record = { + INVALID_REQUEST: "The engine could not understand the request for the 3D view.", + UNSUPPORTED_FORMAT: "The 3D view supports 3MF and STL files only.", + INVALID_ARCHIVE: "This file could not be read as a 3MF project, so there is no 3D view.", + INVALID_GEOMETRY: "This file has geometry the 3D view cannot read, so there is no 3D view.", + UNRESOLVED_REFERENCE: "This project points at a part that is not in the file, so the 3D view cannot show it.", + LIMIT_EXCEEDED: "This project is larger than the 3D view can show. The rest of Studio still works on it.", + SOURCE_CHANGED: "The file changed while it was being read. Try again once it has finished saving.", + CANCELLED: "The 3D view was cancelled.", + TIMEOUT: "Reading the project took too long, so the 3D view was stopped.", + EXPIRED: "The 3D view result was discarded by the engine. Try again.", + NOT_READY: "The 3D view is still being prepared. Try again in a moment.", + WORKER_WEDGED: "The engine is still busy with an earlier 3D view. Wait a few seconds and try again.", + INTERNAL: "The engine hit an unexpected problem while building the 3D view.", + UNREACHABLE: "Studio could not reach the local engine, so there is no 3D view.", + BAD_RESPONSE: "The engine sent a 3D view Studio does not understand.", + STALE_START: "A newer request for the 3D view replaced this one.", + CANCELLED_BEFORE_START: "This 3D view request was cancelled before it started.", + SESSION_EXPIRED: "Studio lost its connection to the engine for the 3D view. Try again.", + SESSION_LIMIT: "The engine is serving as many 3D views as it allows. Close another Studio window, then try again.", +}; +export function sceneErrorText(code: SceneErrorCode): string { + return ERROR_TEXT[code] ?? ERROR_TEXT.INTERNAL; +} + +const KNOWN_CODES = new Set(Object.keys(ERROR_TEXT)); +function asCode(value: unknown): SceneErrorCode { + return typeof value === "string" && KNOWN_CODES.has(value) ? (value as SceneErrorCode) : "INTERNAL"; +} + +/** One engine call: POST a JSON body to a scene route and return the parsed body with its HTTP status. */ +export type SceneTransport = ( + route: "session" | "start" | "status" | "result" | "cancel", body: unknown, signal?: AbortSignal, +) => Promise<{ status: number; body: unknown }>; + +export const defaultTransport: SceneTransport = async (route, body, signal) => { + let connection: { base: string; token: string }; + try { + connection = await engineConnection(); + } catch { + throw new SceneError("UNREACHABLE"); + } + let response: Response; + try { + response = await fetch(`${connection.base}/scene/${route}`, { + method: "POST", + headers: { "Content-Type": "application/json", "X-Auth-Token": connection.token }, + body: JSON.stringify(body), + signal, + }); + } catch (error) { + if (signal?.aborted) throw error; + throw new SceneError("UNREACHABLE"); + } + let parsed: unknown = null; + try { parsed = await response.json(); } catch { /* an empty or non-JSON body is handled by the caller */ } + return { status: response.status, body: parsed }; +}; + +export function newRequestId(): string { + const c = (globalThis as { crypto?: Crypto }).crypto; + if (c?.randomUUID) return c.randomUUID(); + const bytes = new Uint8Array(16); + if (c?.getRandomValues) c.getRandomValues(bytes); + else for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256); + return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); +} + +const isObject = (v: unknown): v is Record => typeof v === "object" && v !== null; +const STATES = new Set(["queued", "running", "succeeded", "failed", "cancelled"]); + +function readStatus(body: unknown): JobStatus { + if (!isObject(body) || typeof body.job_id !== "string" || typeof body.state !== "string" || !STATES.has(body.state)) { + throw new SceneError("BAD_RESPONSE"); + } + return body as unknown as JobStatus; +} + +/** What /scene/start answers: a job's identity and state only. It carries no stage, progress or error. */ +export type JobStart = { + job_id: string; request_id: string; state: JobState; revision: string | null; replaced_job_id: string | null; +}; + +function readStart(body: unknown): JobStart { + return readStatus(body) as unknown as JobStart; +} + +function errorFromResponse(status: number, body: unknown): SceneError { + if (isObject(body) && "error" in body) return new SceneError(asCode(body.error)); + return new SceneError(status >= 500 ? "INTERNAL" : "BAD_RESPONSE"); +} + +// ---- Sessions ------------------------------------------------------------------------------------------------------------ +// The engine orders overlapping starts within a SESSION. The client opens one session lazily (the first time it needs one) +// and uses its `client_id` on every start and cancel. Each start attempt takes the next `seq` of the session (strictly +// increasing from 1). The engine's rules, which the stand-in engine in scene.test.ts implements: +// * a start whose seq is not higher than the highest seen is refused (STALE_START). That includes an exact retry of a start +// the engine already processed, so every retry uses a fresh request id and the next seq; +// * a start whose request or seq was cancelled is refused (CANCELLED_BEFORE_START); +// * an unknown or idle-expired session is refused (SESSION_EXPIRED): the client opens a new session (seq starts again at 1) +// and restarts ONCE; more sessions than the engine allows is SESSION_LIMIT (shown, with Try again); +// * the guarantee is per session only: a start from another session replaces the running job as before. +type Session = { clientId: string; seq: number }; +let session: Session | null = null; +let opening: Promise | null = null; + +/** Forgets the session. For tests; the app never needs it. */ +export function resetSceneSession(): void { + session = null; + opening = null; +} +/** The current session's client id, or null before one is opened. For tests and diagnostics. */ +export function currentSceneClientId(): string | null { + return session?.clientId ?? null; +} + +/** Opens the session once, however many loads ask at the same time. A caller can stop waiting without cancelling the open. */ +function ensureSession(transport: SceneTransport, caller: AbortSignal, ms: number): Promise { + if (session) return Promise.resolve(session); + if (!opening) { + const attempt = (async (): Promise => { + const reply = await limited((s) => transport("session", {}, s), new AbortController().signal, ms); + if (reply.status !== 200) throw errorFromResponse(reply.status, reply.body); + const id = isObject(reply.body) ? reply.body.client_id : undefined; + if (typeof id !== "string" || id.length === 0 || id.length > 128) throw new SceneError("BAD_RESPONSE"); + session = { clientId: id, seq: 0 }; + return session; + })(); + opening = attempt; + const done = () => { if (opening === attempt) opening = null; }; + attempt.then(done, done); + } + const shared = opening; + return limited(() => shared, caller, ms); +} + +/** One start attempt: enough to cancel it. */ +export type StartAttempt = { clientId: string; requestId: string; seq: number }; + +const CANCEL_MS = 3000; + +/** + * Tells the engine a start attempt is no longer wanted, by `{client_id, request_id, seq}`, so it works whether or not the + * start has been answered or even delivered (a late start is then refused). Best effort and silent: it runs from cleanup + * paths that must never throw or wait, it is bounded, and it is never awaited, so it cannot hold up the next start. A + * SESSION_EXPIRED answer (the session is gone, so the request is too) needs nothing more. + */ +export function cancelSceneRequest(attempt: StartAttempt, transport: SceneTransport = defaultTransport): void { + const ctl = new AbortController(); + const timer = setTimeout(() => ctl.abort(), CANCEL_MS); + let sent: Promise; + try { + sent = transport("cancel", { client_id: attempt.clientId, request_id: attempt.requestId, seq: attempt.seq }, ctl.signal); + } catch { + clearTimeout(timer); + return; + } + void sent.catch(() => undefined).finally(() => clearTimeout(timer)); +} + + +export type LoadSceneOptions = { + signal: AbortSignal; + /** A fresh id per scene generation, so a cancelled earlier job is never handed back. */ + requestId?: string; + onProgress?: (p: SceneProgress) => void; + pollMs?: number; + transport?: SceneTransport; + sleep?: (ms: number, signal: AbortSignal) => Promise; + /** How long to wait for the engine to answer the start call. Default 15 s. */ + startTimeoutMs?: number; + /** How long to wait for any one status or result answer. Default 30 s. */ + requestTimeoutMs?: number; +}; + +function abortError(): Error { + const e = new Error("aborted"); + e.name = "AbortError"; + return e; +} +export const isAbort = (e: unknown): boolean => isObject(e) && (e as { name?: unknown }).name === "AbortError"; + +function defaultSleep(ms: number, signal: AbortSignal): Promise { + return new Promise((resolve, reject) => { + if (signal.aborted) return reject(abortError()); + const t = setTimeout(() => { signal.removeEventListener("abort", onAbort); resolve(); }, ms); + const onAbort = () => { clearTimeout(t); reject(abortError()); }; + signal.addEventListener("abort", onAbort, { once: true }); + }); +} + +/** + * Runs one engine call that gives up when the caller aborts or after `ms`. The result is a race, so a transport that + * ignores its signal still cannot hold the caller: the answer is dropped. Rejects with an AbortError or a TIMEOUT SceneError. + */ +function limited(run: (signal: AbortSignal) => Promise, caller: AbortSignal, ms: number): Promise { + if (caller.aborted) return Promise.reject(abortError()); + const ctl = new AbortController(); + let timedOut = false; + const onCaller = () => ctl.abort(); + caller.addEventListener("abort", onCaller, { once: true }); + const timer = setTimeout(() => { timedOut = true; ctl.abort(); }, ms); + let onLimit: () => void = () => undefined; + return new Promise((resolve, reject) => { + onLimit = () => reject(timedOut ? new SceneError("TIMEOUT") : abortError()); + ctl.signal.addEventListener("abort", onLimit, { once: true }); + run(ctl.signal).then(resolve, reject); + }).finally(() => { + clearTimeout(timer); + caller.removeEventListener("abort", onCaller); + ctl.signal.removeEventListener("abort", onLimit); + }); +} + +// Outcomes that mean "this request was replaced or cancelled by something other than the user leaving": the engine +// replaced it with a newer start, or refused a start as out of order or already cancelled. +const SUPERSEDED = new Set(["CANCELLED", "STALE_START", "CANCELLED_BEFORE_START"]); + +/** + * Starts a scene job for `path`, follows it, and resolves with the scene. If `signal` aborts, the browser requests are + * aborted AND the engine is told to cancel the start attempt by client id, request id and seq, at once (aborting a request + * alone does not stop work in the engine); the promise then rejects with an AbortError. Every other failure rejects with a + * SceneError. + * + * Ordering of overlapping starts is the engine's job, within a session (see "Sessions" above). As resilience, not as the + * fix, there are at most two automatic restarts, each with a fresh request id and the next seq: ONE after SESSION_EXPIRED + * (a new session is opened first), and ONE when a wanted request comes back cancelled or refused as superseded. A second + * outcome of the same kind is reported as it is. + */ +export async function loadScene(path: string, opts: LoadSceneOptions): Promise { + const { signal } = opts; + if (signal.aborted) throw abortError(); + let sessionRestarted = false; + let supersededRestarted = false; + for (let attempt = 0; ; attempt++) { + try { + return await runOnce(path, opts, attempt === 0 ? opts.requestId ?? newRequestId() : newRequestId()); + } catch (error) { + if (!(error instanceof SceneError) || signal.aborted) throw error; + if (error.code === "SESSION_EXPIRED" && !sessionRestarted) { sessionRestarted = true; continue; } + if (SUPERSEDED.has(error.code) && !supersededRestarted) { supersededRestarted = true; continue; } + throw error; + } + } +} + +async function runOnce(path: string, opts: LoadSceneOptions, requestId: string): Promise { + const { signal } = opts; + const transport = opts.transport ?? defaultTransport; + const sleep = opts.sleep ?? defaultSleep; + const pollMs = opts.pollMs ?? 250; + const startMs = opts.startTimeoutMs ?? 15000; + const requestMs = opts.requestTimeoutMs ?? 30000; + + // Registered before anything is sent, so leaving at ANY moment cancels the start attempt once there is one (before the + // session is known, or before the attempt takes its seq, nothing has been sent and there is nothing to cancel). + let attempt: StartAttempt | null = null; + const onAbort = () => { if (attempt) cancelSceneRequest(attempt, transport); }; + signal.addEventListener("abort", onAbort, { once: true }); + try { + const sess = await ensureSession(transport, signal, startMs); + if (signal.aborted) throw abortError(); + attempt = { clientId: sess.clientId, requestId, seq: ++sess.seq }; + const sent = attempt; + const started = await limited( + (s) => transport("start", { path, request_id: sent.requestId, client_id: sent.clientId, seq: sent.seq }, s), signal, startMs, + ); + if (started.status !== 200) throw errorFromResponse(started.status, started.body); + const job = readStart(started.body); + const jobId = job.job_id; + // The start answer has no progress or error fields, so it becomes a status with those unknown (null). + let status: JobStatus = { + job_id: job.job_id, request_id: job.request_id, state: job.state, stage: null, completed: null, total: null, error: null, revision: job.revision, + }; + let fromStart = true; + for (;;) { + if (signal.aborted) throw abortError(); + opts.onProgress?.({ state: status.state, stage: status.stage, completed: status.completed, total: status.total }); + if (status.state === "succeeded") break; + if (status.state === "failed") { + // Asking again with a request id the engine still holds returns a failed job without its reason; fetch it. + if (fromStart) { + const why = await limited((s) => transport("status", { job_id: jobId, client_id: sent.clientId }, s), signal, requestMs); + if (why.status !== 200) throw errorFromResponse(why.status, why.body); + status = readStatus(why.body); + fromStart = false; + } + throw new SceneError(asCode(status.error?.code)); + } + if (status.state === "cancelled") throw new SceneError("CANCELLED"); + await sleep(pollMs, signal); + const polled = await limited((s) => transport("status", { job_id: jobId, client_id: sent.clientId }, s), signal, requestMs); + if (polled.status !== 200) throw errorFromResponse(polled.status, polled.body); + status = readStatus(polled.body); + fromStart = false; + } + const result = await limited( + (s) => transport("result", { job_id: jobId, client_id: sent.clientId, ...(status.revision ? { expected_revision: status.revision } : {}) }, s), + signal, requestMs, + ); + if (signal.aborted) throw abortError(); + if (result.status !== 200) throw errorFromResponse(result.status, result.body); + if (!isObject(result.body) || result.body.schema !== "scene/1" || !Array.isArray(result.body.nodes)) { + throw new SceneError("BAD_RESPONSE"); + } + return result.body as unknown as SceneV1; + } catch (error) { + if (signal.aborted && !isAbort(error)) throw abortError(); + if (error instanceof SceneError) { + // An answer that never came: stop the attempt too (a no-op if it is already over). + if (error.code === "TIMEOUT" && attempt) cancelSceneRequest(attempt, transport); + // The session is gone: forget it, so the next attempt opens a new one (seq starts again at 1). + if (error.code === "SESSION_EXPIRED" && attempt && session?.clientId === attempt.clientId) session = null; + } + throw error; + } finally { + signal.removeEventListener("abort", onAbort); + } +} + + +// ---- Geometry helpers ------------------------------------------------------------------------------------------- + +function base64Bytes(text: string): Uint8Array { + const binary = atob(text); + const out = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i); + return out; +} + +/** Decodes one mesh's little-endian float32 positions and uint32 indices. Throws BAD_RESPONSE when sizes disagree. */ +export function decodeMesh(mesh: SceneMesh): { positions: Float32Array; indices: Uint32Array } { + let positionBytes: Uint8Array; + let indexBytes: Uint8Array; + try { + positionBytes = base64Bytes(mesh.positions_f32le_base64); + indexBytes = base64Bytes(mesh.indices_u32le_base64); + } catch { + throw new SceneError("BAD_RESPONSE"); + } + if (positionBytes.length !== mesh.vertex_count * 12 || indexBytes.length !== mesh.triangle_count * 12) { + throw new SceneError("BAD_RESPONSE"); + } + // Copy into aligned buffers: a Uint8Array view from atob has no alignment promise, and the data is little endian. + const positions = new Float32Array(mesh.vertex_count * 3); + const indices = new Uint32Array(mesh.triangle_count * 3); + const pv = new DataView(positionBytes.buffer, positionBytes.byteOffset, positionBytes.byteLength); + const iv = new DataView(indexBytes.buffer, indexBytes.byteOffset, indexBytes.byteLength); + for (let i = 0; i < positions.length; i++) positions[i] = pv.getFloat32(i * 4, true); + for (let i = 0; i < indices.length; i++) { + const v = iv.getUint32(i * 4, true); + if (v >= mesh.vertex_count) throw new SceneError("BAD_RESPONSE"); + indices[i] = v; + } + return { positions, indices }; +} diff --git a/desktop/src/routes/DesignInsights.tsx b/desktop/src/routes/DesignInsights.tsx index 65c69e3b..abcc0701 100644 --- a/desktop/src/routes/DesignInsights.tsx +++ b/desktop/src/routes/DesignInsights.tsx @@ -30,6 +30,7 @@ import { PlacementCard } from "@/components/PlacementCard"; import { PreflightCard } from "@/components/PreflightCard"; import { ColorPlanCard } from "@/components/ColorPlanCard"; import { DesignHealth } from "@/components/DesignHealth"; +import { ProjectSceneSection } from "@/components/project-scene/ProjectSceneSection"; import { HeartPulse } from "lucide-react"; import { PrintRiskSignals } from "@/components/PrintRiskSignals"; import { @@ -211,6 +212,8 @@ export default function DesignInsights() {
+ {doctor.status === "done" && } + {file.ext !== "stl" && !prepareBlocked && void runConvertWithoutSetup()} />} {file.ext !== "stl" && } {file.ext === "stl" &&

{STARTER_NOTICE}

} diff --git a/desktop/src/routes/LiveWorkspace.tsx b/desktop/src/routes/LiveWorkspace.tsx index c7269427..a342c3eb 100644 --- a/desktop/src/routes/LiveWorkspace.tsx +++ b/desktop/src/routes/LiveWorkspace.tsx @@ -14,6 +14,7 @@ import { usePrinter } from "@/store/printer"; import { useOpenFile } from "@/hooks/useOpenFile"; import { StrategyPicker } from "@/components/StrategyPicker"; import { DesignHealth } from "@/components/DesignHealth"; +import { ProjectSceneSection } from "@/components/project-scene/ProjectSceneSection"; import { mesh as apiMesh, insights as apiInsights, toolheadFit as apiToolheadFit, report as apiReport } from "@/api"; import { readinessView } from "@/lib/readiness"; import { OrcaHandoff } from "@/components/OrcaHandoff"; @@ -120,6 +121,8 @@ export default function LiveWorkspace() {
)} + {doctor.status === "done" && } + {doctor.status === "done" && meshQ.data?.available && ( diff --git a/desktop/src/vendor/slicerx/LICENSE-APACHE b/desktop/src/vendor/slicerx/LICENSE-APACHE new file mode 100644 index 00000000..6b1af957 --- /dev/null +++ b/desktop/src/vendor/slicerx/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2026 The SlicerX contributors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/desktop/src/vendor/slicerx/NOTICE b/desktop/src/vendor/slicerx/NOTICE new file mode 100644 index 00000000..fc973006 --- /dev/null +++ b/desktop/src/vendor/slicerx/NOTICE @@ -0,0 +1,51 @@ +SlicerX +Copyright (C) 2026 The SlicerX contributors + +Made possible by SlicerX: https://slicerx.app/support + +Everything the SlicerX contributors wrote, including the engine, the CAD +layer, mimir, the apps and the SlicerX edition (editions/slicerx/), is +licensed under the Apache License 2.0 (LICENSE-APACHE). Each file's SPDX +header states its license. + +Attribution. Under section 4(d) of the Apache License, anyone who +redistributes SlicerX or a work built on it must pass on this NOTICE. Show +the line "Made possible by SlicerX" with the link above wherever your product shows +third-party credits, such as an About screen, a credits page or the +documentation. If your product shows no such credits, put it in a NOTICE or +credits file that ships with it. + +The stock printer, filament and process profiles in packages/profiles/ come +from the profile resources of OrcaSlicer and Bambu Studio and are licensed +under the GNU Affero General Public License, version 3 or later +(LICENSES/AGPL-3.0-or-later.txt), as is +packages/core/bench/compare/orca_base.json. REUSE.toml lists these paths. The +engine, the sx command line tool and the C ABI do not use them. The SlicerX +app ships them, so the app as distributed is covered by the AGPL as a whole. +docs/licensing.md has the details. + +SlicerX is its own slicer. Its slicing engine and user interface are written +for SlicerX and contain no code or help text from OrcaSlicer, Bambu Studio, +PrusaSlicer or Slic3r. Setting key names follow the ones those slicers use so +that profiles and project files interchange, and SlicerX reads a user's own +OrcaSlicer, Bambu Studio and PrusaSlicer profile and 3MF files. + +Third-party code, data and fonts keep their own licenses. THIRD-PARTY.md lists +what ships and under which terms, including the three libraries vendored in +packages/vendor with our changes (i_overlay, boostvoronoi, cpp_map), the STEP +reader built from occt-import-js and Open CASCADE Technology (LGPL-2.1; SlicerX +makes use of facilities provided by the Open CASCADE Technology software; the +source offer is in packages/vendor/occt-import-js/SOURCE.md), Cisco's OpenH264 +binary, which is downloaded on Linux and never bundled, and the SigLIP2 model +weights used by the print watch. The full per-version list is generated at +release time into THIRD_PARTY_LICENSES and shipped with every build. + +The aegis wall generator follows the method of preFlight's Athena walls, with +thanks to the preFlight authors. SlicerX contains none of their code. + +"SlicerX", the SlicerX logo, and the Subban theme artwork are trademarks or +reserved brand assets of the SlicerX project. The open source license grants +no rights in them beyond the "Made possible by SlicerX" credit above. A fork must not +call itself SlicerX. TRADEMARK.md explains what a white-label edition may +and may not do with the name. Printer maker names and logos belong to their +owners and are used only to identify their printers. diff --git a/desktop/src/vendor/slicerx/UPDATING.md b/desktop/src/vendor/slicerx/UPDATING.md new file mode 100644 index 00000000..2e0c1f75 --- /dev/null +++ b/desktop/src/vendor/slicerx/UPDATING.md @@ -0,0 +1,136 @@ +# Vendored SlicerX viewport: provenance and local changes + +Source: (Apache-2.0), commit +`edb521fe41306dd60d01bda8a0f6bf8aa54fcb29` (committed 2026-10-08, "fix(app): a new open replaces one still +running, with no save prompt"). `@slicerx/viewport` is not published on npm, so the source is vendored. +Attribution: `LICENSE-APACHE` and `NOTICE` (including "Made possible by SlicerX") are kept verbatim from +`packages/ui/viewport/`; the credit is repeated in `THIRD_PARTY_NOTICES.md` and in the 3D view panel. + +## What is here + +* `viewport/` - every file of `packages/ui/viewport/src/` except upstream `index.ts` (36 files). The upstream + `viewport.ts` imports the others at module level, so none can be left out without rewriting it. +* `contracts/preview.ts`, `slice.ts`, `settings.ts` - the part of `packages/contracts/src/` the viewport imports + (SXPV buffer types and constants, `Bed`). `settings.ts` and `slice.ts` are almost all types; the few constants and helpers in them are not used by the viewport. +* `LICENSE-APACHE`, `NOTICE`. +* Studio-authored files (not upstream, no upstream hash): `entry.ts`, `contracts/index.ts`, `error-cause.d.ts`, this file. + +NOT vendored: upstream tests (`packages/ui/viewport/test`, so vitest never collects them), bench, demo, `data/`, docs, +`@slicerx/embed`, the engine, profiles and every AGPL-licensed resource of the SlicerX repository. + +## Editing code is bundled, and unreachable from Studio + +Upstream `viewport.ts` constructs its move, rotate, scale, paint, cut, sketch and push machinery +(`painter.ts`, `paint.ts`, `gizmo.ts`, `cutplane.ts`, `cadtools.ts`, `rings.ts`, `scaling.ts`) in its constructor, +and about 190 lines of it refer to them. They were **not** removed: that would be an extensive rewrite of a pinned file. +They are in the bundle. Studio keeps them inert by construction: + +* **Enforced where.** `src/components/project-scene/defaultViewport.ts` is the only file that imports the viewport's + factory (`entry.ts`) and the only one that touches its tool: it calls `setTool("probe")` once (a click only reports what is + under the cursor; nothing is selected, dragged or painted), keeps the viewport in a closure, and returns a + `ReadOnlyViewport` built from an `InspectionPort` that has no `setTool`, no generic `on`, no editing member and no handle. + A throw after the viewport exists disposes it. `readOnlyViewport.ts` holds the facade and a type-only import of the + vendor entry; `credits.ts` imports `NOTICE` and `LICENSE-APACHE` as plain text and nothing else from this tree. +* `readOnly.guard.test.ts` scans every non-test file in `src/` (not only the view's folder) and fails on any other + mention of this tree (import, re-export, dynamic or computed `import()`, `?raw`, relative path), on any editing member + name in any spelling, and on `createViewport` outside the adapter. Mutation tests prove it fails for bypasses placed in + `project-scene/sub/`, `routes/` and `lib/`. When you update the vendored source, a new upstream default that turned an + editing tool on under `probe` is what the real-browser interaction check (in the docs README) would catch. +* `readOnlyViewport.test.ts` has a type-level test that editing calls, `setTool` and a generic `on` do not type-check on + the facade or the port; `defaultViewport.test.ts` tests the adapter against a stand-in viewport. +* `docs/testing/project-viewer/README.md` records a real-browser run that drives mouse, modifier and keyboard input at + the viewport and shows no object moved, with a control run (the upstream default tool) that does move it. + +Do not describe this code as removed. + +## Local changes (every one) + +1. **Import path, 7 files.** `from '@slicerx/contracts'` becomes `from '../contracts/index'` in `viewport/palette.ts`, + `stage.ts`, `summary.ts`, `toolchanger.ts`, `toolpaths.ts`, `types.ts` and `viewport.ts` (one line each). + Reason: the contracts package is not published and Studio's TypeScript and Vite configuration are not changed to alias it. + **Modification notice (second documented patch).** In each of the same seven files a clearly marked comment block + ("MODIFIED BY SNAPMAKER STUDIO ...") sits directly after the upstream header, naming the single change, the upstream + repository and commit, and this file. The upstream copyright and SPDX lines and license references are untouched. The + notice is added so a reader of any one file can see it is not byte-for-byte upstream (Apache License 2.0, section 4(b)). + Nothing else in these files differs from upstream. +2. **`contracts/index.ts`** (new, Studio-authored): `export * from './preview'; export type { Bed } from './slice'`. +3. **`entry.ts`** (new, Studio-authored): re-exports `createViewport` and a handful of types. Replaces upstream `index.ts`, + which re-exports the editing helpers. +4. **`error-cause.d.ts`** (new, Studio-authored): upstream calls `new Error(message, { cause })`, which the ES2022 lib + types but this project's ES2020 lib does not (TS2554, at line 292 of the upstream `viewport.ts`). The file declares only that constructor + form. No React, Vite or TypeScript upgrade, no lib or target change. +5. **Line endings:** files are stored with LF, as in the upstream tree and as `.gitattributes` requires. + +Nothing else differs. `project-scene/vendor.integrity.test.ts` checks this table: for every verbatim file the git blob id of its +content equals the upstream blob id here; for the seven patched files the notice block is present, the import path is the +only other difference, and no other vendored file carries a notice; every sha256 below equals the file as stored. + +## File table + +"Upstream blob" is the git blob id at the pinned commit (first 12 hex). "sha256" is of the file as stored here. + +| Vendored file | Upstream path | Upstream blob | sha256 (12) | Status | +|---|---|---|---|---| +| `viewport/brim.ts` | `packages/ui/viewport/src/brim.ts` | 479e1e33edfa | fb8a7b864a74 | verbatim | +| `viewport/cadtools.ts` | `packages/ui/viewport/src/cadtools.ts` | 44bff3b6c1cc | 9f82c17e98c9 | verbatim | +| `viewport/camera.ts` | `packages/ui/viewport/src/camera.ts` | 5f4b92397d8e | 32d48e858024 | verbatim | +| `viewport/contour.ts` | `packages/ui/viewport/src/contour.ts` | b245e9e414de | 4a4be2307fda | verbatim | +| `viewport/controls.ts` | `packages/ui/viewport/src/controls.ts` | d50082ebccc5 | 22dc0cbbf6d6 | verbatim | +| `viewport/cutplane.ts` | `packages/ui/viewport/src/cutplane.ts` | 339cf6c39515 | c423d79d8480 | verbatim | +| `viewport/faces.ts` | `packages/ui/viewport/src/faces.ts` | 7648f2e9503f | 22796530c9d3 | verbatim | +| `viewport/firstframe.ts` | `packages/ui/viewport/src/firstframe.ts` | e1eab56a2cda | a7e9d4222ce1 | verbatim | +| `viewport/gantry.ts` | `packages/ui/viewport/src/gantry.ts` | 56dddaaaecf5 | e48191d2d81a | verbatim | +| `viewport/gaps.ts` | `packages/ui/viewport/src/gaps.ts` | eef431a85cf3 | 6e6bfaa3287c | verbatim | +| `viewport/gizmo.ts` | `packages/ui/viewport/src/gizmo.ts` | 00d6dc4215eb | 19472cccc952 | verbatim | +| `viewport/gizmobindings.ts` | `packages/ui/viewport/src/gizmobindings.ts` | 3458538554c3 | 74ed2817883d | verbatim | +| `viewport/gpu.ts` | `packages/ui/viewport/src/gpu.ts` | 08294f84a111 | 458c44e4d0f5 | verbatim | +| `viewport/guides.ts` | `packages/ui/viewport/src/guides.ts` | 234313c6972f | 1348c669721a | verbatim | +| `viewport/headparts.ts` | `packages/ui/viewport/src/headparts.ts` | 9e023b7a8a73 | 3199f9580328 | verbatim | +| `viewport/headpath.ts` | `packages/ui/viewport/src/headpath.ts` | f400e190f8af | b4aaed478599 | verbatim | +| `viewport/heads.ts` | `packages/ui/viewport/src/heads.ts` | 902ef4a53d65 | 3789c7b6f89a | verbatim | +| `viewport/layerheights.ts` | `packages/ui/viewport/src/layerheights.ts` | 8d7c8aa86145 | a4028eda71ad | verbatim | +| `viewport/materials.ts` | `packages/ui/viewport/src/materials.ts` | 53860e313a69 | 7e66c0fcf1a5 | verbatim | +| `viewport/model.ts` | `packages/ui/viewport/src/model.ts` | 6b1ee5cbf4d8 | 40b55e95eb7d | verbatim | +| `viewport/paint.ts` | `packages/ui/viewport/src/paint.ts` | ecfa8be661a9 | 168d45c0d93e | verbatim | +| `viewport/painter.ts` | `packages/ui/viewport/src/painter.ts` | 00cbde84fbc8 | b6df28902cac | verbatim | +| `viewport/palette.ts` | `packages/ui/viewport/src/palette.ts` | 1c03b359dc03 | 7318d56bd3fe | **patched** (import path, plus a modification notice) | +| `viewport/post.ts` | `packages/ui/viewport/src/post.ts` | 4f4b5388e138 | 7273ee20d53d | verbatim | +| `viewport/probe.ts` | `packages/ui/viewport/src/probe.ts` | 956d63efa13e | d912fca27139 | verbatim | +| `viewport/purge.ts` | `packages/ui/viewport/src/purge.ts` | 4903d225bf78 | 1745134b0962 | verbatim | +| `viewport/rings.ts` | `packages/ui/viewport/src/rings.ts` | 54a1ceb1f77f | 61f07293728d | verbatim | +| `viewport/scaling.ts` | `packages/ui/viewport/src/scaling.ts` | 4981c9aa9603 | 4c5853161dcd | verbatim | +| `viewport/stage.ts` | `packages/ui/viewport/src/stage.ts` | 4f2c7df9d316 | 9f08d80b4a2e | **patched** (import path, plus a modification notice) | +| `viewport/strikes.ts` | `packages/ui/viewport/src/strikes.ts` | 2437eb5d8802 | 15cd9cbb2807 | verbatim | +| `viewport/summary.ts` | `packages/ui/viewport/src/summary.ts` | c00093cf95f0 | b930a8431c33 | **patched** (import path, plus a modification notice) | +| `viewport/toolchanger.ts` | `packages/ui/viewport/src/toolchanger.ts` | c77bde8a45f6 | bf66f54c2280 | **patched** (import path, plus a modification notice) | +| `viewport/toolhead.ts` | `packages/ui/viewport/src/toolhead.ts` | 3c4f42934cc7 | 74b6e31d0859 | verbatim | +| `viewport/toolpaths.ts` | `packages/ui/viewport/src/toolpaths.ts` | 168619855730 | fa547bb5ddf9 | **patched** (import path, plus a modification notice) | +| `viewport/types.ts` | `packages/ui/viewport/src/types.ts` | 3e41e01471f1 | 16ae58080b68 | **patched** (import path, plus a modification notice) | +| `viewport/viewport.ts` | `packages/ui/viewport/src/viewport.ts` | 192b487a6879 | 59d4f25cd48f | **patched** (import path, plus a modification notice) | +| `contracts/preview.ts` | `packages/contracts/src/preview.ts` | 9a5ee2453416 | 8a8713b8e330 | verbatim | +| `contracts/slice.ts` | `packages/contracts/src/slice.ts` | 84d8f8a5aecd | d396019b7dbd | verbatim | +| `contracts/settings.ts` | `packages/contracts/src/settings.ts` | 6660497098be | 20c6047ea2d1 | verbatim | +| `LICENSE-APACHE` | `packages/ui/viewport/LICENSE-APACHE` | 6b1af957a1a6 | 73e6451273ce | verbatim | +| `NOTICE` | `packages/ui/viewport/NOTICE` | fc9730069d4c | 2dca0c6b058d | verbatim | + +## Dependencies and licences + +* `three` 0.186.1 (MIT), pinned exactly in `desktop/package.json`; the viewport imports `three` and + `three/addons/controls/OrbitControls.js` (same package). `@types/three` 0.186.0 (MIT, development only; there is + no 0.186.1 of it) is pinned exactly. +* No other runtime dependency is added. The viewport's own devDependencies (playwright-core, vite, vitest, typescript) + are not used. `@types/three` pulls type packages only (`@dimforge/rapier3d-compat`, `@tweenjs/tween.js`, + `@types/stats.js`, `@types/webxr`, `fflate`, `meshoptimizer`); none are bundled. +* The vendored source contains no network access, workers, `eval`, `new Function` or blob URLs (checked with a source + search), so the Content-Security-Policy in `src-tauri/tauri.conf.json` is unchanged. + +## How to update + +1. Fetch the new commit and diff `packages/ui/viewport/src` and the three `packages/contracts/src` files above against + this tree. Re-apply the seven import-path edits, regenerate the table, update the commit id here and in + `THIRD_PARTY_NOTICES.md`. +2. Keep `three` and `@types/three` pinned to the version the viewport declares; edit `package-lock.json` by hand + (see the lockfile guard) and prove it with `npm ci`. +3. Run `npm run test`, `npx tsc --noEmit`, `npm run build`, then the browser checks in + `docs/testing/project-viewer/README.md`. The read-only guard tests must still pass; if a new upstream default turns + an editing tool on under `probe`, the interaction check fails. diff --git a/desktop/src/vendor/slicerx/contracts/index.ts b/desktop/src/vendor/slicerx/contracts/index.ts new file mode 100644 index 00000000..e8ec4c1b --- /dev/null +++ b/desktop/src/vendor/slicerx/contracts/index.ts @@ -0,0 +1,3 @@ +// Studio-authored barrel (not upstream): the subset of @slicerx/contracts the vendored viewport imports. +export * from "./preview"; +export type { Bed } from "./slice"; diff --git a/desktop/src/vendor/slicerx/contracts/preview.ts b/desktop/src/vendor/slicerx/contracts/preview.ts new file mode 100644 index 00000000..9a5ee245 --- /dev/null +++ b/desktop/src/vendor/slicerx/contracts/preview.ts @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// The SXPV preview buffer format (docs/architecture.md, "SXPV +// preview buffer format") and a zero-copy reader. Rust writes it in sx-core. + +export const SXPV_MAGIC = 0x56505853 // "SXPV" as a little-endian u32 +export const SXPV_VERSION = 1 +export const SXPV_HEADER_BYTES = 32 +export const SXPV_SEGMENT_BYTES = 32 +export const SXPV_TRAVEL_BYTES = 16 +export const SXPV_FLAG_TRAVELS = 1 +/** Per-segment extras follow the travels; only present together with travels and G-code. */ +export const SXPV_FLAG_EXTRAS = 2 +export const SXPV_EXTRA_BYTES = 8 +/** + * Per-segment object index follows the extras (or the travels when there are none): one u16 per segment, the + * index in the request's `plate.objects`, padded to four bytes. Written when the plate has two or more objects; + * readers that do not know the flag skip it. + */ +export const SXPV_FLAG_OBJECTS = 4 +export const SXPV_OBJECT_BYTES = 2 +/** + * With the extras: their G-code lines count from the segment's layer's `;LAYER_CHANGE` line (0xffffffff when + * unknown), as one shard of a parallel slice writes them. Stitching makes them absolute with the finished file's + * layer lines (0 when those are missing) and clears the flag, so only raw shard buffers carry it. + */ +export const SXPV_FLAG_LAYER_LINES = 8 +/** The object index of the skirt, a brim shared by several objects, the prime tower and custom G-code. */ +export const SXPV_OBJECT_NONE = 0xffff + +/** Byte offsets inside one 32-byte segment record. */ +export const SXPV_SEGMENT = { + x0: 0, y0: 4, x1: 8, y1: 12, z: 16, + widthUm: 20, heightUm: 22, + feature: 24, tool: 25, speedDeciMmS: 26, + flowMm3S: 28, +} as const + +/** Byte offsets inside one 8-byte extras record (one per segment, in segment order). */ +export const SXPV_EXTRA = { fan: 0, flags: 1, nozzleC: 2, gcodeLine: 4 } as const +/** Bits of the extras `flags` byte. They sit on the first segment of a path (seam: of a closed wall loop). */ +export const SXPV_EXTRA_FLAG = { retract: 1, lift: 2, seam: 4, pathStart: 8 } as const +/** Travel flag bytes (one per travel) use the retract and lift bits: the nozzle retracted or lifted for that move. */ + +export const FEATURE = { + outerWall: 0, + innerWall: 1, + overhangWall: 2, + topSurface: 3, + bottomSurface: 4, + internalSolid: 5, + sparseInfill: 6, + bridge: 7, + support: 8, + supportInterface: 9, + brimSkirt: 10, + ironing: 11, + gapFill: 12, + primeTower: 13, + custom: 14, + skirt: 15, + internalBridge: 16, +} as const +export type FeatureId = (typeof FEATURE)[keyof typeof FEATURE] + +export interface PreviewBuffers { + raw: ArrayBuffer + version: number + segmentCount: number + layerCount: number + travelCount: number + toolCount: number + layerHeight: number + /** First segment index of each layer; length layerCount + 1, last entry = segmentCount. */ + layerStart: Uint32Array + layerZ: Float32Array + layerTimeS: Float32Array + /** First travel index of each layer, or null when the buffer has no travels. */ + travelStart: Uint32Array | null + /** Byte offset of the first segment record in raw (4-byte aligned). */ + segmentsOffset: number + /** Byte offset of the first travel record, or -1 when there are none. */ + travelsOffset: number + /** + * Byte offset of the first segment's 8-byte extras record (fan 0 to 255, flags, nozzle temperature in C, + * G-code line, 1-based, 0 when unknown), or -1 when the buffer has no extras. + */ + extrasOffset: number + /** Byte offset of the travel flag bytes (one per travel, retract and lift bits), or -1. */ + travelFlagsOffset: number + /** + * Byte offset of the per-segment object indices (u16, index in the request's objects, SXPV_OBJECT_NONE for none), + * or -1 when the buffer has none (a plate of one object, or an older engine). + */ + objectsOffset: number +} + +export function readPreview(raw: ArrayBuffer): PreviewBuffers { + const v = new DataView(raw) + if (raw.byteLength < SXPV_HEADER_BYTES || v.getUint32(0, true) !== SXPV_MAGIC) throw new Error('Not an SXPV buffer') + const version = v.getUint16(4, true) + if (version !== SXPV_VERSION) throw new Error(`Unsupported SXPV version ${version}`) + const flags = v.getUint16(6, true) + const segmentCount = v.getUint32(8, true) + const layerCount = v.getUint32(12, true) + const travelCount = v.getUint32(16, true) + const toolCount = v.getUint32(20, true) + const layerHeight = v.getFloat32(24, true) + let o = SXPV_HEADER_BYTES + const layerStart = new Uint32Array(raw, o, layerCount + 1); o += (layerCount + 1) * 4 + const layerZ = new Float32Array(raw, o, layerCount); o += layerCount * 4 + const layerTimeS = new Float32Array(raw, o, layerCount); o += layerCount * 4 + const hasTravels = (flags & SXPV_FLAG_TRAVELS) !== 0 + const travelStart = hasTravels ? new Uint32Array(raw, o, layerCount + 1) : null + if (hasTravels) o += (layerCount + 1) * 4 + const segmentsOffset = o; o += segmentCount * SXPV_SEGMENT_BYTES + const travelsOffset = hasTravels ? o : -1 + if (travelsOffset >= 0) o += travelCount * SXPV_TRAVEL_BYTES + let extrasOffset = -1 + let travelFlagsOffset = -1 + if ((flags & SXPV_FLAG_EXTRAS) !== 0 && hasTravels) { + extrasOffset = o; o += segmentCount * SXPV_EXTRA_BYTES + travelFlagsOffset = o; o += travelCount + o = (o + 3) & ~3 + } + let objectsOffset = -1 + if ((flags & SXPV_FLAG_OBJECTS) !== 0) { + objectsOffset = o; o += segmentCount * SXPV_OBJECT_BYTES + o = (o + 3) & ~3 + } + if (o > raw.byteLength) throw new Error('Truncated SXPV buffer') + return { raw, version, segmentCount, layerCount, travelCount, toolCount, layerHeight, layerStart, layerZ, layerTimeS, travelStart, segmentsOffset, travelsOffset, extrasOffset, travelFlagsOffset, objectsOffset } +} + +/** The object index of a segment (index in the request's objects), or -1 when unknown or none. */ +export function objectOfSegment(b: PreviewBuffers, segment: number): number { + if (b.objectsOffset < 0 || segment < 0 || segment >= b.segmentCount) return -1 + const k = new DataView(b.raw).getUint16(b.objectsOffset + segment * SXPV_OBJECT_BYTES, true) + return k === SXPV_OBJECT_NONE ? -1 : k +} diff --git a/desktop/src/vendor/slicerx/contracts/settings.ts b/desktop/src/vendor/slicerx/contracts/settings.ts new file mode 100644 index 00000000..66604970 --- /dev/null +++ b/desktop/src/vendor/slicerx/contracts/settings.ts @@ -0,0 +1,302 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Settings schema types. Keys are OrcaSlicer's own names. +import type { SliceStage } from './slice' + +export type SettingSection = 'process' | 'filament' | 'printer' +/** + * Scalar types first, then the per-extruder lists Orca stores as arrays + * (`floats` is a list of numbers, `points` a list of [x, y] pairs). A + * `floatOrPercent` value is a string such as `0.42` or `110%`, as in Orca. + */ +export type SettingType = + | 'float' | 'int' | 'bool' | 'percent' | 'floatOrPercent' | 'enum' | 'string' | 'gcode' | 'point' + | 'floats' | 'ints' | 'bools' | 'percents' | 'floatsOrPercents' | 'enums' | 'strings' | 'points' | 'pointsGroups' +export type SettingValue = number | boolean | string | number[] | boolean[] | string[] | [number, number][] | [number, number][][] +export type SettingUnit = + | 'mm' | 'mm/s' | 'mm/s2' | 'mm3/s' | '%' | 'C' | 's' | 'g/cm3' | 'deg' | 'money/kg' + | 'mm3' | 'layers' | 'Hz' | 'delta-C' | 'money/h' +export type SettingMode = 'simple' | 'advanced' | 'expert' | 'develop' | 'hidden' +export type SettingIntent = 'quality' | 'strength' | 'speed' | 'supports' | 'adhesion' | 'multicolor' | 'effects' | 'output' +export type PilotRule = 'edit' | 'guarded' | 'read' + +/** A key is enabled only while every condition holds, as in Orca's own toggles. */ +export interface SettingCondition { + key: string + op: 'eq' | 'ne' | 'gt' | 'ge' | 'lt' | 'le' | 'in' | 'notin' + value: SettingValue | SettingValue[] +} + +export interface SettingDef { + /** Orca key, such as `layer_height` or `sparse_infill_density`. */ + key: string + section: SettingSection + type: SettingType + unit?: SettingUnit + default: SettingValue + /** Recommended range. Where the knowledge catalog gives Pilot bounds these are those bounds. */ + min?: number + max?: number + /** Orca's own limits, only present when they differ from `min` and `max`; null means Orca sets no limit. Outside them Orca rejects the value. */ + orcaMin?: number | null + orcaMax?: number | null + step?: number + /** Orca's enum strings, in Orca's order. */ + /** The value 0 means automatic (line widths take the nozzle diameter) and is always allowed, whatever `min` says. */ + auto?: boolean + enumValues?: string[] + enumLabels?: string[] + /** Enum values the schema lists but the SlicerX engine cannot print yet. Choosing one is allowed (imported projects use them) and validation says so. */ + unavailableValues?: string[] + /** Old enum strings that read as a current value (for example athena for aegis). */ + enumAliases?: Record + label: string + help?: string + /** One or two plain sentences on what the setting does and when to change it (packages/settings/notes.json). Shown in its tooltip. */ + note?: string + /** UI group: quality, strength, speed, cooling, temperature, extrusion, support, adhesion, multimaterial, machine, gcode, and so on. */ + group: string + /** Orca's own category string, when it has one. */ + category?: string + mode: SettingMode + /** What the key is for, for grouping the Advanced and Expert tiers. Process keys only. */ + intent?: SettingIntent + /** `multicolor`: show the key only when two or more filaments are in use (see `isVisible`). */ + showWhen?: 'multicolor' + /** Shown in Easy mode (usually driven by an Easy control rather than edited directly). */ + easy?: boolean + /** Orca writes `nil` for "use the other profile's value"; such a key is left out of the config. */ + nullable?: boolean + enabledWhen?: SettingCondition[] + /** Pilot edit rule from knowledge/settings.yaml, when the key is in the catalog. */ + pilot?: PilotRule + /** One line each: what raising or lowering the value does to the print. Used for diff reasons. */ + effect?: { increase?: string; decrease?: string } + /** First slice stage this key invalidates. */ + invalidates: SliceStage +} + +/** + * A fully resolved config: every key the engine reads, with typed values. + * Percent values are numbers (15 means 15 percent). Orca's string forms are + * converted on import and restored on export. + */ +export interface PrintConfig { + layer_height: number + initial_layer_print_height: number + wall_loops: number + top_shell_layers: number + bottom_shell_layers: number + sparse_infill_density: number + sparse_infill_pattern: string + line_width: number + brim_type: string + brim_width: number + enable_support: boolean + nozzle_diameter: number[] + nozzle_temperature: number[] + printable_area: [number, number][] + printable_height: number + gcode_flavor: string + [key: string]: SettingValue +} + +/** sleipnir, the automatic variable layer height. Shown as Off, sleipnir: Quality and sleipnir: Strength. */ +export type SmartLayerMode = 'off' | 'quality' | 'strength' +export const SMART_LAYER_LABELS: Record = { off: 'Off', quality: 'sleipnir: Quality', strength: 'sleipnir: Strength' } + +/** The stored Speed names. Labels live in packages/settings/easy-map.json (`controls.speed.labels`). */ +export type SpeedPreset = 'quality' | 'balanced' | 'fast' | 'fastest' +/** Old Speed names, still read from saved projects, presets and links. Never write them. */ +export type LegacySpeedPreset = 'silent' | 'standard' | 'sport' | 'ludicrous' | 'gentle' | 'maximum' +export type SupportMode = 'off' | 'auto' | 'painted' +/** Old support name, still read: `everywhere` reads as `auto`. Never write it. */ +export type LegacySupportMode = 'everywhere' + +/** The Easy mode controls from the Prepare workspace. */ +export interface EasySettings { + /** 0 to 100; higher means thinner layers. */ + detail: number + /** 0 to 100; more walls and denser infill. */ + strength: number + speed: SpeedPreset | LegacySpeedPreset + supports: SupportMode | LegacySupportMode + brim: boolean + /** The Vary layer height switch under Detail: automatic variable layer height, bounded by Detail. Off when absent. */ + varyLayerHeight?: boolean + /** Old sleipnir mode, read when `varyLayerHeight` is absent. Never write it. */ + smartLayer?: SmartLayerMode +} + +export type EasyGoal = 'draft' | 'standard' | 'fine' | 'strong' + +/** Same table as `goals` in packages/settings/easy-map.json; a test keeps them equal. */ +export const EASY_GOALS: Record = { + draft: { detail: 0, strength: 10, speed: 'fast', supports: 'auto', brim: true, varyLayerHeight: false }, + standard: { detail: 40, strength: 20, speed: 'balanced', supports: 'auto', brim: true, varyLayerHeight: true }, + fine: { detail: 80, strength: 30, speed: 'balanced', supports: 'auto', brim: true, varyLayerHeight: true }, + strong: { detail: 40, strength: 85, speed: 'balanced', supports: 'auto', brim: true, varyLayerHeight: true }, +} + +export const EASY_DEFAULTS: EasySettings = { detail: 40, strength: 20, speed: 'balanced', supports: 'auto', brim: true, varyLayerHeight: true } + +/** A material, printer and nozzle: what a plan switches between. */ +export interface SetupRef { + /** Knowledge printer id, such as `prusa_mk4s`. */ + printer: string + nozzleDiameter: number + /** Knowledge filament id, such as `petg`. */ + filament: string + process?: string + /** Hotend flavor, when the printer offers both. Defaults to `standard`. */ + hotend?: 'standard' | 'high_flow' + /** Fitted nozzle material (`brass`, `hardened_steel`, ...). Defaults to the printer's stock nozzle. */ + nozzleMaterial?: string +} + +/** Where a planned value comes from. */ +export type ChangeOrigin = 'printer' | 'filament' | 'nozzle' | 'intent' | 'calibration' | 'profile' + +export interface SettingChange { + key: string + label: string + section: SettingSection + unit?: SettingUnit + /** The value in the base config or the old setup; null when neither has one. */ + before: SettingValue | null + after: SettingValue + reason: string + /** Source ids from knowledge/sources or Orca profile paths (`orca:...`). */ + sources: string[] + origin: ChangeOrigin + /** The key's mimir class from the settings catalog. `read` keys are shown but never written. */ + klass: PilotRule + /** `ask` when a guarded key lands outside the filament's range. */ + approval: 'none' | 'ask' + /** The intent goal that asked for it, when origin is `intent`. */ + goal?: string + priority?: 'core' | 'supporting' +} + +/** A value moved to fit a limit. */ +export interface PlanClamp { + key: string + requested: SettingValue + applied: SettingValue + by: 'bounds' | 'filament' | 'printer' + limit: number + reason: string +} + +/** A value the plan will not write. */ +export interface PlanRefusal { + key: string + requested: SettingValue + reason: string +} + +export interface PlanAdvice { + text: string + kind: 'material' | 'hardware' | 'orientation' | 'environment' | 'workflow' + sources: string[] +} + +export interface SettingsPlan { + from: SetupRef + to: SetupRef + changes: SettingChange[] + /** Keys the plan could not decide, with why. */ + unresolved: { key: string; reason: string }[] + /** Problems with the new setup: nozzle too small, hotend too cool, printer not suited to the material. */ + warnings: string[] + /** Every value moved to fit a bound, a filament range or a printer limit. */ + clamps: PlanClamp[] + /** Values past a printer limit, or on a read only key: not written. */ + refused: PlanRefusal[] + /** Hard stops, such as an abrasive material on a soft nozzle. `changes` is empty while any exist. */ + blockers: string[] + /** Questions to ask the user before applying. */ + questions: string[] + /** Notes that must be shown with the plan (food contact and similar). */ + caveats: { text: string; sources: string[] }[] + /** Hardware, orientation and workflow suggestions. Never applied automatically. */ + advice: PlanAdvice[] + /** What was given up when goals conflicted. */ + tellUser: string[] + computedMs: number +} + +export interface PlanGoal { + /** A goal id from knowledge/intents, such as `strength`. */ + id: string + /** A level of that goal (`standard`, `max`, `draft`); its default level when omitted. */ + level?: string + /** Said by the user (true, the default) or inferred from the model or material. */ + stated?: boolean +} + +export interface PlanIntent { + goals: PlanGoal[] +} + +/** A stored calibration result for one spool, printer and nozzle. */ +export interface CalibrationResult { + /** A calibration id from knowledge/workflows/calibration, such as `pressure_advance`. */ + id: string + /** Result fields by name, such as `{ value: 0.045 }` or `{ best_c: 235 }`. */ + values: Record + printer?: string + filament?: string + nozzleDiameter?: number +} + +export interface ProfileRef { + id: string + name: string + section: SettingSection + vendor?: string + /** Name of the parent profile, as in Orca's `inherits`. */ + inherits?: string +} + +export type IssueSeverity = 'error' | 'warning' | 'info' + +/** A validation problem or a conflict between keys. `fix` is a suggested edit, never applied silently. */ +export interface SettingIssue { + code: string + severity: IssueSeverity + keys: string[] + message: string + fix?: { key: string; value: SettingValue } +} + +export interface ConfigDiffEntry { + key: string + label: string + group: string + unit?: SettingUnit + before?: SettingValue + after?: SettingValue + kind: 'added' | 'removed' | 'changed' + /** First slice stage the change invalidates. */ + stage: SliceStage + /** Plain sentence for the Pilot diff card and the settings panel. */ + reason: string +} + +/** Result of importing an Orca or Bambu Studio profile with its `inherits` chain resolved. */ +export interface ProfileImport { + name: string + section: SettingSection + /** Names from the profile itself up to the root of the chain. */ + chain: string[] + config: PrintConfig + /** Keys in the profile that neither the schema nor Orca's legacy rules know. Orca would drop them too. */ + unknownKeys: string[] + /** Keys Orca drops on purpose: obsolete keys and keys only Bambu Studio and other forks define. */ + ignoredKeys: string[] + /** Keys that were `nil` in the profile and left out. */ + nilKeys: string[] + /** Keys whose value could not be read as the schema type and were skipped. */ + invalidKeys: string[] +} diff --git a/desktop/src/vendor/slicerx/contracts/slice.ts b/desktop/src/vendor/slicerx/contracts/slice.ts new file mode 100644 index 00000000..84d8f8a5 --- /dev/null +++ b/desktop/src/vendor/slicerx/contracts/slice.ts @@ -0,0 +1,398 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Slice requests and results. Mirrors sx-core's public types. +import type { PrintConfig, SettingValue } from './settings' + +export type EngineId = 'sx' | 'orca' +export type GcodeFlavor = + | 'marlin2' + | 'klipper' + | 'reprapfirmware' + | 'bambu' + | 'marlin' + | 'reprap' + | 'repetier' + | 'teacup' + | 'makerware' + | 'sailfish' + | 'mach3' + | 'machinekit' + | 'smoothie' + | 'no-extrusion' + /** Ultimaker S3, S5 and S7. */ + | 'griffin' + /** Ultimaker S6 and S8. */ + | 'cheetah' + +/** Pipeline stages, in order. Settings declare the first stage they invalidate. */ +export const SLICE_STAGES = ['layers', 'contours', 'perimeters', 'surfaces', 'infill', 'paths', 'gcode', 'preview'] as const +export type SliceStage = (typeof SLICE_STAGES)[number] + +/** A loaded model, referenced by content hash so re-slicing never copies geometry again. */ +export interface MeshHandle { + id: string + hash: string + name: string + triangles: number + /** Axis-aligned size in mm, Z up. */ + bboxMm: [number, number, number] + openEdges: number + parts: MeshPartInfo[] +} + +export interface MeshPartInfo { + name: string + /** Filament slot, 1-based as in Orca's `extruder`. */ + slot: number + color?: string + triangles: number +} + +/** The settings entries of a Bambu Studio or Orca 3MF project, in the request shape of the settings crate's project import. */ +export interface ProjectMetadata { + /** Metadata/project_settings.config, parsed. */ + projectSettings?: Record + /** Text of Metadata/model_settings.config. */ + modelSettings?: string + /** Text of Metadata/layer_config_ranges.xml. */ + layerRanges?: string +} + +/** The surface a face of a part lies on (sx-geom `faces.rs`). Plane normals point out of the part. */ +export type FaceSurface = + | { kind: 'plane'; normal: [number, number, number]; offset: number } + | { kind: 'cylinder'; origin: [number, number, number]; axis: [number, number, number]; radius: number } + | { kind: 'cone'; apex: [number, number, number]; axis: [number, number, number]; halfAngle: number } + | { kind: 'sphere'; center: [number, number, number]; radius: number } + | { kind: 'other' } + +/** Which face each triangle belongs to, and the surface of each face. */ +export interface MeshFaces { + /** One per triangle, an index into `table`. */ + ids: Uint32Array + table: FaceSurface[] + /** A key per face in `table` that history steps name the face by; absent when the engine gave none. */ + keys?: number[] +} + +/** Raw geometry for hosts that take buffers directly (tests, the benchmark, Pilot's cut skill). */ +export interface MeshPart { + name: string + slot: number + positions: Float32Array + indices: Uint32Array + /** The part's faces, when the geometry engine knows them. Code that changes the triangles leaves them out. */ + faces?: MeshFaces +} + +export interface Bed { + widthMm: number + depthMm: number + heightMm: number +} + +/** What an extra volume of an object does: cut material away, keep support out, force it in, or print the object inside it with other settings. */ +export type VolumeRole = 'negative' | 'support_blocker' | 'support_enforcer' | 'modifier' + +export interface PlateVolume { + name?: string + role: VolumeRole + mesh: MeshHandle['id'] + /** Defaults to the object's transform, so the volume keeps its place in the object. */ + transform?: number[] + /** For a modifier: Orca key overrides that apply to the object inside the volume (walls, infill, speeds, flow). */ + settings?: Record +} + +export interface PlateObject { + id: string + name: string + mesh: MeshHandle['id'] + /** 4x4 column-major transform, mm, Z up, origin at the bed's front left corner. */ + transform: number[] + /** Part name to filament slot, when the plate differs from the file. */ + slotOverrides?: Record + /** Orca key overrides for this object. Objects may differ: each slices with its own walls, infill, shells, supports and speeds (temperatures, fans and retraction follow the plate). Layer height may differ only when the plate prints by object. */ + settings?: Partial & Record + /** Negative volumes, support blockers and support enforcers. */ + volumes?: PlateVolume[] + /** Orca key overrides for single parts of the mesh, by part name: the part's own area prints with them (walls, infill, shells, line widths, speeds), as a modifier shaped like the part would. */ + partSettings?: Record> + /** Painted brim ears for `brim_type` painted: [x, y, z, headRadius] in mm, in the mesh's own space (before `transform`), z at or under the bed after the transform. */ + brimPoints?: [number, number, number, number][] +} + +export interface Plate { + bed: Bed + objects: PlateObject[] +} + +/** Setting overrides for a band of heights. Only wall count, temperature, flow, pressure advance, speeds and retraction may change by height; geometry keys are rejected. */ +export interface HeightRange { + zFromMm: number + /** Must be greater than zFromMm. */ + zToMm: number + /** Orca keys, such as `nozzle_temperature` or `pressure_advance`. */ + settings: Record + /** + * Ids of the plate objects the range applies to (`PlateObject.id`); absent for every object. Objects printed + * one after another (`print_sequence` by object) each get their own temperature, pressure advance and + * retraction. Objects printed layer by layer share the nozzle, so those keys then apply to the whole layer. + */ + objects?: string[] +} + +export type LayerGcode = ({ layer: number; zMm?: never } | { zMm: number; layer?: never }) & { kind: 'pause' | 'color_change' | 'custom'; gcode?: string } + +export interface SliceOptions { + engine?: EngineId + flavor?: GcodeFlavor + /** Web host only: number of worker shards. Output is identical for any value. */ + shards?: number + emitGcode?: boolean + emitPreview?: boolean + /** The time of this slice, seconds since 1970 UTC, for the G-code date and time variables some printers' G-code uses. The browser and desktop hosts fill it on every slice. */ + nowUnix?: number + /** The local offset from UTC in minutes (east is positive) that goes with `nowUnix`. */ + nowOffsetMinutes?: number + /** + * sleipnir: the top of every layer in mm, first entry is the first layer's top. Entries strictly + * ascend, each layer is 0.04 to 0.8 mm thick, and the last reaches the top of the plate. Replaces + * layer_height and initial_layer_print_height. + */ + layerTopsMm?: number[] + /** + * Resume a print at this layer (0-based). The plate is sliced whole and G-code is written only from + * this layer, after a start sequence that heats, homes X and Y but not Z, and draws no purge line. + * The preview still holds every layer. 0 means a normal print; past the last layer is an error. + * `@slicerx/geom` `resume` turns a measured height into this layer index and the Z it starts at. + */ + resumeFromLayer?: number + /** + * With resumeFromLayer: declare the nozzle's Z (G92 Z after homing X and Y) instead of leaving it as the + * printer has it. The result carries a manual_step warning: the nozzle must be at zMm by hand first. + * mimir asks the person before using it. + */ + resumeZ?: { mode: 'declare'; zMm: number } + /** Setting overrides by height (calibration towers, temperature and pressure advance tests). */ + heightRanges?: HeightRange[] + /** + * G-code written at the start of layers: a pause, a color change, or custom text such as a firmware setting for a + * calibration band. Each entry gives `layer` (0-based) or `zMm`: the first layer whose top reaches that height, on + * the layers the engine plans. Of several entries by height that land on one layer, the last stays. + */ + layerGcode?: LayerGcode[] + /** Limits of the target printer in C. Settings above them are lowered and reported as safety_limit warnings. */ + machineLimits?: { nozzleMaxC?: number; bedMaxC?: number; chamberMaxC?: number; ptfeLined?: boolean } + /** The custom G-code in the config is the person's own. Off by default: imported text gets the strict linter. */ + trustedGcode?: boolean + /** For the `filename_format` placeholders `{plate_name}`, `{plate_number}` (from 1) and `{model_name}` (the project's name). */ + plateName?: string + plateNumber?: number + modelName?: string + /** Image for the G-code thumbnails: raw RGBA bytes, width by height pixels. The engine scales it to the sizes the profile asks for. */ + thumbnail?: { width: number; height: number; rgba: Uint8Array } + /** The printer profile id (`bambu-h2d`): heimdall checks the plate with that printer's head, gantry and tool changer. */ + printerId?: string +} + +export interface SliceRequest { + plate: Plate + config: PrintConfig + options?: SliceOptions +} + +export interface SliceProgress { + stage: SliceStage + /** 0 to 1 within the stage. */ + fraction: number +} + +export interface SliceStats { + /** The print's time as the finished file reads it: the start before the first layer, every layer, the end. */ + timeS: number + /** Seconds of `timeS` before the first layer (heating, homing, leveling, the purge line); `layerTimeS` adds up to the rest. */ + prepareS?: number + /** Per filament slot, index 0 is slot 1. */ + filamentMm: number[] + filamentG: number[] + cost: number + toolChanges: number +} + +export type SliceWarningCode = 'open_edges' | 'thin_wall' | 'floating_region' | 'long_bridge' | 'outside_bed' | 'unsupported_setting' | 'manual_step' | 'collision' | 'safety_limit' + +export interface SliceWarning { + code: SliceWarningCode + message: string + objectId?: string + layer?: number +} + +/** Why the prime tower stands where it does. */ +export type PrimeTowerReason = + /** Where `wipe_tower_x` and `wipe_tower_y` put it. */ + | 'kept' + /** Picked by the engine (`prime_tower_auto_position`): clear of the objects and no-go zones, shortest travel, toward the back. */ + | 'auto' + /** Pulled back onto the bed by the least distance. */ + | 'moved_onto_bed' + /** Moved to the nearest spot clear of the objects and the printer's no-go zones. */ + | 'moved_clear' + /** Made wider and shallower, or turned a quarter, to fit at all. */ + | 'reshaped' + +/** The prime tower as the engine placed it: front left corner, size and rotation about that corner. mm and degrees. */ +export interface PrimeTowerPlacement { + x: number + y: number + width: number + depth: number + angle: number + reason: PrimeTowerReason +} + +/** + * Which nozzle prints each filament on a printer with two extruders fed by their own AMS (Bambu Lab H2D and H2C): + * Bambu Studio's `filament_maps`. + */ +export interface FilamentMapInfo { + /** The extruder of each filament (index slot - 1): 1 the left, 2 the right. */ + extruders: number[] + /** The nozzle of each filament: 0 the left extruder's, the right extruder's from 1 (one per H2C rack hotend). */ + nozzles: number[] + /** True when the slicer picked the map, false when the plate's settings gave it. */ + auto: boolean +} + +/** What variable layer heights (sleipnir) cost on a multi-color plate against fixed layers. */ +export interface VaryLayerCost { + /** Tool changes added (negative when fewer). */ + extraToolChanges: number + /** Filament purged on the tower and into the chute, grams added. */ + extraPurgeG: number +} + +/** What of the machine meets a printed part. */ +/** + * What of the machine meets a printed part; or `path_conflict`, the paths of two objects (or of an object and the prime + * tower, `prime-tower`) crossing on one layer; or `keep_out`, a print path in a zone the printer keeps clear + * (`exclusion-area`, `wrap-check-zone`). + */ +export type CollisionKind = 'gantry' | 'hotend' | 'nozzle_travel_through_part' | 'tool_change' | 'dock' | 'path_conflict' | 'keep_out' + +/** + * One place where the machine would meet a part already printed (heimdall, print by object). `hit` is the head's own + * shape; `close` is only inside the printer profile's clearance radius, with the head itself clearing. Codes, numbers + * and object ids: the app writes the words. + */ +export interface Collision { + kind: CollisionKind + severity: 'hit' | 'close' + /** + * The piece of the machine: the nozzle, the toolhead, the gantry beam or the frame over the bed (the profile's lid + * height); `clearance` is the profile's clearance radius, which blocks where the head is not measured (A1, A1 mini). + */ + part: 'nozzle' | 'toolhead' | 'gantry' | 'lid' | 'clearance' + /** The plate object printing, and the one it meets. */ + objectId: string + hitId: string + /** When it first happens: plate layer (0-based), the layer's extrusion segment as the preview counts them, print time. */ + layer: number + segment: number + timeS: number + lastLayer: number + /** The nozzle tip, and where the machine meets the part, at that moment, mm. */ + at: [number, number, number] + point: [number, number, number] + /** The layer and the spot where it goes deepest. */ + worstLayer: number + worstPoint: [number, number, number] + depthMm: number + /** How tall the object it meets stands, mm. */ + hitHeightMm: number + /** The clearance it breaks, mm: the rod height (gantry), the lid height (lid), the clearance radius (close call). */ + limitMm?: number + /** The extra spacing that clears a toolhead strike sideways, mm. */ + pushMm?: number + /** During a tool change: the tools (0-based) and how far along the trip, 0 to 1. */ + change?: [number, number, number] +} + +export type CollisionFixKind = 'reorder' | 'by_layer' | 'spread' | 'raise_lift' | 'move_object' | 'arrange' + +/** A way to clear some of the collisions, with the print time it adds. */ +export interface CollisionFix { + kind: CollisionFixKind + costS: number + /** Indices into the collisions it clears. */ + clears: number[] + /** Safe to apply with one click (a new order, print by layer, arrange the plate); the others are explained. */ + oneClick: boolean + /** reorder: the plate object ids in the new print order. */ + order?: string[] + /** spread: the extra space between objects; raise_lift: the Z hop, mm. */ + mm?: number + /** move_object: which object. */ + objectId?: string + /** by_layer: the most extra travel moves on one layer. */ + moves?: number + /** Reorder: the close calls the new order still has (inside the profile's radius; the head itself clears them). */ + closeCalls?: number +} + +export interface SliceResult { + id: string + engine: EngineId + layerCount: number + layerZ: Float32Array + layerTimeS: Float32Array + stats: SliceStats + /** Microseconds spent per stage, summed over shards. */ + stageMicros: Partial> + /** Wall time from request to result, ms. */ + wallMs: number + warnings: SliceWarning[] + /** `bgcode` when the profile asked for binary G-code (Prusa); absent for plain text. */ + gcodeFormat?: 'bgcode' + /** The name the profile's `filename_format` gives the G-code file; absent when the host did not return one. */ + fileName?: string + /** Where the prime tower stands; absent when the plate has none. */ + primeTower?: PrimeTowerPlacement + /** Present when the plate has two or more filaments and variable layer heights. */ + varyLayerCost?: VaryLayerCost + /** Present on a printer with two extruders fed by their own AMS: the nozzle of each filament. */ + filamentMap?: FilamentMapInfo + /** Print by object: every place the head, gantry or tool changer would meet a printed part, in print order. */ + collisions?: Collision[] + /** Fixes for the collisions. */ + collisionFixes?: CollisionFix[] +} + +export type GcodeTarget = { kind: 'blob' } | { kind: 'path'; path: string } + +export interface GcodeExport { + fileName: string + bytes: number + sha256: string + /** Present when target.kind is 'blob'. */ + blob?: Blob + path?: string +} + +export interface SlicerHost { + loadModel(data: ArrayBuffer, fileName: string): Promise + loadParts(name: string, parts: MeshPart[]): Promise + slice(req: SliceRequest, opts?: { onProgress?: (p: SliceProgress) => void; signal?: AbortSignal }): Promise + /** + * Geometry of a loaded model (3MF, STL or parts) for drawing, in the file's build space, before the + * plate transform. Optional: hosts that only slice may not have it. + */ + meshParts?(meshId: MeshHandle['id']): Promise + /** Settings entries of a 3MF project, without loading its geometry. Optional. */ + projectMetadata?(data: ArrayBuffer, fileName: string): Promise + /** SXPV bytes for a slice result; parse with readPreview(). */ + getPreview(sliceId: string): Promise + exportGcode(sliceId: string, target: GcodeTarget): Promise + release(id: string): void +} diff --git a/desktop/src/vendor/slicerx/entry.ts b/desktop/src/vendor/slicerx/entry.ts new file mode 100644 index 00000000..e818238b --- /dev/null +++ b/desktop/src/vendor/slicerx/entry.ts @@ -0,0 +1,5 @@ +// Studio entry point (not upstream). Exposes the viewport factory and types only; no editing tools are re-exported. +export { createViewport } from "./viewport/viewport"; +export type { + DisplayStyle, RenderMode, ViewPreset, Viewport, ViewportObject, ViewportOptions, ViewportPlate, +} from "./viewport/types"; diff --git a/desktop/src/vendor/slicerx/error-cause.d.ts b/desktop/src/vendor/slicerx/error-cause.d.ts new file mode 100644 index 00000000..981317fc --- /dev/null +++ b/desktop/src/vendor/slicerx/error-cause.d.ts @@ -0,0 +1,9 @@ +// Studio-authored (not upstream). The vendored viewport calls `new Error(message, { cause })`, which the ES2022 lib types +// but this project's ES2020 lib does not. This declares only that two-argument form; the lib, target, React and Vite +// are unchanged. +interface ErrorOptions { + cause?: unknown; +} +interface ErrorConstructor { + new (message?: string, options?: ErrorOptions): Error; +} diff --git a/desktop/src/vendor/slicerx/viewport/brim.ts b/desktop/src/vendor/slicerx/viewport/brim.ts new file mode 100644 index 00000000..479e1e33 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/brim.ts @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Brim ears (Orca's GLGizmoBrimEars, render_points): flat discs on the bed under a model, in the bed frame. +// An ear is drawn as a cylinder of radius r and 0.2 mm height; an ear that does not connect to the first layer +// is drawn in the alert color. A faint disc follows the cursor while the tool is on. +import { Color, CylinderGeometry, Group, Mesh, MeshBasicMaterial } from 'three' +import { SCENE, type SceneColors } from './palette' + +export interface BrimEar { + x: number + y: number + z: number + r: number + error?: boolean + /** Drawn in the selection color. */ + selected?: boolean +} + +const HEIGHT = 0.2 +const UNIT = new CylinderGeometry(1, 1, HEIGHT, 40).rotateX(Math.PI / 2) + +export class BrimEars { + /** Child of the bed frame (Z up, mm). */ + readonly group = new Group() + private ears = new Map() + private meshes: Mesh[] = [] + private readonly good = new MeshBasicMaterial({ color: new Color(SCENE.selection), transparent: true, opacity: 0.85, depthWrite: false, toneMapped: false }) + private readonly bad = new MeshBasicMaterial({ color: new Color(SCENE.overhangRed), transparent: true, opacity: 0.9, depthWrite: false, toneMapped: false }) + private readonly picked = new MeshBasicMaterial({ color: new Color(SCENE.liveLayer), transparent: true, opacity: 0.95, depthWrite: false, toneMapped: false }) + private readonly hoverMat = new MeshBasicMaterial({ color: new Color(SCENE.selection), transparent: true, opacity: 0.3, depthWrite: false, toneMapped: false }) + private readonly hover = new Mesh(UNIT, this.hoverMat) + private hoverR: number | null = null + + constructor() { + this.group.name = 'brim-ears' + this.hover.visible = false + this.hover.renderOrder = 3 + this.group.add(this.hover) + } + + /** The theme's selection and live layer colors. */ + setColors(scene: Pick): void { + this.good.color.set(scene.selection) + this.hoverMat.color.set(scene.selection) + this.bad.color.set(scene.overhangRed) + this.picked.color.set(scene.liveLayer) + } + + setEars(map: Record): void { + for (const m of this.meshes) this.group.remove(m) + this.meshes = [] + this.ears = new Map(Object.entries(map).map(([id, list]) => [id, list.map((e) => ({ ...e }))])) + for (const list of this.ears.values()) { + for (const e of list) { + const m = new Mesh(UNIT, e.selected ? this.picked : e.error ? this.bad : this.good) + m.position.set(e.x, e.y, e.z + HEIGHT / 2) + m.scale.set(e.r, e.r, 1) + m.renderOrder = 3 + this.group.add(m) + this.meshes.push(m) + } + } + } + + /** True when any ear is drawn as selected. */ + get anySelected(): boolean { + for (const list of this.ears.values()) if (list.some((e) => e.selected)) return true + return false + } + + isSelected(objectId: string, index: number): boolean { + return !!this.ears.get(objectId)?.[index]?.selected + } + + forEachEar(cb: (objectId: string, index: number, ear: BrimEar) => void): void { + for (const [id, list] of this.ears) list.forEach((e, i) => cb(id, i, e)) + } + + get count(): number { + return this.meshes.length + } + + setHoverRadius(r: number | null): void { + this.hoverR = r + if (r === null) this.hover.visible = false + else this.hover.scale.set(r, r, 1) + } + + /** The cursor's position on the bed, or null when it is off the model. */ + setHover(at: [number, number] | null): boolean { + const show = at !== null && this.hoverR !== null + const changed = show !== this.hover.visible || (show && (this.hover.position.x !== at[0] || this.hover.position.y !== at[1])) + this.hover.visible = show + if (show) this.hover.position.set(at[0], at[1], HEIGHT / 2) + return changed + } + + /** The ear under a bed point (within its radius, at least 1.5 mm), nearest first. */ + hit(x: number, y: number): { objectId: string; index: number } | null { + let best: { objectId: string; index: number; d: number } | null = null + for (const [objectId, list] of this.ears) { + list.forEach((e, index) => { + const d = Math.hypot(e.x - x, e.y - y) + if (d <= Math.max(e.r, 1.5) && (!best || d < best.d)) best = { objectId, index, d } + }) + } + return best ? { objectId: (best as { objectId: string }).objectId, index: (best as { index: number }).index } : null + } + + dispose(): void { + this.good.dispose() + this.bad.dispose() + this.picked.dispose() + this.hoverMat.dispose() + } +} diff --git a/desktop/src/vendor/slicerx/viewport/cadtools.ts b/desktop/src/vendor/slicerx/viewport/cadtools.ts new file mode 100644 index 00000000..44bff3b6 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/cadtools.ts @@ -0,0 +1,514 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// The 3D view's part of the modeling tools: the push and pull preview, the sketch layer and kept +// dimensions. Each one draws only while its tool has something to show, and keeps its buffers: +// a drag moves a matrix or rewrites a few floats in place, never builds geometry. The app does the +// geometry (the sx-geom worker) and hands over prisms, outlines and labels. +import { + BufferAttribute, + BufferGeometry, + CanvasTexture, + Color, + DoubleSide, + EdgesGeometry, + Float32BufferAttribute, + Group, + Line, + LineBasicMaterial, + LineSegments, + Matrix4, + Mesh, + MeshBasicMaterial, + Points, + PointsMaterial, + Sprite, + SpriteMaterial, +} from 'three' +import type { V3 } from './scaling' + +export type V2 = [number, number] + +/** A plane in bed coordinates (mm): origin, in-plane axes u and v, and the outward normal. */ +export interface CadFrame { + origin: V3 + u: V3 + v: V3 + normal: V3 +} + +const dot = (a: V3, b: V3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + +/** Plane coordinates of a bed point. */ +export function toPlane(f: CadFrame, p: V3): V2 { + const d: V3 = [p[0] - f.origin[0], p[1] - f.origin[1], p[2] - f.origin[2]] + return [dot(d, f.u), dot(d, f.v)] +} + +/** A plane point in bed coordinates. */ +export function fromPlane(f: CadFrame, [x, y]: V2): V3 { + return [f.origin[0] + f.u[0] * x + f.v[0] * y, f.origin[1] + f.u[1] * x + f.v[1] * y, f.origin[2] + f.u[2] * x + f.v[2] * y] +} + +/** Where a ray (bed coordinates) meets the plane, in plane coordinates; null when it runs along it or points away. */ +export function rayOnPlane(f: CadFrame, o: V3, d: V3): V2 | null { + const den = dot(d, f.normal) + if (Math.abs(den) < 1e-9) return null + const t = dot([f.origin[0] - o[0], f.origin[1] - o[1], f.origin[2] - o[2]], f.normal) / den + if (t < 0) return null + return toPlane(f, [o[0] + d[0] * t, o[1] + d[1] * t, o[2] + d[2] * t]) +} + +/** The plane's matrix: plane coordinates (x, y, 0) to bed coordinates. */ +export function frameMatrix(f: CadFrame, out = new Matrix4()): Matrix4 { + return out.set(f.u[0], f.v[0], f.normal[0], f.origin[0], f.u[1], f.v[1], f.normal[1], f.origin[1], f.u[2], f.v[2], f.normal[2], f.origin[2], 0, 0, 0, 1) +} + +/** + * A 1 mm push prism stretched to `d` mm: a scale by `d` along the normal about the face's plane. + * The walls of a push run straight along the normal, so this is exactly the prism for `d`. + */ +export function prismMatrix(point: V3, normal: V3, d: number, out = new Matrix4()): Matrix4 { + const [nx, ny, nz] = normal + const k = d - 1 + // I + k n nᵀ, about the plane through `point`. + const m00 = 1 + k * nx * nx + const m01 = k * nx * ny + const m02 = k * nx * nz + const m11 = 1 + k * ny * ny + const m12 = k * ny * nz + const m22 = 1 + k * nz * nz + const pn = dot(point, normal) + return out.set(m00, m01, m02, -k * nx * pn, m01, m11, m12, -k * ny * pn, m02, m12, m22, -k * nz * pn, 0, 0, 0, 1) +} + +const JOIN = '#50fa7b' +const CUT = '#ff5555' + +/** What a fillet or chamfer would change: the removed pieces red, the added ones green, drawn through the model. Built only when set. */ +export class EdgePreview { + readonly group = new Group() + private readonly cutFill = new MeshBasicMaterial({ color: new Color(CUT), transparent: true, opacity: 0.45, depthTest: false, depthWrite: false, side: DoubleSide, toneMapped: false }) + private readonly joinFill = new MeshBasicMaterial({ color: new Color(JOIN), transparent: true, opacity: 0.45, depthTest: false, depthWrite: false, side: DoubleSide, toneMapped: false }) + + constructor() { + this.group.name = 'edge-preview' + this.group.renderOrder = 9 + this.group.visible = false + } + + set(p: { cut: { positions: ArrayLike; indices: ArrayLike } | null; join: { positions: ArrayLike; indices: ArrayLike } | null } | null): void { + this.clear() + if (!p) return + for (const [m, mat] of [[p.cut, this.cutFill], [p.join, this.joinFill]] as const) { + if (!m || m.indices.length < 3) continue + const g = new BufferGeometry() + g.setAttribute('position', new Float32BufferAttribute(Array.from(m.positions), 3)) + g.setIndex(Array.from(m.indices)) + const mesh = new Mesh(g, mat) + mesh.renderOrder = 9 + mesh.raycast = () => {} + this.group.add(mesh) + } + this.group.visible = this.group.children.length > 0 + } + + private clear(): void { + for (const c of [...this.group.children]) { + c.removeFromParent() + ;(c as Mesh).geometry.dispose() + } + this.group.visible = false + } + + dispose(): void { + this.clear() + this.cutFill.dispose() + this.joinFill.dispose() + } +} + +/** The push and pull preview: the swept prism, green when it adds and red when it cuts, drawn through the model. */ +export class PushPreview { + readonly group = new Group() + private readonly fill = new MeshBasicMaterial({ color: new Color(JOIN), transparent: true, opacity: 0.28, depthTest: false, depthWrite: false, side: DoubleSide, toneMapped: false }) + private readonly edge = new LineBasicMaterial({ color: new Color(JOIN), transparent: true, opacity: 0.95, depthTest: false, toneMapped: false }) + private mesh: Mesh | null = null + private lines: LineSegments | null = null + private face: { point: V3; normal: V3 } | null = null + + constructor() { + this.group.name = 'push-preview' + this.group.matrixAutoUpdate = false + this.group.renderOrder = 9 + } + + /** The 1 mm prism (bed coordinates) for the picked face; null clears it. */ + setPrism(prism: { positions: ArrayLike; indices: ArrayLike } | null, face: { point: V3; normal: V3 } | null): void { + this.clear() + this.face = face + if (!prism || !face || prism.indices.length < 3) return + const g = new BufferGeometry() + g.setAttribute('position', new Float32BufferAttribute(Array.from(prism.positions), 3)) + g.setIndex(Array.from(prism.indices)) + this.mesh = new Mesh(g, this.fill) + this.mesh.renderOrder = 9 + this.mesh.raycast = () => {} + this.lines = new LineSegments(new EdgesGeometry(g, 20), this.edge) + this.lines.renderOrder = 10 + this.lines.raycast = () => {} + this.group.add(this.mesh, this.lines) + } + + /** Stretches the prism to `d` mm; 0 hides it. */ + setDistance(d: number): void { + const f = this.face + this.group.visible = !!f && !!this.mesh && Math.abs(d) > 1e-6 + if (!f) return + prismMatrix(f.point, f.normal, d, this.group.matrix) + this.group.matrixWorldNeedsUpdate = true + const c = d < 0 ? CUT : JOIN + this.fill.color.set(c) + this.edge.color.set(c) + } + + get hasPrism(): boolean { + return this.mesh !== null + } + + private clear(): void { + for (const o of [this.mesh, this.lines]) { + if (!o) continue + o.removeFromParent() + o.geometry.dispose() + } + this.mesh = null + this.lines = null + } + + dispose(): void { + this.clear() + this.fill.dispose() + this.edge.dispose() + this.group.removeFromParent() + } +} + +export type SketchTone = 'normal' | 'selected' | 'issue' | 'soft' | 'axis' | 'grid' + +/** What the sketch layer shows, all in plane coordinates (mm). */ +export interface SketchScene { + frame: CadFrame + /** Polylines: drawn segments, the picked face's outline (soft), problems (issue), a revolve axis. */ + paths: readonly { points: readonly V2[]; closed?: boolean; tone?: SketchTone }[] + /** Points a press can grab when `dragHandles` is on; drawn as dots. */ + handles: readonly V2[] + dragHandles?: boolean + /** A faint grid, every `stepMm`, over the rectangle `min` to `max`. */ + grid?: { stepMm: number; min: V2; max: V2 } + /** Problem spots, drawn as red dots. */ + marks?: readonly V2[] +} + +/** The line being drawn (a polyline from the last point to the cursor), the snapped cursor and an alignment guide. */ +export interface SketchCursor { + path?: readonly V2[] | null + at?: V2 | null + guide?: readonly [V2, V2] | null +} + +const TONE: Record = { + normal: { color: '#8be9fd', opacity: 1 }, + selected: { color: '#f1fa8c', opacity: 1 }, + issue: { color: '#ff5555', opacity: 1 }, + soft: { color: '#bd93f9', opacity: 0.55 }, + axis: { color: '#ffb86c', opacity: 1 }, + grid: { color: '#6272a4', opacity: 0.32 }, +} + +/** Room for the line being drawn: an arc preview needs the most points. */ +const CURSOR_POINTS = 256 + +/** + * The sketch on its plane. A group placed by the frame's matrix holds flat geometry, lifted a hair off + * the plane and drawn through the model so it reads from any angle. `set` rebuilds the drawn sketch + * (on a click or a point drag); `cursor` rewrites the rubber band in place. + */ +export class SketchLayer { + readonly group = new Group() + private readonly mats = new Map() + private readonly dotMat = new PointsMaterial({ color: new Color('#f8f8f2'), size: 7, sizeAttenuation: false, depthTest: false, toneMapped: false }) + private readonly markMat = new PointsMaterial({ color: new Color('#ff5555'), size: 10, sizeAttenuation: false, depthTest: false, toneMapped: false }) + private readonly snapMat = new PointsMaterial({ color: new Color('#f1fa8c'), size: 11, sizeAttenuation: false, depthTest: false, toneMapped: false }) + private drawn: (LineSegments | Points)[] = [] + private readonly band: Line + private readonly bandPos = new Float32Array(CURSOR_POINTS * 3) + private readonly snap: Points + private readonly snapPos = new Float32Array(3) + private readonly guide: Line + private readonly guidePos = new Float32Array(6) + scene: SketchScene | null = null + + constructor() { + this.group.name = 'sketch' + this.group.matrixAutoUpdate = false + this.group.visible = false + for (const [tone, t] of Object.entries(TONE) as [SketchTone, { color: string; opacity: number }][]) { + this.mats.set(tone, new LineBasicMaterial({ color: new Color(t.color), transparent: true, opacity: t.opacity, depthTest: false, toneMapped: false })) + } + const bandGeo = new BufferGeometry() + bandGeo.setAttribute('position', new BufferAttribute(this.bandPos, 3)) + bandGeo.setDrawRange(0, 0) + this.band = new Line(bandGeo, this.mats.get('selected')) + this.band.frustumCulled = false + this.band.renderOrder = 12 + const snapGeo = new BufferGeometry() + snapGeo.setAttribute('position', new BufferAttribute(this.snapPos, 3)) + snapGeo.setDrawRange(0, 0) + this.snap = new Points(snapGeo, this.snapMat) + this.snap.frustumCulled = false + this.snap.renderOrder = 13 + const guideGeo = new BufferGeometry() + guideGeo.setAttribute('position', new BufferAttribute(this.guidePos, 3)) + guideGeo.setDrawRange(0, 0) + this.guide = new Line(guideGeo, this.mats.get('axis')) + this.guide.frustumCulled = false + this.guide.renderOrder = 11 + for (const o of [this.band, this.snap, this.guide]) o.raycast = () => {} + this.group.add(this.band, this.snap, this.guide) + } + + set(scene: SketchScene | null): void { + for (const d of this.drawn) { + d.removeFromParent() + d.geometry.dispose() + } + this.drawn = [] + this.scene = scene + this.group.visible = !!scene + if (!scene) return this.cursor(null) + frameMatrix(scene.frame, this.group.matrix) + this.group.matrixWorldNeedsUpdate = true + const lift = 0.02 + const byTone = new Map() + const push = (tone: SketchTone, a: readonly number[], b: readonly number[]) => { + let list = byTone.get(tone) + if (!list) byTone.set(tone, (list = [])) + list.push(a[0] ?? 0, a[1] ?? 0, lift, b[0] ?? 0, b[1] ?? 0, lift) + } + const g = scene.grid + if (g && g.stepMm > 0) { + const n = (lo: number, hi: number) => Math.min(400, Math.floor((hi - lo) / g.stepMm)) + const x0 = Math.ceil(g.min[0] / g.stepMm) * g.stepMm + const y0 = Math.ceil(g.min[1] / g.stepMm) * g.stepMm + for (let i = 0; i <= n(x0, g.max[0]); i++) push('grid', [x0 + i * g.stepMm, g.min[1]], [x0 + i * g.stepMm, g.max[1]]) + for (let i = 0; i <= n(y0, g.max[1]); i++) push('grid', [g.min[0], y0 + i * g.stepMm], [g.max[0], y0 + i * g.stepMm]) + } + for (const p of scene.paths) { + const pts = p.points + for (let i = 0; i + 1 < pts.length; i++) push(p.tone ?? 'normal', pts[i]!, pts[i + 1]!) + if (p.closed && pts.length > 2) push(p.tone ?? 'normal', pts[pts.length - 1]!, pts[0]!) + } + // Draw order: grid, soft, normal, axis, selected, issue on top. + const order: SketchTone[] = ['grid', 'soft', 'normal', 'axis', 'selected', 'issue'] + order.forEach((tone, k) => { + const pos = byTone.get(tone) + if (!pos?.length) return + const geo = new BufferGeometry() + geo.setAttribute('position', new Float32BufferAttribute(pos, 3)) + const seg = new LineSegments(geo, this.mats.get(tone)) + seg.renderOrder = 6 + k * 0.1 + seg.raycast = () => {} + this.group.add(seg) + this.drawn.push(seg) + }) + const dots = (list: readonly V2[] | undefined, mat: PointsMaterial, order: number) => { + if (!list?.length) return + const geo = new BufferGeometry() + geo.setAttribute('position', new Float32BufferAttribute(list.flatMap((p) => [p[0], p[1], lift]), 3)) + const pts = new Points(geo, mat) + pts.renderOrder = order + pts.raycast = () => {} + this.group.add(pts) + this.drawn.push(pts) + } + dots(scene.handles, this.dotMat, 8) + dots(scene.marks, this.markMat, 9) + } + + /** The rubber band and snap marker; rewrites the fixed buffers, nothing is allocated. */ + cursor(c: SketchCursor | null): void { + const path = c?.path ?? null + const n = path ? Math.min(CURSOR_POINTS, path.length) : 0 + for (let i = 0; i < n; i++) { + const p = path![i]! + this.bandPos[3 * i] = p[0] + this.bandPos[3 * i + 1] = p[1] + this.bandPos[3 * i + 2] = 0.03 + } + const bg = this.band.geometry + bg.setDrawRange(0, n >= 2 ? n : 0) + ;(bg.getAttribute('position') as BufferAttribute).needsUpdate = true + const at = c?.at ?? null + if (at) { + this.snapPos[0] = at[0] + this.snapPos[1] = at[1] + this.snapPos[2] = 0.04 + } + this.snap.geometry.setDrawRange(0, at ? 1 : 0) + ;(this.snap.geometry.getAttribute('position') as BufferAttribute).needsUpdate = true + const gd = c?.guide ?? null + if (gd) this.guidePos.set([gd[0][0], gd[0][1], 0.025, gd[1][0], gd[1][1], 0.025]) + this.guide.geometry.setDrawRange(0, gd ? 2 : 0) + ;(this.guide.geometry.getAttribute('position') as BufferAttribute).needsUpdate = true + } + + /** The handle within `tolMm` of a plane point, nearest first, or -1. */ + handleAt(at: V2, tolMm: number): number { + const s = this.scene + if (!s?.dragHandles) return -1 + let best = -1 + let bestD = tolMm + s.handles.forEach((h, i) => { + const d = Math.hypot(h[0] - at[0], h[1] - at[1]) + if (d <= bestD) { + bestD = d + best = i + } + }) + return best + } + + /** Construction lines take the theme's selection color. */ + setAccent(hex: string): void { + this.mats.get('soft')?.color.set(hex) + } + + dispose(): void { + this.set(null) + for (const o of [this.band, this.snap, this.guide]) o.geometry.dispose() + for (const m of this.mats.values()) m.dispose() + this.dotMat.dispose() + this.markMat.dispose() + this.snapMat.dispose() + this.group.removeFromParent() + } +} + +/** A kept dimension as the view draws it: a line between two bed points and its value. */ +export interface DimensionMark { + id: string + from: V3 + to: V3 + label: string + /** Extra dots, such as a circle's center. */ + points?: readonly V3[] +} + +/** Label height on screen, CSS pixels. */ +const LABEL_PX = 20 + +/** + * Kept dimensions: leader lines through the model and a value label that always faces the camera. + * Labels are sprites with their text drawn once into a small texture, so orbiting moves no DOM and + * runs no code per frame; only a change of field of view or view height rescales them. + */ +export class DimensionLayer { + readonly group = new Group() + private readonly line = new LineBasicMaterial({ color: new Color('#f1fa8c'), depthTest: false, transparent: true, opacity: 0.95, toneMapped: false }) + private readonly dot = new PointsMaterial({ color: new Color('#f1fa8c'), size: 6, sizeAttenuation: false, depthTest: false, toneMapped: false }) + private drawn: (LineSegments | Points)[] = [] + private labels: { sprite: Sprite; aspect: number }[] = [] + private scaledFor = '' + + constructor() { + this.group.name = 'dimensions' + } + + set(marks: readonly DimensionMark[]): boolean { + const had = this.drawn.length > 0 || this.labels.length > 0 + for (const d of this.drawn) { + d.removeFromParent() + d.geometry.dispose() + } + for (const l of this.labels) { + l.sprite.removeFromParent() + l.sprite.material.map?.dispose() + l.sprite.material.dispose() + } + this.drawn = [] + this.labels = [] + this.scaledFor = '' + if (marks.length === 0) return had + const pos: number[] = [] + const dots: number[] = [] + for (const m of marks) { + pos.push(...m.from, ...m.to) + dots.push(...m.from, ...m.to) + for (const p of m.points ?? []) dots.push(...p) + } + const lg = new BufferGeometry() + lg.setAttribute('position', new Float32BufferAttribute(pos, 3)) + const ls = new LineSegments(lg, this.line) + ls.renderOrder = 14 + const dg = new BufferGeometry() + dg.setAttribute('position', new Float32BufferAttribute(dots, 3)) + const ds = new Points(dg, this.dot) + ds.renderOrder = 14 + for (const o of [ls, ds]) { + o.raycast = () => {} + this.group.add(o) + this.drawn.push(o) + } + for (const m of marks) { + const label = makeLabel(m.label) + if (!label) continue + label.sprite.position.set((m.from[0] + m.to[0]) / 2, (m.from[1] + m.to[1]) / 2, (m.from[2] + m.to[2]) / 2) + this.group.add(label.sprite) + this.labels.push(label) + } + return true + } + + /** Keeps labels LABEL_PX tall on screen. Cheap to call every frame: it works only when the lens or the view height changed. */ + fit(fovDeg: number, heightPx: number): void { + const key = `${fovDeg}:${heightPx}:${this.labels.length}` + if (key === this.scaledFor || this.labels.length === 0) return + this.scaledFor = key + // A sprite without size attenuation covers scale / (2 tan(fov / 2)) of the view height. + const h = (LABEL_PX / Math.max(1, heightPx)) * 2 * Math.tan((fovDeg * Math.PI) / 360) + for (const l of this.labels) l.sprite.scale.set(h * l.aspect, h, 1) + } + + dispose(): void { + this.set([]) + this.line.dispose() + this.dot.dispose() + this.group.removeFromParent() + } +} + +function makeLabel(text: string): { sprite: Sprite; aspect: number } | null { + if (typeof document === 'undefined') return null + const c = document.createElement('canvas') + const ctx = c.getContext('2d') + if (!ctx) return null + const px = 40 + const font = `600 ${px * 0.62}px ui-monospace, SFMono-Regular, Menlo, monospace` + ctx.font = font + const w = Math.ceil(ctx.measureText(text).width + px * 0.6) + c.width = w + c.height = px + ctx.font = font + ctx.fillStyle = 'rgba(30, 31, 41, 0.9)' + ctx.beginPath() + ctx.roundRect?.(0, 0, w, px, px * 0.22) + ctx.fill() + ctx.fillStyle = '#f1fa8c' + ctx.textBaseline = 'middle' + ctx.fillText(text, px * 0.3, px / 2 + 1) + const tex = new CanvasTexture(c) + const sprite = new Sprite(new SpriteMaterial({ map: tex, depthTest: false, sizeAttenuation: false, transparent: true, toneMapped: false })) + sprite.renderOrder = 15 + sprite.raycast = () => {} + return { sprite, aspect: w / px } +} diff --git a/desktop/src/vendor/slicerx/viewport/camera.ts b/desktop/src/vendor/slicerx/viewport/camera.ts new file mode 100644 index 00000000..5f4b9239 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/camera.ts @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Camera framing: the product-shot default, view presets, animated moves and +// near and far planes fitted to the scene so the depth buffer keeps its +// precision for stacked color parts. +import { Box3, PerspectiveCamera, Sphere, Spherical, Vector3 } from 'three' +import type { OrbitControls } from 'three/addons/controls/OrbitControls.js' +import type { ViewPreset } from './types' + +export interface CameraMove { + t0: number + dur: number + fromPos: Vector3 + fromTarget: Vector3 + toPos: Vector3 + toTarget: Vector3 +} + +// the app's Motion choice is on the root as data-motion (ui/src/motion.ts); without it, the system's +export function reducedMotion(): boolean { + const m = typeof document === 'undefined' ? undefined : document.documentElement.dataset['motion'] + if (m) return m === 'reduced' + return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches +} + +/** Distance at which the box's projected corners fill the given share of the view. */ +function fitDistance(cam: PerspectiveCamera, box: Box3, dir: Vector3, fillH: number, fillW: number): { target: Vector3; distance: number } { + const target = box.getCenter(new Vector3()) + const pts: Vector3[] = [] + for (let i = 0; i < 8; i++) pts.push(new Vector3(i & 1 ? box.max.x : box.min.x, i & 2 ? box.max.y : box.min.y, i & 4 ? box.max.z : box.min.z)) + const c = cam.clone() + c.near = 1 + c.far = 200000 + c.updateProjectionMatrix() + let d = 500 + const v = new Vector3() + for (let it = 0; it < 5; it++) { + c.position.copy(target).addScaledVector(dir, d) + c.lookAt(target) + c.updateMatrixWorld(true) + let x0 = 1e9, x1 = -1e9, y0 = 1e9, y1 = -1e9 + for (const p of pts) { + v.copy(p).project(c) + x0 = Math.min(x0, v.x); x1 = Math.max(x1, v.x); y0 = Math.min(y0, v.y); y1 = Math.max(y1, v.y) + } + d *= Math.max((y1 - y0) / 2 / fillH, (x1 - x0) / 2 / fillW) + } + return { target, distance: Math.max(d, 60) } +} + +/** Pixels of the view that overlays cover on each side (the legend, the layer strip, the playback bar). */ +export interface Insets { + left: number + right: number + top: number + bottom: number +} + +export const NO_INSETS: Insets = { left: 0, right: 0, top: 0, bottom: 0 } + +/** What is left of a w by h view once the insets are taken off. Each side keeps at least 40 percent of the view. */ +export function freeArea(w: number, h: number, insets: Insets): { insets: Insets; x: number; y: number; w: number; h: number } { + const fit = (a: number, b: number, size: number): [number, number] => { + const room = size * 0.6 + const sum = a + b + return sum > room ? [(a * room) / sum, (b * room) / sum] : [a, b] + } + const [left, right] = fit(Math.max(0, insets.left), Math.max(0, insets.right), w) + const [top, bottom] = fit(Math.max(0, insets.top), Math.max(0, insets.bottom), h) + return { insets: { left, right, top, bottom }, x: left, y: top, w: w - left - right, h: h - top - bottom } +} + +/** + * Shifts the picture so the middle of the view is the middle of the free area, and returns the free + * area as shares of the view (what the framing math fills). With no insets the camera is left alone. + */ +export function applyInsets(camera: PerspectiveCamera, w: number, h: number, insets: Insets): { fw: number; fh: number } { + const f = freeArea(w, h, insets) + const { left, right, top, bottom } = f.insets + if (left || right || top || bottom) camera.setViewOffset(w, h, -(left - right) / 2, (bottom - top) / 2, w, h) + else camera.clearViewOffset() + camera.updateProjectionMatrix() + return { fw: f.w / w, fh: f.h / h } +} + +export class CameraRig { + move: CameraMove | null = null + preset: ViewPreset | null = 'iso' + /** Share of the view width and height the overlays leave free; presets frame the model inside it. */ + free = { fw: 1, fh: 1 } + /** An overlay is on the view, so a framed model fills more of the free area. */ + get covered(): boolean { + return this.free.fw < 1 || this.free.fh < 1 + } + + constructor( + readonly camera: PerspectiveCamera, + readonly controls: OrbitControls, + ) {} + + /** Destination for a preset. `box` is the world-space bounds of what should be framed; `bedSize` the larger bed side. */ + presetPose(kind: ViewPreset, box: Box3, bedSize: number): { pos: Vector3; target: Vector3 } { + const cam = this.camera + const sphere = box.getBoundingSphere(new Sphere()) + let target: Vector3 + let dir: Vector3 + let d: number + const fov = (cam.fov * Math.PI) / 180 + const fovH = 2 * Math.atan(Math.tan(fov / 2) * cam.aspect) + // A sphere of radius r fits the free area when it fits the narrower of its two half angles. + const { fw, fh } = this.free + const half = Math.min(Math.atan(Math.tan(fov / 2) * fh), Math.atan(Math.tan(fovH / 2) * fw)) + const distFor = (r: number): number => r / Math.sin(half) + if (kind === 'bed') { + const bed = new Box3(new Vector3(-bedSize / 2, -2, -bedSize / 2), new Vector3(bedSize / 2, 2, bedSize / 2)) + target = bed.getCenter(new Vector3()) + dir = cam.position.clone().sub(this.controls.target).normalize() + d = distFor(bedSize * 0.52 * 1.08) + } else if (kind === 'fit') { + target = sphere.center.clone() + dir = cam.position.clone().sub(this.controls.target).normalize() + d = distFor(sphere.radius * 1.12) + } else if (kind === 'iso') { + // Product shot: three-quarter view from the front right, slightly high, model filling about 60 percent of the height. + dir = new Vector3(0.66, 0.42, 1).normalize() + // With overlays on the view (the Preview legend, strip and bar) the model fills more of the free area, never more than it. + const f = this.covered ? fitDistance(cam, box, dir, 0.74 * fh, 0.84 * fw) : fitDistance(cam, box, dir, 0.6, 0.72) + target = f.target + d = f.distance + } else if (kind === 'top' || kind === 'bottom') { + target = new Vector3(0, 0, 0) + dir = new Vector3(0, kind === 'top' ? 1 : -1, 0.0008).normalize() + d = distFor(bedSize * 0.74) + } else { + const side = kind === 'back' ? [0, 0.16, -1] : kind === 'left' ? [-1, 0.16, 0] : kind === 'right' ? [1, 0.16, 0] : [0, 0.16, 1] + target = new Vector3(0, Math.max(20, sphere.center.y), 0) + dir = new Vector3(side[0], side[1], side[2]).normalize() + d = distFor(bedSize * 0.62) + } + return { pos: target.clone().addScaledVector(dir, d), target } + } + + /** The pose that moves the view sideways to look at `target`, keeping the angle and the distance (so the zoom level stays). */ + centerOn(target: Vector3): { pos: Vector3; target: Vector3 } { + const delta = target.clone().sub(this.controls.target) + return { pos: this.camera.position.clone().add(delta), target: target.clone() } + } + + /** The pose `factor` times closer to the target (below 1 moves away), kept within the zoom limits. */ + zoomed(factor: number): { pos: Vector3; target: Vector3 } { + const t = this.controls.target + const off = this.camera.position.clone().sub(t) + const d = Math.min(this.controls.maxDistance, Math.max(this.controls.minDistance, off.length() / factor)) + return { pos: t.clone().add(off.setLength(d)), target: t.clone() } + } + + go(pose: { pos: Vector3; target: Vector3 }, animate: boolean, now: number): void { + if (!animate || reducedMotion()) { + this.move = null + this.camera.position.copy(pose.pos) + this.controls.target.copy(pose.target) + this.controls.update() + return + } + this.move = { t0: now, dur: 520, fromPos: this.camera.position.clone(), fromTarget: this.controls.target.clone(), toPos: pose.pos, toTarget: pose.target } + } + + /** Advances an animated move. Returns true while it is running. */ + step(now: number): boolean { + const m = this.move + if (!m) return false + const k = Math.min(1, (now - m.t0) / m.dur) + const e = k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2 + this.camera.position.lerpVectors(m.fromPos, m.toPos, e) + this.controls.target.lerpVectors(m.fromTarget, m.toTarget, e) + if (k >= 1) this.move = null + return true + } + + /** Near and far hug the scene. `sceneRadius` is the radius around the target that must stay inside the planes. */ + fitClip(sceneRadius: number): boolean { + const cam = this.camera + const d = cam.position.distanceTo(this.controls.target) + const near = Math.max(1, d - sceneRadius * 1.3, d * 0.08) + const far = d + sceneRadius * 3.5 + if (Math.abs(near - cam.near) / cam.near < 0.04 && Math.abs(far - cam.far) / cam.far < 0.04) return false + cam.near = near + cam.far = far + cam.updateProjectionMatrix() + return true + } + + /** Slides the view sideways and up by a pixel delta, at the scale of the orbit distance. `heightPx` is the canvas height. */ + panBy(dxPx: number, dyPx: number, heightPx: number): void { + const cam = this.camera + const dist = cam.position.distanceTo(this.controls.target) + const perPx = (2 * dist * Math.tan((cam.fov * Math.PI) / 360)) / Math.max(1, heightPx) + const right = new Vector3().setFromMatrixColumn(cam.matrix, 0) + const up = new Vector3().setFromMatrixColumn(cam.matrix, 1) + const d = right.multiplyScalar(-dxPx * perPx).addScaledVector(up, dyPx * perPx) + cam.position.add(d) + this.controls.target.add(d) + this.preset = null + this.move = null + } + + /** Orbits by a pixel delta around the target, respecting the polar limits. `speed` is OrbitControls.rotateSpeed. */ + orbitBy(dxPx: number, dyPx: number, heightPx: number, speed: number): void { + const t = this.controls.target + const sph = new Spherical().setFromVector3(this.camera.position.clone().sub(t)) + const k = (2 * Math.PI * speed) / Math.max(1, heightPx) + sph.theta -= dxPx * k + sph.phi = Math.min(this.controls.maxPolarAngle, Math.max(this.controls.minPolarAngle, sph.phi - dyPx * k)) + this.camera.position.copy(t).add(new Vector3().setFromSpherical(sph)) + this.camera.lookAt(t) + this.preset = null + this.move = null + } + + /** Moves the orbit center to the depth of `point` along the current view ray. The picture does not change; later orbits pivot at that depth. */ + retargetToDepthOf(point: Vector3): void { + const cam = this.camera + const fwd = cam.getWorldDirection(new Vector3()) + const d = Math.max(cam.near, point.clone().sub(cam.position).dot(fwd)) + this.controls.target.copy(cam.position).addScaledVector(fwd, d) + } +} diff --git a/desktop/src/vendor/slicerx/viewport/contour.ts b/desktop/src/vendor/slicerx/viewport/contour.ts new file mode 100644 index 00000000..b245e9e4 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/contour.ts @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Where a plane cuts a triangle mesh, as line segments. The height tool of the painter draws the cut at the bottom and top of +// its band on the model, as OrcaSlicer's height range cursor does. Pure math. + +/** + * Segments where the plane `n . p = d` crosses the triangles, as x0, y0, z0, x1, y1, z1 per segment. Triangles that lie in + * the plane or only touch it at a corner give nothing. + */ +export function planeContour(positions: ArrayLike, indices: ArrayLike, n: [number, number, number], d: number): Float32Array { + const out: number[] = [] + const tri = Math.floor(indices.length / 3) + const dist = (i: number): number => n[0] * (positions[3 * i] ?? 0) + n[1] * (positions[3 * i + 1] ?? 0) + n[2] * (positions[3 * i + 2] ?? 0) - d + const at = (i: number, j: number, di: number, dj: number): [number, number, number] => { + const t = di / (di - dj) + return [0, 1, 2].map((a) => (positions[3 * i + a] ?? 0) + t * ((positions[3 * j + a] ?? 0) - (positions[3 * i + a] ?? 0))) as [number, number, number] + } + for (let t = 0; t < tri; t++) { + const v = [indices[3 * t] ?? 0, indices[3 * t + 1] ?? 0, indices[3 * t + 2] ?? 0] + const ds = v.map(dist) + const pts: [number, number, number][] = [] + for (let e = 0; e < 3; e++) { + const a = e + const b = (e + 1) % 3 + const da = ds[a] as number + const db = ds[b] as number + if ((da < 0 && db > 0) || (da > 0 && db < 0)) pts.push(at(v[a] as number, v[b] as number, da, db)) + else if (da === 0 && db !== 0 && ds[(e + 2) % 3] !== 0 && Math.sign(db) !== Math.sign(ds[(e + 2) % 3] as number)) pts.push(at(v[a] as number, v[b] as number, da, db)) + } + if (pts.length === 2) out.push(...(pts[0] as number[]), ...(pts[1] as number[])) + } + return new Float32Array(out) +} diff --git a/desktop/src/vendor/slicerx/viewport/controls.ts b/desktop/src/vendor/slicerx/viewport/controls.ts new file mode 100644 index 00000000..d50082eb --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/controls.ts @@ -0,0 +1,249 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Camera and mouse controls as data. One map per look and feel preset; the +// viewport resolves every drag and wheel event through these functions, so a +// preset's bindings can be tested without a canvas. No three.js import here. + +/** Mirrors LookId in @slicerx/contracts so the viewport stays independent of that package. */ +import { BAMBU_GIZMO, ORCA_GIZMO, PRUSA_GIZMO, withGizmoOverrides, type GizmoBindings, type GizmoOverrides } from './gizmobindings' + +export type ControlsPresetId = 'slicerx' | 'bambu-studio' | 'prusaslicer' | 'orcaslicer' +export type ControlsContext = 'prepare' | 'preview' +export type DragAction = 'rotate' | 'pan' | 'zoom' | 'none' +export type MouseButtonName = 'left' | 'middle' | 'right' +export type OrbitCenter = 'scene' | 'selection' + +export interface Modifiers { + shift: boolean + /** Control, or Command on macOS. */ + ctrl: boolean + alt: boolean + /** The space bar, held. */ + space: boolean +} + +export interface DragBinding { + button: MouseButtonName + /** Modifiers that must be down. Any modifier not listed must be up. */ + mods?: Partial + /** Where the binding applies. Default: both. */ + context?: 'prepare' | 'preview' | 'any' + action: DragAction +} + +export interface ControlsMap { + id: ControlsPresetId + /** Full text for settings screens. */ + label: string + drags: readonly DragBinding[] + wheel: { + /** Flip the zoom direction. */ + invert: boolean + /** Zoom toward the point under the cursor instead of the orbit center. */ + zoomToCursor: boolean + } + trackpad: { + /** Two-finger scroll. */ + scroll: 'pan' | 'rotate' | 'zoom' + /** Two-finger scroll with Shift held. */ + shiftScroll: 'pan' | 'rotate' | 'zoom' + /** Pinch always zooms. */ + pinch: 'zoom' + } + /** What a rotate drag orbits around. Selection falls back to the current orbit center when nothing is selected. */ + orbitAround: OrbitCenter + /** Orbit around the point under the cursor at the start of a rotate drag (at that point's depth). Off by default. */ + freeCamera: boolean + /** + * Who takes a plain left drag that starts on a model in Prepare. + * `move-selected`: only an already selected model moves, otherwise the view rotates and a click selects. + * `move-any`: the model under the cursor is selected and moved. + * Camera bindings still win over a drag on a model when a modifier is bound to one (for example Ctrl in SlicerX). + */ + objectDrag: 'move-selected' | 'move-any' + doubleClick: { empty: 'fit' | 'none'; object: 'zoom' | 'none' } + rotateSpeed: number + zoomSpeed: number + /** Modifier keys and steps of the move, scale and paint tools (see gizmobindings.ts). */ + gizmo: GizmoBindings +} + +const NO_MODS: Modifiers = { shift: false, ctrl: false, alt: false, space: false } + +/** Left rotates, right and middle pan, wheel zooms toward the cursor. Bambu Studio, PrusaSlicer and OrcaSlicer all start here. */ +const CLASSIC: readonly DragBinding[] = [ + { button: 'left', action: 'rotate' }, + { button: 'right', action: 'pan' }, + { button: 'middle', action: 'pan' }, +] + +// Bindings follow docs/look-and-feel.md section 3 (design research). Trackpad rows +// for the three imitated apps are unverified there; keep them as settings defaults. +export const CONTROL_PRESETS: Readonly> = { + slicerx: { + id: 'slicerx', + label: 'SlicerX', + drags: [ + ...CLASSIC, + { button: 'left', mods: { space: true }, action: 'pan' }, + { button: 'left', mods: { ctrl: true }, action: 'rotate' }, + { button: 'left', mods: { shift: true }, context: 'preview', action: 'pan' }, + ], + wheel: { invert: false, zoomToCursor: true }, + trackpad: { scroll: 'pan', shiftScroll: 'rotate', pinch: 'zoom' }, + orbitAround: 'selection', + freeCamera: false, + objectDrag: 'move-selected', + doubleClick: { empty: 'fit', object: 'zoom' }, + rotateSpeed: 0.8, + zoomSpeed: 0.9, + gizmo: BAMBU_GIZMO, + }, + 'bambu-studio': { + id: 'bambu-studio', + label: 'Bambu Studio style', + drags: CLASSIC, + wheel: { invert: false, zoomToCursor: true }, + trackpad: { scroll: 'zoom', shiftScroll: 'zoom', pinch: 'zoom' }, + orbitAround: 'scene', + freeCamera: false, + objectDrag: 'move-any', + doubleClick: { empty: 'none', object: 'none' }, + rotateSpeed: 0.8, + zoomSpeed: 0.9, + gizmo: BAMBU_GIZMO, + }, + prusaslicer: { + id: 'prusaslicer', + label: 'PrusaSlicer style', + drags: [...CLASSIC, { button: 'left', mods: { ctrl: true }, action: 'rotate' }], + wheel: { invert: false, zoomToCursor: true }, + trackpad: { scroll: 'zoom', shiftScroll: 'zoom', pinch: 'zoom' }, + orbitAround: 'scene', + freeCamera: false, + objectDrag: 'move-any', + doubleClick: { empty: 'none', object: 'none' }, + rotateSpeed: 1, + zoomSpeed: 0.9, + gizmo: PRUSA_GIZMO, + }, + orcaslicer: { + id: 'orcaslicer', + label: 'OrcaSlicer style', + drags: CLASSIC, + wheel: { invert: false, zoomToCursor: true }, + trackpad: { scroll: 'zoom', shiftScroll: 'zoom', pinch: 'zoom' }, + orbitAround: 'scene', + freeCamera: false, + objectDrag: 'move-any', + doubleClick: { empty: 'none', object: 'none' }, + rotateSpeed: 0.8, + zoomSpeed: 0.9, + gizmo: ORCA_GIZMO, + }, +} + +export const CONTROL_PRESET_IDS: readonly ControlsPresetId[] = ['slicerx', 'bambu-studio', 'prusaslicer', 'orcaslicer'] + +export function controlsPreset(id: ControlsPresetId): ControlsMap { + return CONTROL_PRESETS[id] +} + +export function buttonName(button: number): MouseButtonName | null { + return button === 0 ? 'left' : button === 1 ? 'middle' : button === 2 ? 'right' : null +} + +export function modifiersOf(e: { shiftKey: boolean; ctrlKey: boolean; metaKey?: boolean; altKey: boolean }, space = false): Modifiers { + return { shift: e.shiftKey, ctrl: e.ctrlKey || !!e.metaKey, alt: e.altKey, space } +} + +/** What a mouse drag does. Exact modifier match wins; a plain binding is the fallback only when no modifier is down. */ +export function resolveDrag(map: ControlsMap, button: MouseButtonName, mods: Modifiers = NO_MODS, context: ControlsContext = 'prepare'): DragAction { + for (const b of map.drags) { + if (b.button !== button) continue + if (b.context && b.context !== 'any' && b.context !== context) continue + const want = { ...NO_MODS, ...b.mods } + if (want.shift === mods.shift && want.ctrl === mods.ctrl && want.alt === mods.alt && want.space === mods.space) return b.action + } + return 'none' +} + +/** three.js MOUSE codes: 0 rotate, 1 dolly, 2 pan; -1 does nothing. */ +export const ORBIT_CODE = { rotate: 0, zoom: 1, pan: 2, none: -1 } as const + +/** + * The code to hand OrbitControls for a button so `action` happens. OrbitControls + * swaps rotate and pan when Shift, Control or Command is down, so this swaps first. + */ +export function orbitCodeFor(action: DragAction, mods: Modifiers): number { + if (mods.shift || mods.ctrl) { + if (action === 'rotate') return ORBIT_CODE.pan + if (action === 'pan') return ORBIT_CODE.rotate + } + return ORBIT_CODE[action] +} + +export interface WheelLike { + deltaX: number + deltaY: number + deltaMode: number + ctrlKey: boolean + shiftKey: boolean +} + +/** + * Trackpad or mouse. Browsers do not say, so this reads the event: pinch arrives + * as a wheel with ctrlKey; a two-finger scroll is pixel based and either has a + * horizontal part or a small fractional vertical step; a mouse wheel steps in + * whole notches (100 pixels or lines). + */ +export function wheelKind(e: WheelLike): 'pinch' | 'scroll' | 'wheel' { + if (e.ctrlKey) return 'pinch' + if (e.deltaMode !== 0) return 'wheel' + if (e.deltaX !== 0) return 'scroll' + const a = Math.abs(e.deltaY) + if (a === 0) return 'wheel' + if (!Number.isInteger(e.deltaY) || a < 40) return 'scroll' + return 'wheel' +} + +/** Camera action for a wheel event. */ +export function resolveWheel(map: ControlsMap, e: WheelLike): 'zoom' | 'pan' | 'rotate' { + const kind = wheelKind(e) + if (kind === 'scroll') return e.shiftKey ? map.trackpad.shiftScroll : map.trackpad.scroll + return 'zoom' +} + +/** + * A user's per-button remap from Settings. Replaces what the plain (no modifier) + * drag of each listed button does; modifier bindings stay. `null` clears it. + */ +export type ButtonRemap = Partial | null>> + +/** Gizmo bindings edited in Settings, applied to a map. */ +export function withGizmo(map: ControlsMap, overrides: GizmoOverrides): ControlsMap { + return { ...map, gizmo: withGizmoOverrides(map.gizmo, overrides) } +} + +export function withRemap(map: ControlsMap, remap: ButtonRemap): ControlsMap { + const drags = map.drags.filter((b) => !(b.button in remap && !hasMods(b))) + for (const [button, action] of Object.entries(remap) as [MouseButtonName, ButtonRemap[MouseButtonName]][]) { + if (action) drags.push({ button, action }) + } + return { ...map, drags } +} + +function hasMods(b: DragBinding): boolean { + return !!b.mods && Object.values(b.mods).some(Boolean) +} + +/** + * True when a left press on a model should be handed to the model layer, given + * the map, whether that model is already selected and the resolved camera action. + * A drag that a modifier binds to a camera action never moves a model. + */ +export function dragStartsOnModel(map: ControlsMap, mods: Modifiers, action: DragAction, selected: boolean): boolean { + if (mods.shift || mods.ctrl || mods.alt || mods.space) return false + if (action !== 'rotate') return false + return map.objectDrag === 'move-any' || selected +} diff --git a/desktop/src/vendor/slicerx/viewport/cutplane.ts b/desktop/src/vendor/slicerx/viewport/cutplane.ts new file mode 100644 index 00000000..339cf6c3 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/cutplane.ts @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// The cut tool in the 3D view, after OrcaSlicer's GLGizmoCut3D (v2.4.2): a plane through the model +// with a grabber on a stem along the plane normal (drag it, or the plane, to move the plane along +// its normal) and two rings to tilt it. The preview clips the model at the plane: the side the cut +// keeps draws as it is, a side it drops draws faint, and keeping both tints the upper piece. Clipping planes are uniforms, so moving the +// plane rewrites no geometry and compiles no shader; only attaching to a model does, once. +import { Color, CylinderGeometry, DoubleSide, Group, Mesh, MeshBasicMaterial, PlaneGeometry, Plane, Quaternion, SphereGeometry, Vector3, type Material, type Matrix4 } from 'three' +import type { ObjectEntry } from './model' +import { planeBasis, unit } from './rings' +import type { V3 } from './scaling' + +export type CutKeep = 'both' | 'above' | 'below' + +const dot = (a: V3, b: V3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + +/** Smallest and largest signed distance of a box's corners from the plane through `point` along unit `normal`. */ +export function extentAlong(min: V3, max: V3, m: ArrayLike, point: V3, normal: V3): [number, number] { + let lo = Infinity + let hi = -Infinity + for (let i = 0; i < 8; i++) { + const x = i & 1 ? max[0] : min[0] + const y = i & 2 ? max[1] : min[1] + const z = i & 4 ? max[2] : min[2] + const w: V3 = [(m[0] ?? 0) * x + (m[4] ?? 0) * y + (m[8] ?? 0) * z + (m[12] ?? 0), (m[1] ?? 0) * x + (m[5] ?? 0) * y + (m[9] ?? 0) * z + (m[13] ?? 0), (m[2] ?? 0) * x + (m[6] ?? 0) * y + (m[10] ?? 0) * z + (m[14] ?? 0)] + const d = dot([w[0] - point[0], w[1] - point[1], w[2] - point[2]], normal) + lo = Math.min(lo, d) + hi = Math.max(hi, d) + } + return [lo, hi] +} + +/** The plane moved `t` mm along its normal, kept within the model's extent so it always crosses it. */ +export function movePlane(point: V3, normal: V3, t: number, extent: [number, number]): V3 { + const c = Math.max(extent[0], Math.min(extent[1], t)) + return [point[0] + normal[0] * c, point[1] + normal[1] * c, point[2] + normal[2] * c] +} + +const PLANE_COLOR = '#8be9fd' +const HOT = '#ffe066' + +/** Plane, stem and grabber. The tilt rings are a RingSet the viewport owns. */ +export class CutGizmo { + readonly group = new Group() + readonly quad: Mesh + readonly grabber: Mesh + private readonly stem: Mesh + private hot: 'plane' | 'grabber' | null = null + + constructor() { + this.group.name = 'cut-gizmo' + this.group.visible = false + this.quad = new Mesh(new PlaneGeometry(2, 2), new MeshBasicMaterial({ color: new Color(PLANE_COLOR), side: DoubleSide, transparent: true, opacity: 0.18, depthWrite: false, toneMapped: false })) + this.quad.renderOrder = 8 + this.stem = new Mesh(new CylinderGeometry(1, 1, 1, 6), new MeshBasicMaterial({ color: new Color(PLANE_COLOR), depthTest: false, transparent: true, opacity: 0.8, toneMapped: false })) + this.stem.renderOrder = 10 + this.stem.raycast = () => {} + this.grabber = new Mesh(new SphereGeometry(1, 16, 12), new MeshBasicMaterial({ color: new Color(PLANE_COLOR), depthTest: false, transparent: true, opacity: 0.95, toneMapped: false })) + this.grabber.renderOrder = 11 + this.group.add(this.quad, this.stem, this.grabber) + } + + /** Places everything for a plane through `point` along `normal`, `radius` mm wide; `px` is one screen pixel in mm at the plane. */ + place(point: V3, normal: V3, radius: number, px: number): void { + const n = new Vector3(...normal) + const q = new Quaternion().setFromUnitVectors(new Vector3(0, 0, 1), n) + this.quad.position.set(...point) + this.quad.quaternion.copy(q) + this.quad.scale.setScalar(radius) + const tip = new Vector3(...point).addScaledVector(n, radius * 0.6) + this.grabber.position.copy(tip) + this.grabber.scale.setScalar(px * 7) + this.stem.position.set(...point).addScaledVector(n, radius * 0.3) + this.stem.quaternion.setFromUnitVectors(new Vector3(0, 1, 0), n) + this.stem.scale.set(px * 1.2, radius * 0.6, px * 1.2) + const color = (m: Mesh, on: boolean): void => void (m.material as MeshBasicMaterial).color.set(on ? HOT : PLANE_COLOR) + color(this.grabber, this.hot === 'grabber') + color(this.stem, this.hot === 'grabber') + color(this.quad, this.hot === 'plane') + } + + setHot(part: 'plane' | 'grabber' | null): boolean { + if (part === this.hot) return false + this.hot = part + return true + } + + dispose(): void { + for (const m of [this.quad, this.stem, this.grabber]) { + m.geometry.dispose() + ;(m.material as MeshBasicMaterial).dispose() + } + this.group.removeFromParent() + } +} + +/** + * A copy of a model material that draws the same: `clone` drops the shader hooks the layer look adds + * (materials.ts), and a shader material keeps the page-wide uniform objects instead of copies. + */ +function lookAlike(base: Material): Material { + const m = base.clone() + m.onBeforeCompile = base.onBeforeCompile + m.customProgramCacheKey = base.customProgramCacheKey + if ('uniforms' in base && 'uniforms' in m) (m as { uniforms: unknown }).uniforms = (base as { uniforms: unknown }).uniforms + return m +} + +/** + * The clipped look of the model being cut. Each part gets its own copy of its material clipped to + * the side below the plane, and a second mesh on the same geometry clipped to the side above. The + * planes are in three.js world space and are moved in place. + */ +export class CutPreview { + private readonly below = new Plane() + private readonly above = new Plane() + private attached: { entry: ObjectEntry; saved: Material[]; mats: Material[]; uppers: Mesh[] } | null = null + + get entry(): ObjectEntry | null { + return this.attached?.entry ?? null + } + + attach(entry: ObjectEntry, keep: CutKeep): void { + this.detach() + const saved: Material[] = [] + const mats: Material[] = [] + const uppers: Mesh[] = [] + for (const p of entry.parts) { + const base = p.mesh.material as Material + saved.push(base) + const lower = lookAlike(base) + const upper = lookAlike(base) + for (const [m, plane, kept] of [[lower, this.below, keep !== 'above'], [upper, this.above, keep !== 'below']] as const) { + m.clippingPlanes = [plane] + m.side = DoubleSide + if (!kept) { + m.transparent = true + m.opacity = 0.18 + m.depthWrite = false + } + } + // Keeping both, the upper piece takes a tint of the plane's color so the two pieces read apart. + const tint = (upper as Material & { color?: Color }).color + if (keep === 'both' && tint instanceof Color) tint.lerp(new Color(PLANE_COLOR), 0.35) + p.mesh.material = lower + const u = new Mesh(p.mesh.geometry, upper) + u.raycast = () => {} + u.renderOrder = p.mesh.renderOrder + p.mesh.add(u) + mats.push(lower, upper) + uppers.push(u) + } + this.attached = { entry, saved, mats, uppers } + } + + /** The cut plane in bed coordinates, turned into the two world space clipping planes. */ + setPlane(point: V3, normal: V3, bedToWorld: Matrix4): void { + const n = new Vector3(...unit(normal)) + const p = new Vector3(...point) + // three.js keeps what lies on the positive side of a clipping plane. + this.above.setFromNormalAndCoplanarPoint(n, p).applyMatrix4(bedToWorld) + this.below.setFromNormalAndCoplanarPoint(n.negate(), p).applyMatrix4(bedToWorld) + } + + detach(): void { + const a = this.attached + if (!a) return + this.attached = null + a.entry.parts.forEach((p, i) => { + const s = a.saved[i] + if (s) p.mesh.material = s + }) + for (const u of a.uppers) u.removeFromParent() + for (const m of a.mats) m.dispose() + } +} + +/** The plane's two tilt axes: square to the normal and to each other. */ +export function tiltAxes(normal: V3): { u: V3; v: V3 } { + const [u, v] = planeBasis(normal) + return { u, v } +} diff --git a/desktop/src/vendor/slicerx/viewport/faces.ts b/desktop/src/vendor/slicerx/viewport/faces.ts new file mode 100644 index 00000000..7648f2e9 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/faces.ts @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Flat face patches for the lay-on-face tool: the coplanar triangles around a +// picked triangle, their normal and area, and the rotation that puts a face on +// the bed. Pure math, no three.js, so it runs anywhere and is unit tested. + +export interface FacePatch { + /** Triangle indexes (into the index buffer, three vertices each), seed first. */ + triangles: number[] + /** Unit normal in the mesh's own frame, outward. */ + normal: [number, number, number] + areaMm2: number +} + +const adjacencyCache = new WeakMap() + +/** + * Triangle neighbors for a mesh whose vertices may be duplicated (STL style): positions are welded at + * 1 micrometer first, so triangles that share an edge in space are neighbors. Cached per index buffer. + */ +export function adjacencyOf(positions: ArrayLike, indices: ArrayLike): Int32Array { + let adj = adjacencyCache.get(indices as object) + if (adj) return adj + const ids = new Map() + const welded = new Uint32Array(indices.length) + for (let i = 0; i < indices.length; i++) { + const v = 3 * (indices[i] ?? 0) + const key = `${Math.round((positions[v] ?? 0) * 1000)},${Math.round((positions[v + 1] ?? 0) * 1000)},${Math.round((positions[v + 2] ?? 0) * 1000)}` + let id = ids.get(key) + if (id === undefined) { + id = ids.size + ids.set(key, id) + } + welded[i] = id + } + adj = triangleAdjacency(welded) + adjacencyCache.set(indices as object, adj) + return adj +} + +/** For each triangle, its three edge neighbors (-1 for none). Non-manifold edges keep the first pair. */ +export function triangleAdjacency(indices: ArrayLike): Int32Array { + const n = Math.floor(indices.length / 3) + const out = new Int32Array(n * 3).fill(-1) + const N = 2 ** 26 + const seen = new Map() + for (let t = 0; t < n; t++) { + for (let e = 0; e < 3; e++) { + const a = indices[3 * t + e] ?? 0 + const b = indices[3 * t + ((e + 1) % 3)] ?? 0 + const key = Math.min(a, b) * N + Math.max(a, b) + const other = seen.get(key) + if (other === undefined) seen.set(key, t * 3 + e) + else { + const ot = Math.floor(other / 3) + if (out[other] === -1 && out[3 * t + e] === -1) { + out[other] = t + out[3 * t + e] = ot + } + } + } + } + return out +} + +function triNormal(p: ArrayLike, i: ArrayLike, t: number): [number, number, number, number] { + const a = 3 * (i[3 * t] ?? 0), b = 3 * (i[3 * t + 1] ?? 0), c = 3 * (i[3 * t + 2] ?? 0) + const ux = (p[b] ?? 0) - (p[a] ?? 0), uy = (p[b + 1] ?? 0) - (p[a + 1] ?? 0), uz = (p[b + 2] ?? 0) - (p[a + 2] ?? 0) + const vx = (p[c] ?? 0) - (p[a] ?? 0), vy = (p[c + 1] ?? 0) - (p[a + 1] ?? 0), vz = (p[c + 2] ?? 0) - (p[a + 2] ?? 0) + const nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx + const len = Math.hypot(nx, ny, nz) + return len > 0 ? [nx / len, ny / len, nz / len, len / 2] : [0, 0, 0, 0] +} + +/** + * The connected triangles around `seed` whose normals stay within `flatDeg` of + * the seed's normal. Comparing to the seed, not the neighbor, keeps a gentle + * curve from leaking into one big patch. `maxTriangles` bounds the work. + */ +export function facePatch(positions: ArrayLike, indices: ArrayLike, seed: number, flatDeg = 1, maxTriangles = 200000): FacePatch | null { + const n = Math.floor(indices.length / 3) + if (seed < 0 || seed >= n) return null + const s = triNormal(positions, indices, seed) + if (s[3] === 0) return null + const adj = adjacencyOf(positions, indices) + const cos = Math.cos((flatDeg * Math.PI) / 180) + const seen = new Set([seed]) + const queue = [seed] + const tris: number[] = [] + let ax = 0, ay = 0, az = 0, area = 0 + while (queue.length && tris.length < maxTriangles) { + const t = queue.pop() as number + const q = triNormal(positions, indices, t) + if (q[0] * s[0] + q[1] * s[1] + q[2] * s[2] < cos) continue + tris.push(t) + ax += q[0] * q[3]; ay += q[1] * q[3]; az += q[2] * q[3] + area += q[3] + for (let e = 0; e < 3; e++) { + const o = adj[3 * t + e] ?? -1 + if (o >= 0 && !seen.has(o)) { + seen.add(o) + queue.push(o) + } + } + } + const l = Math.hypot(ax, ay, az) || 1 + return { triangles: tris, normal: [ax / l, ay / l, az / l], areaMm2: area } +} + +/** Unit vector for a direction, or null when it is zero length. */ +function unit(v: [number, number, number]): [number, number, number] | null { + const l = Math.hypot(v[0], v[1], v[2]) + return l > 0 ? [v[0] / l, v[1] / l, v[2] / l] : null +} + +/** Column-major 4x4 rotation about `center` that takes `from` to `to` by the shortest turn. */ +export function rotationBetween(from: [number, number, number], to: [number, number, number], center: [number, number, number] = [0, 0, 0]): number[] { + const a = unit(from) + const b = unit(to) + const I = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] + if (!a || !b) return I + const dot = Math.max(-1, Math.min(1, a[0] * b[0] + a[1] * b[1] + a[2] * b[2])) + let ax: [number, number, number] = [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] + if (dot > 1 - 1e-9) return I + if (dot < -1 + 1e-9) { + // Opposite: turn half a circle about any axis perpendicular to `from`. + ax = Math.abs(a[0]) < 0.9 ? [0, a[2], -a[1]] : [-a[2], 0, a[0]] + } + const k = unit(ax) as [number, number, number] + const c = dot + const s = Math.sqrt(Math.max(0, 1 - dot * dot)) + const t = 1 - c + const [x, y, z] = k + const r = [ + t * x * x + c, t * x * y + s * z, t * x * z - s * y, + t * x * y - s * z, t * y * y + c, t * y * z + s * x, + t * x * z + s * y, t * y * z - s * x, t * z * z + c, + ] as const + const [cx, cy, cz] = center + // Column-major: columns are r[0..2], r[3..5], r[6..8]; translation keeps `center` fixed. + return [ + r[0], r[1], r[2], 0, + r[3], r[4], r[5], 0, + r[6], r[7], r[8], 0, + cx - (r[0] * cx + r[3] * cy + r[6] * cz), cy - (r[1] * cx + r[4] * cy + r[7] * cz), cz - (r[2] * cx + r[5] * cy + r[8] * cz), 1, + ] +} + +function mul(a: number[], b: number[]): number[] { + const o = new Array(16).fill(0) + for (let c = 0; c < 4; c++) for (let r = 0; r < 4; r++) for (let k = 0; k < 4; k++) o[c * 4 + r] = (o[c * 4 + r] ?? 0) + (a[k * 4 + r] ?? 0) * (b[c * 4 + k] ?? 0) + return o +} + +/** + * New object transform (column-major, bed frame, Z up) that lays a face on the + * bed: rotates about `centerBed` so the outward `normalBed` points straight + * down (-Z). The height is not touched; drop the object onto the bed after. + */ +export function layOnFaceTransform(transform: number[], normalBed: [number, number, number], centerBed: [number, number, number]): number[] { + return mul(rotationBetween(normalBed, [0, 0, -1], centerBed), transform) +} diff --git a/desktop/src/vendor/slicerx/viewport/firstframe.ts b/desktop/src/vendor/slicerx/viewport/firstframe.ts new file mode 100644 index 00000000..e1eab56a --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/firstframe.ts @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Work that is not needed for the first picture (shader warm-up for views not yet open) waits here until the +// plate has been drawn once, so a slow shader compiler cannot hold the first frame back. + +export class FirstFrameGate { + private queue: (() => void)[] | null = [] + private t0 = performance.now() + /** Milliseconds from construction to the first drawn frame, or null before it. */ + ms: number | null = null + + /** Runs `fn` after the first frame; at once if that frame is already out. */ + after(fn: () => void): void { + if (this.queue) this.queue.push(fn) + else fn() + } + + /** Called after every frame; the first call releases the queue. */ + frame(): void { + if (!this.queue) return + const q = this.queue + this.queue = null + this.ms = performance.now() - this.t0 + for (const fn of q) fn() + } +} diff --git a/desktop/src/vendor/slicerx/viewport/gantry.ts b/desktop/src/vendor/slicerx/viewport/gantry.ts new file mode 100644 index 00000000..56dddaaa --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/gantry.ts @@ -0,0 +1,151 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// The gantry heimdall checks: in bed coordinates a beam along x across the whole bed, at the nozzle's y and the +// profile's rod height above the tip (`extruder_clearance_height_to_rod`), as deep as the rod's distance either side +// (`extruder_clearance_dist_to_rod`). Drawn translucent with the moving head; where it runs through a part the +// engine reported a gantry strike on, that stretch is drawn in the strike color. On a bed slinger (A1, A1 mini, the +// i3 family) two uprights stand at the beam's ends, so the frame reads as one that moves with the head in bed +// coordinates. +import { BoxGeometry, Color, EdgesGeometry, Group, LineBasicMaterial, LineSegments, Mesh, MeshStandardMaterial } from 'three' + +export interface GantrySpec { + /** The beam's underside above the nozzle tip, mm. */ + rod: number + /** How far the beam reaches either side of the nozzle in y, mm. */ + reach: number + /** The bed it spans, mm. */ + width: number + /** The bed moves in y and the frame's uprights carry the beam: drawn beside the bed at the beam's ends. */ + slinger: boolean +} + +/** A gantry strike: the layers it happens on (0-based, both ends included) and the box of the part it runs through. */ +export interface GantryHit { + layers: [number, number] + /** `[x0, y0, x1, y1]`, mm, and the part's top. */ + box: [number, number, number, number] + top: number +} + +/** How tall the beam is drawn, mm; the check needs only its underside. */ +const BEAM = 14 +/** How far past the band's edge a strike the engine counted may sit, mm (two of its 1 mm cells). */ +const EDGE = 2 +/** The uprights: their width, and how far beside the bed they stand, mm. */ +const POST = 14 +const SIDE = 22 + +export class GantryRig { + readonly root = new Group() + private readonly unit = new BoxGeometry(1, 1, 1) + private readonly edges = new EdgesGeometry(this.unit) + /** Brushed aluminum, the beam and the uprights alike: solid faces the part still shows through. */ + private readonly frameMat = new MeshStandardMaterial({ color: new Color('#a9afc2'), metalness: 0.55, roughness: 0.35, transparent: true, opacity: 0.5, depthWrite: false }) + private readonly edgeMat = new LineBasicMaterial({ color: new Color('#e4e8f4'), transparent: true, opacity: 0.85 }) + private readonly hitMat = new MeshStandardMaterial({ color: new Color('#ff4b5c'), emissive: new Color('#ff4b5c'), emissiveIntensity: 0.35, roughness: 0.5, transparent: true, opacity: 0.8, depthWrite: false }) + private readonly hitEdgeMat = new LineBasicMaterial({ color: new Color('#ff4b5c') }) + private readonly beam = this.solid(this.frameMat, this.edgeMat) + private readonly posts = [this.solid(this.frameMat, this.edgeMat), this.solid(this.frameMat, this.edgeMat)] + private readonly hot: Mesh[] = [] + private spec: GantrySpec | null = null + private hits: readonly GantryHit[] = [] + + constructor() { + this.root.name = 'gantry' + this.root.renderOrder = 9 + this.beam.name = 'beam' + this.posts.forEach((p, i) => (p.name = `upright ${i}`)) + this.root.add(this.beam, ...this.posts) + this.root.visible = false + } + + setSpec(spec: GantrySpec | null): void { + this.spec = spec && spec.rod > 0 && spec.width > 0 ? spec : null + if (!this.spec) this.root.visible = false + } + + setHits(hits: readonly GantryHit[] | null): void { + this.hits = hits ?? [] + } + + /** The strike color, the theme's overhang red. */ + setColor(hit: string): void { + this.hitMat.color.set(hit) + this.hitMat.emissive.set(hit) + this.hitEdgeMat.color.set(hit) + } + + /** True when a gantry strike happens on `layer`: the beam then shows even with the head hidden. */ + striking(layer: number): boolean { + return this.hits.some((h) => layer >= h.layers[0] && layer <= h.layers[1]) + } + + /** Shows the beam over the nozzle at `y`, `z` on `layer`, or hides it. Returns the stretches drawn as hits. */ + place(show: boolean, y: number, z: number, layer: number): number { + const s = this.spec + this.root.visible = show && !!s + if (!s || !show) return 0 + const z0 = z + s.rod + const [y0, y1] = [y - s.reach, y + s.reach] + const x0 = s.slinger ? -SIDE : 0 + const x1 = s.slinger ? s.width + SIDE : s.width + box(this.beam, x0, x1, y0, y1, z0, z0 + BEAM) + for (const [i, p] of this.posts.entries()) { + p.visible = s.slinger + const x = i === 0 ? x0 - POST : x1 + box(p, x, x + POST, y - POST / 2, y + POST / 2, 0, z0 + BEAM) + } + let n = 0 + for (const h of this.hits) { + if (layer < h.layers[0] || layer > h.layers[1] || h.top <= z0) continue + let ya = Math.max(y0, h.box[1]) + let yb = Math.min(y1, h.box[3]) + if (yb <= ya) { + // The engine works in whole cells, so a strike can sit at the band's edge by under a cell or two: the red + // stretch then marks that edge. + if (ya - yb > EDGE) continue + const e = h.box[1] > y1 ? y1 : y0 + ya = e - 1 + yb = e + 1 + } + const m = this.hot[n] ?? this.addHot() + m.visible = true + // A hair larger than the beam, so the red stretch shows over it. + box(m, h.box[0], h.box[2], ya - 0.5, yb + 0.5, z0 - 0.5, Math.min(z0 + BEAM, h.top) + 0.5) + n++ + } + for (let i = n; i < this.hot.length; i++) this.hot[i]!.visible = false + return n + } + + /** A box with crisp edges, scaled to size by `box`. */ + private solid(face: MeshStandardMaterial, edge: LineBasicMaterial): Mesh { + const m = new Mesh(this.unit, face) + const e = new LineSegments(this.edges, edge) + e.name = 'edges' + m.add(e) + return m + } + + private addHot(): Mesh { + const m = this.solid(this.hitMat, this.hitEdgeMat) + m.name = `hit ${this.hot.length}` + this.hot.push(m) + this.root.add(m) + return m + } + + dispose(): void { + this.unit.dispose() + this.edges.dispose() + this.frameMat.dispose() + this.edgeMat.dispose() + this.hitMat.dispose() + this.hitEdgeMat.dispose() + } +} + +function box(m: Mesh, x0: number, x1: number, y0: number, y1: number, z0: number, z1: number): void { + m.scale.set(Math.max(1e-3, x1 - x0), Math.max(1e-3, y1 - y0), Math.max(1e-3, z1 - z0)) + m.position.set((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2) +} diff --git a/desktop/src/vendor/slicerx/viewport/gaps.ts b/desktop/src/vendor/slicerx/viewport/gaps.ts new file mode 100644 index 00000000..eef431a8 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/gaps.ts @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Fit check gaps: a line between the closest points of two parts that sit closer than the printer +// can keep apart, drawn through the model so it reads from any angle. Amber for a tight gap, red +// for parts that touch or overlap. A line measured on one object follows it as it moves; a line between two +// objects shows only while both stay where they were measured. +import { BufferGeometry, Color, Float32BufferAttribute, Group, LineBasicMaterial, LineSegments, Matrix4, Mesh, MeshBasicMaterial, SphereGeometry } from 'three' +import { SCENE } from './palette' + +export interface GapLine { + from: [number, number, number] + to: [number, number, number] + kind: 'horizontal' | 'vertical' | 'fused' | 'apart' + /** The objects it was measured on, with their transforms then. None: it stays put. */ + on?: readonly { id: string; transform: readonly number[] }[] +} + +interface Drawn { + group: Group + /** Measured transform, inverted, per object. */ + on: { id: string; inv: Matrix4; at: Matrix4 }[] +} + +const DOT = new SphereGeometry(0.6, 10, 8) + +export class GapLines { + /** Child of the objects root (bed frame, Z up, mm). */ + readonly group = new Group() + private readonly amber = new LineBasicMaterial({ color: new Color(SCENE.overhangAmber), depthTest: false, transparent: true, opacity: 0.95, toneMapped: false }) + private readonly red = new LineBasicMaterial({ color: new Color(SCENE.overhangRed), depthTest: false, transparent: true, opacity: 0.95, toneMapped: false }) + private readonly amberDot = new MeshBasicMaterial({ color: new Color(SCENE.overhangAmber), depthTest: false, toneMapped: false }) + private readonly redDot = new MeshBasicMaterial({ color: new Color(SCENE.overhangRed), depthTest: false, toneMapped: false }) + private drawn: Drawn[] = [] + + constructor() { + this.group.name = 'fit-gaps' + this.group.renderOrder = 4 + } + + set(lines: readonly GapLine[]): void { + for (const d of this.drawn) { + this.group.remove(d.group) + for (const c of d.group.children) if (c instanceof LineSegments) c.geometry.dispose() + } + this.drawn = [] + for (const l of lines) { + const fused = l.kind === 'fused' + const g = new Group() + g.matrixAutoUpdate = false + const geo = new BufferGeometry() + geo.setAttribute('position', new Float32BufferAttribute([...l.from, ...l.to], 3)) + const seg = new LineSegments(geo, fused ? this.red : this.amber) + seg.renderOrder = 4 + g.add(seg) + for (const p of [l.from, l.to]) { + const dot = new Mesh(DOT, fused ? this.redDot : this.amberDot) + dot.position.set(p[0], p[1], p[2]) + dot.renderOrder = 4 + g.add(dot) + } + this.group.add(g) + const on = (l.on ?? []).map((o) => { + const at = new Matrix4().fromArray(o.transform as number[]) + return { id: o.id, at, inv: at.clone().invert() } + }) + this.drawn.push({ group: g, on }) + } + } + + /** + * Puts each line where its object is now: one object carries its lines along (the object's matrix now, times + * the inverse of the one it was measured at); a line between two objects hides once either has moved. + */ + follow(matrixOf: (id: string) => Matrix4 | undefined): void { + for (const d of this.drawn) { + if (d.on.length === 1) { + const o = d.on[0]! + const now = matrixOf(o.id) + if (now) d.group.matrix.multiplyMatrices(now, o.inv) + d.group.visible = now !== undefined + } else if (d.on.length > 1) { + d.group.visible = d.on.every((o) => { + const now = matrixOf(o.id) + return now !== undefined && now.equals(o.at) + }) + } + d.group.matrixWorldNeedsUpdate = true + } + } + + setColors(amber: string, red: string): void { + this.amber.color.set(amber) + this.amberDot.color.set(amber) + this.red.color.set(red) + this.redDot.color.set(red) + } +} diff --git a/desktop/src/vendor/slicerx/viewport/gizmo.ts b/desktop/src/vendor/slicerx/viewport/gizmo.ts new file mode 100644 index 00000000..00d6dc42 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/gizmo.ts @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Scale gizmo handles, laid out as in OrcaSlicer's GLGizmoScale3D (Orca v2.4.2): an x and a y handle on +// each side at the middle of the bottom edges, one z handle at the top, four uniform handles at the +// bottom corners of the selected model's box (in the model's own axes). They keep a constant size on +// screen and draw over the model. +import { BoxGeometry, Box3, Color, Group, Mesh, MeshBasicMaterial, Raycaster, Vector3, type Camera, type Object3D } from 'three' +import { handleAxis, handleIds, handleLocal, oppositeHandle, type HandleId, type ScaleLayout, type V3 } from './scaling' + +// Orca colors: the axis colors, cyan for uniform handles, gray for the handle that Ctrl pins. +const AXIS: Record<'x' | 'y' | 'z' | 'uniform', string> = { x: '#ff6b6b', y: '#51cf66', z: '#4dabf7', uniform: '#00ffff' } +const CONSTRAINED = '#808080' +const HOT = '#ffe066' +const SIZE_PX = 9 +const ALL_IDS = handleIds('faces') + +export class ScaleGizmo { + readonly group = new Group() + private readonly handles = new Map() + private readonly lines = new Map() + private hover: HandleId | null = null + private dragging: HandleId | null = null + + constructor() { + this.group.name = 'scale-gizmo' + this.group.visible = false + for (const id of ALL_IDS) { + const axis = handleAxis(id) + const h = new Mesh(new BoxGeometry(1, 1, 1), new MeshBasicMaterial({ color: new Color(AXIS[axis]), depthTest: false, transparent: true, opacity: 0.95, toneMapped: false })) + h.renderOrder = 10 + h.userData.handle = id + this.handles.set(id, h) + this.group.add(h) + if (axis !== 'uniform') { + const l = new Mesh(new BoxGeometry(1, 1, 1), new MeshBasicMaterial({ color: new Color(AXIS[axis]), depthTest: false, transparent: true, opacity: 0.6, toneMapped: false })) + l.renderOrder = 9 + l.raycast = () => {} + this.lines.set(id, l) + this.group.add(l) + } + } + } + + private layout: ScaleLayout = 'bottom' + private rootPivot: 'bottom-center' | 'center' = 'bottom-center' + + /** World position of each handle of the current layout for a model whose local box is `box`. */ + positions(obj: Object3D, box: Box3): Partial> { + const min = box.min.toArray() as V3 + const max = box.max.toArray() as V3 + const out: Partial> = {} + for (const id of handleIds(this.layout)) out[id] = obj.localToWorld(new Vector3(...handleLocal(id, min, max, this.layout))) + return out + } + + /** Places the handles for this model and camera, or hides the gizmo with null. `ctrl` shows the pinned handle in gray. */ + update(obj: Object3D | null, box: Box3 | null, camera: Camera, viewHeightPx: number, fovDeg: number, opts: { layout: ScaleLayout; pivot: 'bottom-center' | 'center'; pinned: boolean }): void { + this.layout = opts.layout + this.rootPivot = opts.pivot + const ctrl = opts.pinned + this.group.visible = !!obj && !!box && !box.isEmpty() + if (!obj || !box || box.isEmpty()) return + obj.updateMatrixWorld(true) + const pos = this.positions(obj, box) + const min = box.min.toArray() as V3 + const max = box.max.toArray() as V3 + const root = obj.localToWorld(new Vector3((min[0] + max[0]) / 2, (min[1] + max[1]) / 2, this.rootPivot === 'center' ? (min[2] + max[2]) / 2 : min[2])) + const shown = new Set(handleIds(this.layout)) + const active = this.dragging ?? this.hover + for (const [id, h] of this.handles) { + h.visible = shown.has(id) + const line0 = this.lines.get(id) + if (line0) line0.visible = shown.has(id) + const p = pos[id] + if (!p) continue + const dist = camera.position.distanceTo(p) + const size = (2 * dist * Math.tan((fovDeg * Math.PI) / 360) * SIZE_PX) / Math.max(1, viewHeightPx) + h.position.copy(p) + h.scale.setScalar(size * (handleAxis(id) === 'uniform' ? 1.15 : 1)) + const pinned = ctrl && active !== null && oppositeHandle(active, this.layout) === id + const color = id === active ? HOT : pinned ? CONSTRAINED : AXIS[handleAxis(id)] + ;(h.material as MeshBasicMaterial).color.set(color) + const line = this.lines.get(id) + if (line) { + const len = root.distanceTo(p) + line.position.copy(root).lerp(p, 0.5) + if (len > 1e-6) line.lookAt(p) + line.scale.set(size * 0.2, size * 0.2, Math.max(len, 1e-6)) + ;(line.material as MeshBasicMaterial).color.set(color) + } + } + } + + hit(ray: Raycaster): HandleId | null { + if (!this.group.visible) return null + const h = ray.intersectObjects([...this.handles.values()].filter((m) => m.visible), false)[0] + return (h?.object.userData.handle as HandleId | undefined) ?? null + } + + setHover(id: HandleId | null): boolean { + if (id === this.hover) return false + this.hover = id + return true + } + + setDragging(id: HandleId | null): void { + this.dragging = id + } + + /** Handle positions in world space, for tests and tutorials. */ + handleWorld(obj: Object3D, box: Box3): Partial> { + const p = this.positions(obj, box) + const out: Partial> = {} + for (const id of handleIds(this.layout)) { + const v = p[id] + if (v) out[id] = v.toArray() as V3 + } + return out + } + + dispose(): void { + for (const m of [...this.handles.values(), ...this.lines.values()]) { + m.geometry.dispose() + ;(m.material as MeshBasicMaterial).dispose() + } + this.group.removeFromParent() + } +} diff --git a/desktop/src/vendor/slicerx/viewport/gizmobindings.ts b/desktop/src/vendor/slicerx/viewport/gizmobindings.ts new file mode 100644 index 00000000..34585385 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/gizmobindings.ts @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Modifier keys, steps and layouts of the move, scale and paint tools, one set per look preset, read from the +// sources of the apps the presets imitate (Orca v2.4.2 and Bambu Studio: src/slic3r/GUI/Gizmos GLGizmoScale.cpp, +// GLGizmoMove.cpp, GLGizmoPainterBase.cpp, libslic3r TriangleSelector.cpp; PrusaSlicer 3.0 alpha: slic3r-shared +// src/Slic3r/App/Plater ScaleGizmo.cpp and PaintOnGizmoBase.cpp). SlicerX follows Bambu Studio. Pure data, no +// three.js; Settings edits it with `withGizmoOverrides`. + +export type ModKey = 'shift' | 'ctrl' | 'alt' +export type PaintToolId = 'brush' | 'triangle' | 'fill' | 'smart' | 'height' | 'gap' | 'replace' + +export interface ScaleBindings { + /** + * `bottom`: x and y handles at the middle of the bottom edges, a z handle on top, uniform handles at the + * bottom corners (Orca, Bambu Studio). `faces`: a handle at the center of each of the six faces and uniform + * handles at the corners of the middle height (PrusaSlicer 3.0). + */ + layout: 'bottom' | 'faces' + /** What a drag scales about. Orca and Bambu Studio scale about the bottom center so the model stays on the bed. */ + pivot: 'bottom-center' | 'center' + /** Holding this pins the opposite handle while an axis handle is dragged. Null: no such key. */ + pinKey: ModKey | null + /** Orca reads the pin key when the drag starts; Bambu Studio follows the key while dragging. */ + pinMode: 'at-start' | 'live' + /** A pinned corner handle in Orca keeps the opposite corner and scales x and y only; in Bambu Studio corners ignore the pin. */ + cornerPinLocksZ: boolean + /** Holding this snaps the factor to `snapStep`. */ + snapKey: ModKey | null + snapStep: number + /** + * How the pointer becomes a factor. `plane`: the ray meets the plane of the handle (Orca). `point`: the point of the + * ray nearest the handle's start position (Bambu Studio). `line`: the point of the handle line nearest the ray, + * measured from where the drag began (PrusaSlicer). + */ + ratio: 'plane' | 'point' | 'line' + /** Smallest size a drag may leave, mm (PrusaSlicer keeps at least 1 mm). Null: only the factor limit applies. */ + minSizeMm: number | null + /** Orca's Alt: scale each model about its own origin instead of a shared pivot. It changes nothing for one model. */ + independentKey: ModKey | null +} + +export interface MoveBindings { + /** Holding this snaps a move to `snapStepMm`. Null: no snapping. */ + snapKey: ModKey | null + snapStepMm: number +} + +export interface RotateBindings { + /** + * Holding this snaps the angle of a ring drag to `snapStepDeg`. None of the three apps has such a key (Orca, Bambu Studio and + * PrusaSlicer snap by where the cursor sits on the ring, GLGizmoRotate::on_dragging); SlicerX uses the key the look snaps moves + * and scales with, Shift, on every look. + */ + snapKey: ModKey | null + snapStepDeg: number +} + +export interface PaintBindings { + /** Holding this while painting erases. */ + eraseKey: ModKey | null + /** + * What the right button does on the color layer: `camera` leaves it to the camera (Orca, Bambu Studio), or + * `second-state` paints the second brush color (PrusaSlicer). On the seam and support layers it always paints a blocker. + */ + colorRightButton: 'camera' | 'second-state' + /** The key that changes radius, height band, fill angle and gap area with the wheel, and the key that moves the clipping plane. */ + wheelParamKey: ModKey + wheelClipKey: ModKey + radius: { default: number; min: number; max: number; step: number } + /** The edge limit of splitting is `radius / divisor`, at most `cap` mm when given. */ + detail: { divisor: number; cap: number | null } + /** `bottom`: a band of the thickness starting at the pointer height; `center`: centered on it. */ + height: { anchor: 'bottom' | 'center'; default: number; min: number; max: number; step: number } + /** Orca and Bambu Studio share one angle for smart fill and bucket fill; PrusaSlicer keeps two. */ + angle: { smart: number; bucket: number; shared: boolean; min: number; max: number; step: number } + /** Gap fill (Orca, Bambu Studio): patches smaller than the area merge into a neighbor. Null: no gap fill. */ + gapArea: { default: number; min: number; max: number; step: number } | null + tools: readonly PaintToolId[] +} + +export interface GizmoBindings { + scale: ScaleBindings + move: MoveBindings + rotate: RotateBindings + paint: PaintBindings +} + +const ORCA_TOOLS: readonly PaintToolId[] = ['brush', 'triangle', 'height', 'fill', 'smart', 'gap'] + +export const BAMBU_GIZMO: GizmoBindings = { + scale: { layout: 'bottom', pivot: 'bottom-center', pinKey: 'ctrl', pinMode: 'live', cornerPinLocksZ: false, snapKey: 'shift', snapStep: 0.05, ratio: 'point', minSizeMm: null, independentKey: null }, + move: { snapKey: 'shift', snapStepMm: 1 }, + rotate: { snapKey: 'shift', snapStepDeg: 15 }, + paint: { + eraseKey: 'shift', + colorRightButton: 'camera', + wheelParamKey: 'ctrl', + wheelClipKey: 'alt', + radius: { default: 1, min: 0.4, max: 8, step: 0.2 }, + detail: { divisor: 5, cap: 0.2 }, + height: { anchor: 'bottom', default: 0.2, min: 0.1, max: 8, step: 0.2 }, + angle: { smart: 30, bucket: 30, shared: true, min: 0, max: 90, step: 1 }, + gapArea: { default: 0, min: 0, max: 5, step: 0.2 }, + tools: ORCA_TOOLS, + }, +} + +export const ORCA_GIZMO: GizmoBindings = { + scale: { layout: 'bottom', pivot: 'bottom-center', pinKey: 'ctrl', pinMode: 'at-start', cornerPinLocksZ: true, snapKey: 'shift', snapStep: 0.05, ratio: 'plane', minSizeMm: null, independentKey: 'alt' }, + move: { snapKey: 'shift', snapStepMm: 1 }, + rotate: { snapKey: 'shift', snapStepDeg: 15 }, + paint: { ...BAMBU_GIZMO.paint, detail: { divisor: 5, cap: 0.05 } }, +} + +export const PRUSA_GIZMO: GizmoBindings = { + scale: { layout: 'faces', pivot: 'center', pinKey: null, pinMode: 'at-start', cornerPinLocksZ: false, snapKey: null, snapStep: 0.05, ratio: 'line', minSizeMm: 1, independentKey: null }, + move: { snapKey: null, snapStepMm: 1 }, + rotate: { snapKey: 'shift', snapStepDeg: 15 }, + paint: { + eraseKey: 'shift', + colorRightButton: 'second-state', + wheelParamKey: 'alt', + wheelClipKey: 'ctrl', + radius: { default: 2, min: 0.4, max: 8, step: 0.2 }, + detail: { divisor: 5, cap: null }, + height: { anchor: 'center', default: 1, min: 0.1, max: 10, step: 0.1 }, + angle: { smart: 30, bucket: 90, shared: false, min: 0, max: 90, step: 1 }, + gapArea: null, + tools: ['brush', 'triangle', 'height', 'fill', 'smart', 'replace'], + }, +} + +type DeepPartial = T extends readonly unknown[] ? T : T extends object ? { [K in keyof T]?: DeepPartial } : T +export type GizmoOverrides = DeepPartial + +/** A person's edits from Settings applied on top of a preset's gizmo bindings. The preset is not changed. */ +export function withGizmoOverrides(base: GizmoBindings, o: GizmoOverrides): GizmoBindings { + const merge = (a: T, b: DeepPartial | null | undefined): T => { + if (!b) return a + const out = { ...a } as Record + for (const [k, v] of Object.entries(b)) { + if (v === undefined) continue + const cur = out[k] + out[k] = v !== null && typeof v === 'object' && !Array.isArray(v) && cur !== null && typeof cur === 'object' && !Array.isArray(cur) ? merge(cur as object, v as DeepPartial) : v + } + return out as T + } + return { scale: merge(base.scale, o.scale), move: merge(base.move, o.move), rotate: merge(base.rotate, o.rotate), paint: merge(base.paint, o.paint) } +} diff --git a/desktop/src/vendor/slicerx/viewport/gpu.ts b/desktop/src/vendor/slicerx/viewport/gpu.ts new file mode 100644 index 00000000..08294f84 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/gpu.ts @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// What the viewport makes of the GPU: whether to start on the low quality tier, and whether to warn that 3D is +// drawn on the processor. WebKit reports a made-up GPU name to pages, so on Linux the desktop shell reads the +// real renderer itself and passes it in; that name wins over the one WebGL gives. + +/** Renderers that draw on the processor: Mesa's llvmpipe and softpipe, SwiftShader, Windows' basic renderer. */ +const SOFTWARE = /swiftshader|llvmpipe|softpipe|software|basic render/i +/** Old mobile GPUs that cannot keep up with the high tier. */ +const SLOW = /mali-4|adreno \(tm\) 3/i + +export interface GpuProfile { + /** The renderer name the viewport reports in stats(). */ + name: string + /** Start on the low quality tier with a smaller environment and pixel ratio. */ + weak: boolean + /** 3D is drawn on the processor. */ + software: boolean + /** The name came from the desktop shell, not from WebGL. */ + fromShell: boolean +} + +/** A WebGL2 context that refuses a major performance caveat fails to start on most software renderers. */ +function refusesCaveat(): boolean { + try { + const probe = document.createElement('canvas') + const ok = probe.getContext('webgl2', { failIfMajorPerformanceCaveat: true }) + ok?.getExtension('WEBGL_lose_context')?.loseContext() + return !ok + } catch { + return false + } +} + +/** + * `webgl` is the renderer WebGL reports; `shell` the one the desktop shell read, when it has one. The shell's + * name is trusted as is. WebGL's may be masked, so a software renderer is also caught by the caveat probe. + */ +export function gpuProfile(webgl: string, shell?: string | null, probe: () => boolean = refusesCaveat, cores = typeof navigator !== 'undefined' ? navigator.hardwareConcurrency || 8 : 8): GpuProfile { + const fromShell = Boolean(shell) + const name = shell || webgl + const software = SOFTWARE.test(name) || (!fromShell && probe()) + return { name, weak: SOFTWARE.test(name) || SLOW.test(name) || cores <= 2, software, fromShell } +} diff --git a/desktop/src/vendor/slicerx/viewport/guides.ts b/desktop/src/vendor/slicerx/viewport/guides.ts new file mode 100644 index 00000000..234313c6 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/guides.ts @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Guides for the modeling tools: measured end points with the line between them, the outline of a picked +// face and the profile about to be extruded. Drawn through the model so they read from any angle. +import { BufferGeometry, Color, Float32BufferAttribute, Group, LineBasicMaterial, LineSegments, Mesh, MeshBasicMaterial, SphereGeometry } from 'three' +import { SCENE } from './palette' + +export type GuidePoint = [number, number, number] + +export interface Guides { + /** Straight segments, such as a measured distance. */ + lines?: readonly { from: GuidePoint; to: GuidePoint }[] + /** Closed outlines, such as a shape profile. `soft` draws the dimmer line used for the face behind the shape. */ + loops?: readonly { points: readonly GuidePoint[]; soft?: boolean }[] + /** End points, drawn as dots. */ + points?: readonly GuidePoint[] +} + +const DOT = new SphereGeometry(0.7, 12, 8) + +export class GuideLines { + /** Child of the objects root (bed frame, Z up, mm). */ + readonly group = new Group() + private readonly line = new LineBasicMaterial({ color: new Color(SCENE.selection), depthTest: false, transparent: true, opacity: 0.98, toneMapped: false }) + private readonly soft = new LineBasicMaterial({ color: new Color(SCENE.selection), depthTest: false, transparent: true, opacity: 0.45, toneMapped: false }) + private readonly dot = new MeshBasicMaterial({ color: new Color(SCENE.selection), depthTest: false, toneMapped: false }) + private drawn: (LineSegments | Mesh)[] = [] + + constructor() { + this.group.name = 'guides' + this.group.renderOrder = 5 + } + + /** True when something was or is now drawn, so the caller knows to redraw. */ + set(g: Guides): boolean { + const had = this.drawn.length > 0 + for (const d of this.drawn) { + this.group.remove(d) + if (d instanceof LineSegments) d.geometry.dispose() + } + this.drawn = [] + const segments = (positions: number[], material: LineBasicMaterial): void => { + if (positions.length < 6) return + const geo = new BufferGeometry() + geo.setAttribute('position', new Float32BufferAttribute(positions, 3)) + const seg = new LineSegments(geo, material) + seg.renderOrder = 5 + this.group.add(seg) + this.drawn.push(seg) + } + segments((g.lines ?? []).flatMap((l) => [...l.from, ...l.to]), this.line) + for (const soft of [false, true]) { + const pos: number[] = [] + for (const loop of g.loops ?? []) { + if (Boolean(loop.soft) !== soft || loop.points.length < 2) continue + loop.points.forEach((p, i) => pos.push(...p, ...(loop.points[(i + 1) % loop.points.length] as GuidePoint))) + } + segments(pos, soft ? this.soft : this.line) + } + for (const p of g.points ?? []) { + const dot = new Mesh(DOT, this.dot) + dot.position.set(p[0], p[1], p[2]) + dot.renderOrder = 5 + this.group.add(dot) + this.drawn.push(dot) + } + return had || this.drawn.length > 0 + } + + setColor(color: string): void { + this.line.color.set(color) + this.soft.color.set(color) + this.dot.color.set(color) + } + + dispose(): void { + this.set({}) + this.line.dispose() + this.soft.dispose() + this.dot.dispose() + } +} diff --git a/desktop/src/vendor/slicerx/viewport/headparts.ts b/desktop/src/vendor/slicerx/viewport/headparts.ts new file mode 100644 index 00000000..9e023b7a --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/headparts.ts @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Materials and solid-building helpers shared by the toolhead models (toolhead.ts, heads.ts). Sizes in mm. +import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js' +import { BoxGeometry, Color, CylinderGeometry, Group, Mesh, MeshBasicMaterial, MeshStandardMaterial, SphereGeometry, TorusGeometry, type BufferGeometry, type Material } from 'three' + +// Colors: the machines' own (brushed silver, black anodized, Snapmaker white and orange), with the app's +// tokens where the machine leaves a choice: --orange for the hot plate and lever, --cyan for the ring at +// the nozzle, the light strips white. +export const brass = new MeshStandardMaterial({ color: new Color('#d9b98a'), metalness: 0.9, roughness: 0.28 }) +export const steel = new MeshStandardMaterial({ color: new Color('#b4b9c6'), metalness: 0.85, roughness: 0.3 }) +export const silver = new MeshStandardMaterial({ color: new Color('#a3a6ae'), metalness: 0.7, roughness: 0.34 }) +export const black = new MeshStandardMaterial({ color: new Color('#34363f'), metalness: 0.35, roughness: 0.5 }) +export const deep = new MeshStandardMaterial({ color: new Color('#1d1e24'), metalness: 0.2, roughness: 0.6 }) +export const sock = new MeshStandardMaterial({ color: new Color('#4a4c56'), metalness: 0.05, roughness: 0.8 }) +export const white = new MeshStandardMaterial({ color: new Color('#e6e6ea'), metalness: 0.05, roughness: 0.42 }) +export const graphite = new MeshStandardMaterial({ color: new Color('#44475a'), metalness: 0.35, roughness: 0.45 }) +export const dark = new MeshStandardMaterial({ color: new Color('#2f3241'), metalness: 0.2, roughness: 0.6 }) +export const orange = new MeshBasicMaterial({ color: new Color('#fab570') }) +export const prusaOrange = new MeshStandardMaterial({ color: new Color('#f26b21'), metalness: 0.05, roughness: 0.55 }) +export const amber = new MeshStandardMaterial({ color: new Color('#f5a623'), metalness: 0.1, roughness: 0.4 }) +export const lightMat = new MeshBasicMaterial({ color: new Color('#f4f6ff') }) +export const ringMat = new MeshBasicMaterial({ color: new Color('#8be9fd') }) +export const tipMat = new MeshBasicMaterial({ color: new Color('#fff2c4') }) + +export const part = (geo: BufferGeometry, mat: Material, x: number, y: number, z: number, name = ''): Mesh => { + const m = new Mesh(geo, mat) + m.position.set(x, y, z) + m.name = name + return m +} +export const block = (w: number, d: number, h: number, r = 0.6) => new RoundedBoxGeometry(w, d, h, 3, r) +/** A box from its extents. */ +export const slab = (mat: Material, x0: number, x1: number, y0: number, y1: number, z0: number, z1: number, name: string, r = 0): Mesh => + part(r > 0 ? block(x1 - x0, y1 - y0, z1 - z0, r) : new BoxGeometry(x1 - x0, y1 - y0, z1 - z0), mat, (x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2, name) +/** A cylinder standing on z (three's cylinders stand on y). */ +export const post = (r: number, h: number, seg = 32) => new CylinderGeometry(r, r, h, seg).rotateX(Math.PI / 2) + +export function ring(g: Group): void { + const r = new Mesh(new TorusGeometry(2.3, 0.22, 8, 32), ringMat) + r.position.z = 2.1 + const tip = new Mesh(new SphereGeometry(0.4, 12, 10), tipMat) + tip.position.z = 0.15 + g.add(r, tip) +} + +/** The hot plate on a Bambu front: a black square with three orange heat waves over a short bar. */ +export function hotPlate(x: number, y: number, z: number): Group { + const g = new Group() + g.add(slab(deep, -6, 6, -0.6, 0, -6, 6, 'plate')) + for (const dx of [-2.2, 0, 2.2]) g.add(slab(orange, dx - 0.35, dx + 0.35, -0.9, -0.6, -1, 3, 'wave')) + g.add(slab(orange, -3.2, 3.2, -0.9, -0.6, -3.2, -2.4, 'wave')) + g.position.set(x, y, z) + return g +} diff --git a/desktop/src/vendor/slicerx/viewport/headpath.ts b/desktop/src/vendor/slicerx/viewport/headpath.ts new file mode 100644 index 00000000..f400e190 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/headpath.ts @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Where the toolhead is part of the way through a move during Preview playback, and how much of that move's bead +// is laid down. The head runs along the move at its own pace rather than jumping from one move's end to the next: +// when the move starts away from where the last one ended, the first part of its time is the travel there (no +// bead yet); and where two moves meet, the head rounds the corner a little (at most CORNER_MM, and a quarter of +// either move), the way a real machine eases a change of direction instead of stopping dead. + +/** One move as the preview buffer stores it: from (x0, y0) to (x1, y1) at height z, in bed millimetres. */ +export interface HeadSeg { + x0: number + y0: number + x1: number + y1: number + z: number +} + +/** The head's point and the share of the move's bead drawn (0 while it is still travelling to the move). */ +export interface HeadPoint { + x: number + y: number + z: number + reveal: number +} + +/** Largest corner rounding, in millimetres. */ +export const CORNER_MM = 1 +/** Moves closer than this (mm) count as continuous: no travel between them. */ +const JOIN_MM = 0.05 +/** The travel to a move takes at most this share of the move's time, so the bead always gets the rest. */ +const TRAVEL_SHARE_MAX = 0.5 + +const len = (s: HeadSeg) => Math.hypot(s.x1 - s.x0, s.y1 - s.y0) +const along = (s: HeadSeg, d: number): [number, number] => { + const l = len(s) + const k = l > 1e-9 ? Math.min(1, Math.max(0, d / l)) : 1 + return [s.x0 + (s.x1 - s.x0) * k, s.y0 + (s.y1 - s.y0) * k] +} +const joined = (a: HeadSeg, b: HeadSeg) => Math.hypot(b.x0 - a.x1, b.y0 - a.y1) <= JOIN_MM && Math.abs(b.z - a.z) <= 1e-6 +const bezier = (p0: [number, number], p1: [number, number], p2: [number, number], u: number): [number, number] => { + const v = 1 - u + return [v * v * p0[0] + 2 * v * u * p1[0] + u * u * p2[0], v * v * p0[1] + 2 * v * u * p1[1] + u * u * p2[1]] +} +/** The corner radius between two joined moves: the same from either side, so the head never jumps at the join. */ +const radius = (a: HeadSeg, b: HeadSeg) => Math.min(CORNER_MM, 0.25 * len(a), 0.25 * len(b)) + +/** + * The head `f` (0 to 1) of the way through move `i`'s time. `get` returns a move by index, or null past either end. + * The point is continuous in time: at `f = 1` of one move it is where `f = 0` of a joined next move starts. + */ +export function headAt(get: (i: number) => HeadSeg | null, i: number, f: number): HeadPoint { + const s = get(i) + if (!s) return { x: 0, y: 0, z: 0, reveal: 0 } + const prev = get(i - 1) + const next = get(i + 1) + const L = len(s) + let t = Math.min(1, Math.max(0, f)) + // A travel into the move: the head crosses from the last move's end first, drawing nothing. + if (prev && !joined(prev, s)) { + const gap = Math.hypot(s.x0 - prev.x1, s.y0 - prev.y1) + Math.abs(s.z - prev.z) + const share = Math.min(TRAVEL_SHARE_MAX, gap / (gap + Math.max(L, 1e-6))) + if (t < share) { + const u = share > 0 ? t / share : 1 + return { x: prev.x1 + (s.x0 - prev.x1) * u, y: prev.y1 + (s.y0 - prev.y1) * u, z: prev.z + (s.z - prev.z) * u, reveal: 0 } + } + t = share < 1 ? (t - share) / (1 - share) : 1 + } + const d = t * L + let p = along(s, d) + // Ease the corner into the next joined move, and out of the joined move before. + const rEnd = next && joined(s, next) ? radius(s, next) : 0 + const rStart = prev && joined(prev, s) ? radius(prev, s) : 0 + if (rEnd > 1e-6 && d > L - rEnd) { + p = bezier(along(s, L - rEnd), [s.x1, s.y1], along(next!, rEnd), (d - (L - rEnd)) / (2 * rEnd)) + } else if (rStart > 1e-6 && d < rStart) { + p = bezier(along(prev!, len(prev!) - rStart), [s.x0, s.y0], along(s, rStart), 0.5 + d / (2 * rStart)) + } + return { x: p[0], y: p[1], z: s.z, reveal: t } +} diff --git a/desktop/src/vendor/slicerx/viewport/heads.ts b/desktop/src/vendor/slicerx/viewport/heads.ts new file mode 100644 index 00000000..902ef4a5 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/heads.ts @@ -0,0 +1,374 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// The single-nozzle toolheads Preview draws at the current move, one per printer family, after the +// machines' product photos (sources in docs/toolchanger-sim.md, "The models"). Low poly: every part is a +// separate solid in millimeters, nozzle tip at the origin, z up, the front of the printer toward -y. Parts +// that meet only touch (test/toolhead.test.ts checks every head). Each head shows the printing filament on +// the filament inlet at its top, or on the H2S's nozzle display. +import { Color, ConeGeometry, CylinderGeometry, Group, MeshBasicMaterial, MeshStandardMaterial, type Material, type Mesh } from 'three' +import { amber, black, brass, deep, graphite, hotPlate, lightMat, part, post, prusaOrange, ring, silver, slab, sock, steel, white } from './headparts' + +/** The head families Preview draws for printers with one nozzle. */ +export const HEAD_MODELS = [ + 'bambu-x1', + 'bambu-p1', + 'bambu-a1', + 'bambu-h2s', + 'prusa-nextruder', + 'prusa-mini', + 'voron-stealthburner', + 'sovol-sv08', + 'creality-k1', + 'creality-k2', + 'creality-ender3-v3', + 'creality-sprite', + 'elegoo-centauri', + 'elegoo-neptune4', + 'anycubic-kobra', + 'qidi', + 'snapmaker-module', + 'generic', +] as const +export type HeadModel = (typeof HEAD_MODELS)[number] + +/** The head family for a printer profile id (`bambu-p1s`, `voron-2.4-350`); `generic` when none is close. */ +export function headFor(printerId: string | undefined | null): HeadModel { + const id = (printerId ?? '').toLowerCase() + const table: [RegExp, HeadModel][] = [ + [/^bambu-x1/, 'bambu-x1'], + [/^bambu-(p1|p2)/, 'bambu-p1'], + [/^bambu-a1/, 'bambu-a1'], + [/^bambu-h2/, 'bambu-h2s'], + [/^bambu-/, 'bambu-p1'], + [/^prusa-(mk4|mk3\.9|core-one|xl)/, 'prusa-nextruder'], + [/^prusa-mini/, 'prusa-mini'], + [/^prusa-/, 'prusa-nextruder'], + [/^(voron-|vzbot|ratrig)/, 'voron-stealthburner'], + [/^sovol-sv08/, 'sovol-sv08'], + [/^creality-(k1|hi)/, 'creality-k1'], + [/^creality-k2/, 'creality-k2'], + [/^creality-ender-3-v3(-plus)?$/, 'creality-ender3-v3'], + [/^creality-/, 'creality-sprite'], + [/^elegoo-centauri/, 'elegoo-centauri'], + [/^elegoo-/, 'elegoo-neptune4'], + [/^anycubic-/, 'anycubic-kobra'], + [/^qidi-/, 'qidi'], + [/^snapmaker-(a250|a350|artisan|j1)/, 'snapmaker-module'], + ] + return table.find(([re]) => re.test(id))?.[1] ?? 'generic' +} + +// Machine colors (not app tokens): the plastics and paints the printers ship in. +const bambuGray = new MeshStandardMaterial({ color: new Color('#aeb1b8'), metalness: 0.2, roughness: 0.45 }) +const a1Gray = new MeshStandardMaterial({ color: new Color('#c3c6cc'), metalness: 0.15, roughness: 0.5 }) +const gunmetal = new MeshStandardMaterial({ color: new Color('#555963'), metalness: 0.45, roughness: 0.4 }) +const voronRed = new MeshStandardMaterial({ color: new Color('#c8312c'), metalness: 0.05, roughness: 0.5 }) +const sovolBlue = new MeshStandardMaterial({ color: new Color('#86a9d4'), metalness: 0.05, roughness: 0.5 }) +const enderSilver = new MeshStandardMaterial({ color: new Color('#b6b9bf'), metalness: 0.5, roughness: 0.35 }) +const caution = new MeshStandardMaterial({ color: new Color('#f2c230'), metalness: 0.05, roughness: 0.5 }) +const lidarGreen = new MeshBasicMaterial({ color: new Color('#3fd27a') }) +const labelOrange = new MeshBasicMaterial({ color: new Color('#f26b21') }) + +export interface BuiltHead { + group: Group + /** Painted in the printing filament's color. */ + sleeve: Mesh + /** Radius of the soft shadow under the head. */ + shadow: number +} + +/** The nozzle under a silicone sock, tip at the origin, with the ring that marks the extrusion point. */ +function nozzle(g: Group, sockHalf = 5, sockTop = 8): void { + g.add(part(new ConeGeometry(1.6, 3, 24).rotateX(-Math.PI / 2), brass, 0, 0, 1.5, 'nozzle'), slab(sock, -sockHalf, sockHalf, -sockHalf, sockHalf, 3, sockTop, 'sock', 1.2)) + ring(g) +} + +/** A round fan on a front face at y = `face`, centered at (x, z): the dark disc and the hub in front of it. */ +function frontFan(g: Group, face: number, x: number, z: number, r: number, hubMat: Material = graphite): void { + g.add(part(new CylinderGeometry(r, r, 1, 48), deep, x, face - 0.5, z, 'fan'), part(new CylinderGeometry(r * 0.32, r * 0.32, 1, 32), hubMat, x, face - 1.5, z, 'hub')) +} + +/** The filament inlet on top of the head, in the filament's color. */ +function inlet(g: Group, z: number, y = 0, h = 8): Mesh { + const m = part(post(2.2, h, 20), steel, 0, y, z + h / 2, 'inlet') + g.add(m) + return m +} + +/** Two part cooling outlets either side of the nozzle, under a body that starts at `z`. */ +function sidePods(g: Group, z: number, mat: Material = black, half = 16, y0 = -15, y1 = 12): void { + g.add(slab(mat, -half, -7, y0, y1, z - 6, z, 'duct', 1.5), slab(mat, 7, half, y0, y1, z - 6, z, 'duct', 1.5)) +} + +/** X1 Carbon, X1E (with the Micro Lidar) and P1P, P1S, P2S: a black head behind a light gray front with the round part cooling fan. */ +function bambuX1(lidar: boolean): BuiltHead { + const g = new Group() + nozzle(g) + g.add( + slab(black, -26, 26, -20, 26, 8, 20, 'base', 2), + slab(black, -28, 28, -16, 30, 20, 88, 'body', 4), + slab(bambuGray, -28, 28, -25, -16, 20, 86, 'cover', 4.4), + slab(deep, -11, 11, -25.4, -25, 76, 78.5, 'label'), + ) + frontFan(g, -25, 0, 50, 17) + if (lidar) g.add(slab(graphite, 28, 46, -24, -4, 4, 19.5, 'lidar', 1.5), slab(lidarGreen, 33, 43, -24.4, -24, 11, 13, 'lidar lens')) + return { group: g, sleeve: inlet(g, 88, 6), shadow: 30 } +} + +/** + * A1 and A1 mini, estimated from Bambu's product photos: a low, wide light gray head (the hotend housing and its clip + * under it, the round extruder window in front) with the cable chain leaving its left side, link by link, for the + * frame. + */ +function bambuA1(): BuiltHead { + const g = new Group() + nozzle(g) + g.add( + slab(graphite, -15, 15, -14, 12, 8, 18, 'housing', 2), + slab(steel, 15, 18, -10, 4, 9, 17, 'clip', 1), + slab(a1Gray, -30, 30, -16, 22, 18, 60, 'body', 5), + part(new CylinderGeometry(9, 9, 1, 40), deep, 10, -16.5, 42, 'window'), + part(new CylinderGeometry(5.5, 5.5, 1, 32), amber, 10, -17.5, 42, 'gear'), + slab(deep, -22, -8, -16.4, -16, 44, 46.5, 'label'), + ) + // The cable chain: dark links stepping out and up from the left side. + for (let i = 0; i < 5; i++) g.add(slab(deep, -30 - 7 * (i + 1), -30 - 7 * i, -4, 14, 40 + 3 * i, 48 + 3 * i, 'cable chain', 1)) + return { group: g, sleeve: inlet(g, 60, 6), shadow: 30 } +} + +/** H2S: the H2 family head with one hotend: brushed cover over a black body, the nozzle display and the hot plate. */ +function bambuH2S(): BuiltHead { + const g = new Group() + nozzle(g, 5, 7.8) + const chip = slab(steel, 4, 7.2, -18.3, -18, 49.5, 52, 'chip') + g.add( + slab(black, -14, 14, -17, 17, 7.8, 58.5, 'body', 2), + slab(black, -20, -14, -12, 14, 14, 58.5, 'fan', 2), + slab(black, 14, 20, -12, 14, 14, 58.5, 'fan', 2), + slab(deep, -8, 6, -18, -17, 48, 53.5, 'display'), + chip, + hotPlate(0, -17, 28), + slab(deep, -18, 18, -15, 15, 58.5, 62, 'band'), + slab(silver, -20, 20, -17, 17, 62, 92, 'cover', 5), + slab(lightMat, -12, 12, -17.5, -17, 86, 87.4, 'light'), + slab(steel, -10, 10, -17.4, -17, 70, 72.5, 'logo'), + ) + return { group: g, sleeve: chip, shadow: 22 } +} + +/** Prusa Nextruder (MK4, MK4S, Core One, XL): black, the planetary extruder on top with its label, the hotend fan in front, the blower at the side. */ +function nextruder(): BuiltHead { + const g = new Group() + nozzle(g, 6, 10) + g.add( + slab(black, -20, 20, -18, 18, 10, 52, 'body', 3), + slab(black, -14, 18, -22, -18, 18, 46, 'fan frame', 2), + slab(black, -30, -20, -14, 16, 14, 46, 'blower', 3), + slab(black, -24, -8, -16, -8, 6, 10, 'outlet', 1.5), + slab(black, -20, 20, -14, 22, 52, 88, 'extruder', 3), + slab(deep, -14, 14, -14.6, -14, 62, 84, 'plate'), + slab(labelOrange, -10, 10, -14.9, -14.6, 70, 74, 'label'), + slab(black, -6, 6, -10, 4, 88, 96, 'lever', 1.5), + ) + frontFan(g, -22, 2, 32, 12) + return { group: g, sleeve: inlet(g, 96, -3, 6), shadow: 24 } +} + +/** Prusa MINI+: the orange printed shroud with its front fan, the black blower at the side, the extruder on top. */ +function prusaMini(): BuiltHead { + const g = new Group() + nozzle(g, 5, 7) + g.add( + slab(steel, -8, 8, -6, 6, 7, 11, 'heater', 1), + slab(prusaOrange, -18, 18, -16, 14, 11, 56, 'shroud', 3), + slab(black, 18, 28, -12, 12, 16, 46, 'blower', 2), + slab(black, 8, 22, -14, -6, 4, 11, 'outlet', 1), + slab(black, -14, 14, -10, 16, 56, 76, 'extruder', 2), + ) + frontFan(g, -16, 0, 34, 11, black) + return { group: g, sleeve: inlet(g, 76, 3, 10), shadow: 20 } +} + +/** Voron Stealthburner (and the SV08's head built on it): the faceted accent cover with the lit logo, the hotend fan, two ducts, the Clockwork extruder and its pancake motor. */ +function stealthburner(accent: Material): BuiltHead { + const g = new Group() + nozzle(g, 6, 9) + g.add( + slab(black, -24, 24, -12, 22, 9, 40, 'body', 3), + slab(accent, -24, 24, -20, -12, 12, 40, 'front', 3), + slab(black, -24, -10, -20, -12, 4, 12, 'duct', 1.5), + slab(black, 10, 24, -20, -12, 4, 12, 'duct', 1.5), + slab(accent, -22, 22, -18, 10, 40, 72, 'cover', 4), + slab(black, -22, 22, 10, 26, 40, 72, 'back', 3), + slab(lightMat, -1.5, 1.5, -18.4, -18, 54, 66, 'logo'), + slab(lightMat, -6, -3, -18.4, -18, 58, 62, 'logo'), + slab(black, -12, 12, -8, 18, 72, 84, 'extruder', 2), + part(new CylinderGeometry(14, 14, 10, 40), black, 0, 31, 58, 'motor'), + ) + frontFan(g, -20, 0, 26, 12) + return { group: g, sleeve: inlet(g, 84, 4, 8), shadow: 26 } +} + +/** Creality K1, K1C, K1 Max, K1 SE, Hi: a black head behind a dark front with a large round fan and the label. */ +function crealityK1(): BuiltHead { + const g = new Group() + nozzle(g) + sidePods(g, 10, black, 18) + g.add( + slab(black, -24, 24, -18, 24, 10, 70, 'body', 4), + slab(deep, -24, 24, -22, -18, 12, 70, 'cover', 1.8), + slab(steel, -9, 9, -22.4, -22, 62, 64.5, 'label'), + ) + frontFan(g, -22, 0, 40, 14, steel) + return { group: g, sleeve: inlet(g, 70, 4), shadow: 26 } +} + +/** Creality K2 Plus: the larger gunmetal head with a black front, a vertical light and the round fan. */ +function crealityK2(): BuiltHead { + const g = new Group() + nozzle(g) + sidePods(g, 10, black, 20) + g.add( + slab(gunmetal, -27, 27, -20, 26, 10, 82, 'body', 4), + slab(black, -24, 24, -24, -20, 14, 78, 'front', 1.8), + slab(lightMat, -1, 1, -24.4, -24, 54, 74, 'light'), + ) + frontFan(g, -24, 0, 34, 12) + return { group: g, sleeve: inlet(g, 82, 4), shadow: 28 } +} + +/** Creality Ender-3 V3 and V3 Plus: a rounded silver head with the big round fan and two cooling pods, the extruder on top. */ +function enderV3(): BuiltHead { + const g = new Group() + nozzle(g) + sidePods(g, 14, graphite, 21, -16, 14) + g.add(slab(enderSilver, -21, 21, -18, 20, 14, 68, 'body', 5), slab(black, -14, 14, -8, 18, 68, 82, 'extruder', 2)) + frontFan(g, -18, 0, 42, 14, steel) + return { group: g, sleeve: inlet(g, 82, 5), shadow: 22 } +} + +/** Creality Sprite heads (Ender-3 V3 SE and KE, older Enders): black, a yellow caution label, the round fan, the label strip. */ +function crealitySprite(): BuiltHead { + const g = new Group() + nozzle(g) + sidePods(g, 12, black, 18) + g.add( + slab(black, -20, 20, -18, 20, 12, 70, 'body', 3), + slab(caution, -5, 5, -18.4, -18, 54, 61, 'caution'), + slab(steel, -9, 9, -18.4, -18, 64, 66, 'label'), + ) + frontFan(g, -18, 0, 34, 12) + return { group: g, sleeve: inlet(g, 70, 4), shadow: 22 } +} + +/** Elegoo Centauri Carbon: a black head with a gunmetal front, the round fan and the nozzle light under it. */ +function elegooCentauri(): BuiltHead { + const g = new Group() + nozzle(g) + sidePods(g, 10, black, 18) + g.add( + slab(black, -24, 24, -18, 24, 10, 72, 'body', 4), + slab(gunmetal, -24, 24, -22, -18, 12, 72, 'cover', 1.8), + slab(lightMat, -8, 8, -22.4, -22, 14, 15.5, 'light'), + slab(steel, -8, 8, -22.4, -22, 64, 66, 'label'), + ) + frontFan(g, -22, 0, 40, 13) + return { group: g, sleeve: inlet(g, 72, 4), shadow: 26 } +} + +/** Elegoo Neptune 4 family: an angular gray head with the hotend fan in front and a big blower on each side. */ +function neptune4(): BuiltHead { + const g = new Group() + nozzle(g) + g.add( + slab(gunmetal, -20, 20, -16, 22, 14, 66, 'body', 3), + slab(black, -32, -20, -14, 14, 10, 40, 'blower', 3), + slab(black, 20, 32, -14, 14, 10, 40, 'blower', 3), + slab(black, -24, -8, -12, 8, 4, 10, 'outlet', 1), + slab(black, 8, 24, -12, 8, 4, 10, 'outlet', 1), + slab(steel, -6, 6, -16.4, -16, 56, 59, 'logo'), + ) + frontFan(g, -16, 0, 38, 11) + return { group: g, sleeve: inlet(g, 66, 4), shadow: 26 } +} + +/** Anycubic Kobra 3 and Kobra X: a black head with a graphite front, the round fan and the white name on top. */ +function anycubic(): BuiltHead { + const g = new Group() + nozzle(g) + sidePods(g, 12, black, 17) + g.add(slab(black, -22, 22, -18, 22, 12, 70, 'body', 4), slab(graphite, -20, 20, -21, -18, 16, 56, 'front', 1.4), slab(white, -12, 12, -18.4, -18, 62, 64.5, 'label')) + frontFan(g, -21, 0, 36, 12) + return { group: g, sleeve: inlet(g, 70, 4), shadow: 24 } +} + +/** QIDI Q1 Pro and X-Plus 4: a black head with a slotted vent, the white name and a blower on the right. */ +function qidi(): BuiltHead { + const g = new Group() + nozzle(g) + sidePods(g, 12, black, 17) + g.add(slab(black, -22, 22, -18, 22, 12, 72, 'body', 4), slab(black, 22, 32, -14, 14, 16, 46, 'blower', 3), slab(white, -10, 10, -18.4, -18, 64, 66.5, 'label')) + for (let i = 0; i < 5; i++) g.add(slab(deep, -14, 14, -18.4, -18, 24 + i * 6, 27 + i * 6, 'vent')) + return { group: g, sleeve: inlet(g, 72, 4), shadow: 24 } +} + +/** Snapmaker A250, A350, Artisan: the 3D printing module, a black aluminium box with a brushed top band and the fan grille. */ +function snapmakerModule(): BuiltHead { + const g = new Group() + nozzle(g) + g.add(slab(black, -26, 26, -20, 24, 8, 66, 'body', 2.5), slab(silver, -26, 26, -20, 24, 66, 74, 'band', 1.5), slab(white, -10, 10, -20.4, -20, 58, 60.5, 'label')) + for (let i = 0; i < 6; i++) g.add(slab(deep, -14, 14, -20.4, -20, 16 + i * 6, 18.5 + i * 6, 'grille')) + return { group: g, sleeve: inlet(g, 74, 6), shadow: 28 } +} + +/** Every other printer: a tidy graphite head with a front fan, two cooling pods and the extruder on top. */ +function generic(): BuiltHead { + const g = new Group() + nozzle(g) + sidePods(g, 12, black, 17) + g.add(slab(graphite, -20, 20, -16, 20, 12, 60, 'body', 4), slab(black, -12, 12, -8, 16, 60, 72, 'extruder', 2)) + frontFan(g, -16, 0, 34, 11) + return { group: g, sleeve: inlet(g, 72, 4), shadow: 22 } +} + +/** The head for `model`. */ +export function buildHead(model: HeadModel): BuiltHead { + switch (model) { + case 'bambu-x1': + return bambuX1(true) + case 'bambu-p1': + return bambuX1(false) + case 'bambu-a1': + return bambuA1() + case 'bambu-h2s': + return bambuH2S() + case 'prusa-nextruder': + return nextruder() + case 'prusa-mini': + return prusaMini() + case 'voron-stealthburner': + return stealthburner(voronRed) + case 'sovol-sv08': + return stealthburner(sovolBlue) + case 'creality-k1': + return crealityK1() + case 'creality-k2': + return crealityK2() + case 'creality-ender3-v3': + return enderV3() + case 'creality-sprite': + return crealitySprite() + case 'elegoo-centauri': + return elegooCentauri() + case 'elegoo-neptune4': + return neptune4() + case 'anycubic-kobra': + return anycubic() + case 'qidi': + return qidi() + case 'snapmaker-module': + return snapmakerModule() + default: + return generic() + } +} diff --git a/desktop/src/vendor/slicerx/viewport/layerheights.ts b/desktop/src/vendor/slicerx/viewport/layerheights.ts new file mode 100644 index 00000000..8d7c8aa8 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/layerheights.ts @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// sleipnir heights as data: the tops of every layer (the shape core's +// options.layerTopsMm takes), checks on them, and the lookup the Prepare +// shaders repeat on the GPU. Pure, so the shader math is unit tested here. + +/** Problems in a list of layer tops, as readable strings. Empty means usable. */ +export function layerTopsProblems(tops: ArrayLike): string[] { + const out: string[] = [] + if (tops.length === 0) out.push('layer tops are empty') + let prev = 0 + for (let i = 0; i < tops.length; i++) { + const t = tops[i] ?? 0 + if (!Number.isFinite(t) || t <= prev) { + out.push(`layer ${i} top ${t} is not above the previous top ${prev}`) + break + } + prev = t + } + return out +} + +/** Thickness of each layer, mm. The first layer starts at the bed. */ +export function layerThicknesses(tops: ArrayLike): Float32Array { + const out = new Float32Array(tops.length) + let prev = 0 + for (let i = 0; i < tops.length; i++) { + const t = tops[i] ?? 0 + out[i] = t - prev + prev = t + } + return out +} + +export interface LayerHeightStats { + layers: number + minMm: number + maxMm: number + /** Height that the most layers have, rounded to 0.01 mm. */ + commonMm: number +} + +export function layerHeightStats(tops: ArrayLike): LayerHeightStats { + const th = layerThicknesses(tops) + let mn = Infinity + let mx = 0 + const counts = new Map() + for (const t of th) { + mn = Math.min(mn, t) + mx = Math.max(mx, t) + const k = Math.round(t * 100) / 100 + counts.set(k, (counts.get(k) ?? 0) + 1) + } + let common = 0 + let best = 0 + for (const [k, n] of counts) { + if (n > best) { + best = n + common = k + } + } + return { layers: th.length, minMm: Number.isFinite(mn) ? mn : 0, maxMm: mx, commonMm: common } +} + +/** + * Continuous layer coordinate at height `z`: the layer index plus how far + * through that layer z is. Below the bed it is 0; above the last top it stays + * at the last layer's end. This mirrors sxLayerAt in materials.ts. + */ +export function layerCoordAt(tops: ArrayLike, z: number): { coord: number; thicknessMm: number } { + const n = tops.length + if (n === 0) return { coord: 0, thicknessMm: 0 } + let lo = 0 + let hi = n - 1 + while (lo < hi) { + const mid = (lo + hi) >> 1 + if ((tops[mid] ?? 0) < z) lo = mid + 1 + else hi = mid + } + const t1 = tops[lo] ?? 0 + const t0 = lo > 0 ? (tops[lo - 1] ?? 0) : 0 + const th = Math.max(t1 - t0, 1e-4) + return { coord: lo + Math.min(1, Math.max(0, (z - t0) / th)), thicknessMm: t1 - t0 } +} diff --git a/desktop/src/vendor/slicerx/viewport/materials.ts b/desktop/src/vendor/slicerx/viewport/materials.ts new file mode 100644 index 00000000..53860e31 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/materials.ts @@ -0,0 +1,321 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Prepare materials: per-filament physical materials, clay, overhang heat map, +// X-ray and flat filament colors, plus the "print look" layer-groove shading +// ported from the concept renderer (LAYER_GLSL). +import { + Color, + CustomBlending, + DataTexture, + DoubleSide, + FloatType, + LineBasicMaterial, + Material, + MeshPhysicalMaterial, + MeshStandardMaterial, + NearestFilter, + OneFactor, + RedFormat, + ShaderMaterial, + SrcAlphaFactor, + ZeroFactor, + type WebGLProgramParametersWithUniforms, +} from 'three' +import { HEAT_RAMP, SCENE, displayHex, type SceneColors } from './palette' +import type { FilamentFinish, RenderMode } from './types' + +/** Uniforms shared by every Prepare material, so one write updates all of them. */ +export const shared = { + layerH: { value: 0.2 }, + gmin: { value: 4 }, + lines: { value: 1 }, + overhangDeg: { value: 55 }, + /** sleipnir: layer tops as a texture (4096 per row), their count, and the heat band settings. */ + tops: { value: new DataTexture(new Float32Array(1), 1, 1, RedFormat, FloatType) }, + topsN: { value: 0 }, + band: { value: 0 }, + bandRange: { value: [0.1, 0.3] as [number, number] }, + bandThin: { value: new Color(HEAT_RAMP[0]) }, + bandMid: { value: new Color(HEAT_RAMP[2]) }, + bandThick: { value: new Color(HEAT_RAMP[3]) }, + red: { value: new Color(SCENE.overhangRed) }, + amber: { value: new Color(SCENE.overhangAmber) }, +} + +/* + * Print look: FDM layer grooves. The line width follows fwidth, and when one + * layer is thinner than a few pixels the groove period steps up by octaves of + * the layer height, crossfaded, so the lines always read and never alias into + * moire. Valleys get a cavity darkening so they hold light like real beads. + */ +const LAYER_LOOKUP = /* glsl */ ` +uniform sampler2D uTops; +uniform float uTopsN; +uniform float uBand; +uniform vec2 uBandRange; +uniform vec3 uBandThin; +uniform vec3 uBandMid; +uniform vec3 uBandThick; +float sxTop(int i) { return texelFetch(uTops, ivec2(i % 4096, i / 4096), 0).r; } +// Layer index plus the fraction through the layer at height z (x), and that layer's thickness in mm (y). +vec2 sxLayerAt(float z) { + int lo = 0; + int hi = int(uTopsN) - 1; + for (int i = 0; i < 15; i++) { + if (lo >= hi) break; + int mid = (lo + hi) / 2; + if (sxTop(mid) < z) lo = mid + 1; else hi = mid; + } + float t1 = sxTop(lo); + float t0 = lo > 0 ? sxTop(lo - 1) : 0.0; + float th = max(t1 - t0, 1e-4); + return vec2(float(lo) + clamp((z - t0) / th, 0.0, 1.0), t1 - t0); +} +` + +const GROOVE_PRE = /* glsl */ ` +float sxTilt = 0.0; +{ + // With sleipnir heights the groove phase follows the real layer coordinate, scaled to uLayerH units. + vec2 sxL = uTopsN > 0.5 ? sxLayerAt(vSxW.y) : vec2(0.0); + float sxY = uTopsN > 0.5 ? sxL.x * uLayerH : vSxW.y; + if (uTopsN > 0.5 && uBand > 0.001) { + float k = clamp((sxL.y - uBandRange.x) / max(1e-4, uBandRange.y - uBandRange.x), 0.0, 1.0); + vec3 heat = k < 0.5 ? mix(uBandThin, uBandMid, k * 2.0) : mix(uBandMid, uBandThick, k * 2.0 - 1.0); + diffuseColor.rgb = mix(diffuseColor.rgb, heat, uBand); + } + float px = max(fwidth(sxY), 1e-5); + float L = max(0.0, log2(uGMin * px / uLayerH)); + float o = floor(L), f = fract(L); + float cav = 0.0, tilt = 0.0; + for (int k = 0; k < 2; k++) { + float per = uLayerH * exp2(o + float(k)); + float ph = fract(sxY / per); + float w = clamp(px / per * 1.5, 0.02, 0.5); + float edge = smoothstep(0.0, w, ph) * smoothstep(0.0, w, 1.0 - ph); + float t = (ph - 0.5) * 2.0 * edge; + float c = 1.0 - smoothstep(0.0, 0.5, min(ph, 1.0 - ph) + w * 0.5); + float wt = k == 0 ? 1.0 - f : f; + tilt += t * wt; cav += c * wt; + } + float far = 1.0 - smoothstep(4.0, 6.5, L); + float amp = uLines * far / (1.0 + 0.18 * o); + vec3 nW = normalize(cross(dFdx(vSxW), dFdy(vSxW))); + float side = 1.0 - abs(nW.y); side *= side; + sxTilt = tilt * amp * side; + diffuseColor.rgb *= 1.0 - cav * 0.42 * amp * side; +} +` + +const GROOVE_NORMAL = /* glsl */ ` +{ + vec3 upV = normalize((viewMatrix * vec4(0.0, 1.0, 0.0, 0.0)).xyz); + normal = normalize(normal + upV * sxTilt * 0.95); +} +` + +function addWorldPos(sh: WebGLProgramParametersWithUniforms): void { + sh.vertexShader = 'varying vec3 vSxW;\n' + sh.vertexShader.replace('#include ', '#include \n\tvSxW = (modelMatrix * vec4(transformed, 1.0)).xyz;') + sh.fragmentShader = 'varying vec3 vSxW;\n' + sh.fragmentShader +} + +function withLayerLines(m: M, key: string): M { + m.onBeforeCompile = (sh) => { + sh.uniforms.uLayerH = shared.layerH + sh.uniforms.uLines = shared.lines + sh.uniforms.uGMin = shared.gmin + sh.uniforms.uTops = shared.tops + sh.uniforms.uTopsN = shared.topsN + sh.uniforms.uBand = shared.band + sh.uniforms.uBandRange = shared.bandRange + sh.uniforms.uBandThin = shared.bandThin + sh.uniforms.uBandMid = shared.bandMid + sh.uniforms.uBandThick = shared.bandThick + addWorldPos(sh) + sh.fragmentShader = + 'uniform float uLayerH;\nuniform float uLines;\nuniform float uGMin;\n' + + LAYER_LOOKUP + + sh.fragmentShader + .replace('#include ', '#include \n' + GROOVE_PRE) + .replace('#include ', '#include \n' + GROOVE_NORMAL) + } + m.customProgramCacheKey = () => 'sx-layer-' + key + return m +} + +/** Adds color but leaves destination alpha alone, so the grade pass still sees the background as empty. */ +const ADDITIVE_KEEP_ALPHA = { blending: CustomBlending, blendSrc: OneFactor, blendDst: OneFactor, blendSrcAlpha: ZeroFactor, blendDstAlpha: OneFactor } as const + +function lin(hex: string): Color { + return new Color(hex) +} + +export function studioMaterial(color: string, finish: FilamentFinish): MeshPhysicalMaterial { + const c = lin(displayHex(color)) + const white = new Color(1, 1, 1) + const base = { + color: c, + polygonOffset: true, + sheenColor: c.clone().lerp(white, 0.45), + } + let m: MeshPhysicalMaterial + switch (finish) { + case 'silk': + m = new MeshPhysicalMaterial({ ...base, roughness: 0.26, metalness: 0.28, clearcoat: 1, clearcoatRoughness: 0.07, sheen: 0.9, sheenRoughness: 0.3, envMapIntensity: 1.25 }) + break + case 'matte': + m = new MeshPhysicalMaterial({ ...base, roughness: 0.82, metalness: 0, clearcoat: 0, sheen: 0.35, sheenRoughness: 0.7, envMapIntensity: 0.85 }) + break + case 'petg': + m = new MeshPhysicalMaterial({ ...base, roughness: 0.3, metalness: 0, clearcoat: 0.6, clearcoatRoughness: 0.12, sheen: 0.2, sheenRoughness: 0.4, envMapIntensity: 1.05 }) + break + case 'translucent': + m = new MeshPhysicalMaterial({ ...base, roughness: 0.28, metalness: 0, transmission: 0.55, thickness: 6, ior: 1.5, attenuationColor: c, attenuationDistance: 12, clearcoat: 0.3, clearcoatRoughness: 0.2, envMapIntensity: 1 }) + break + default: + m = new MeshPhysicalMaterial({ ...base, roughness: 0.52, metalness: 0, clearcoat: 0.16, clearcoatRoughness: 0.42, sheen: 0.3, sheenRoughness: 0.55, envMapIntensity: 0.95 }) + } + return withLayerLines(m, 'studio') +} + +export function filamentMaterial(color: string): MeshStandardMaterial { + const c = lin(displayHex(color)) + return new MeshStandardMaterial({ color: c, roughness: 0.92, metalness: 0, envMapIntensity: 0.55, emissive: c.clone().multiplyScalar(0.22), polygonOffset: true }) +} + +let xrayTint: string = SCENE.xrayTint + +export function xrayMaterial(color: string): ShaderMaterial { + const c = lin(displayHex(color)).lerp(lin(xrayTint), 0.35) + return new ShaderMaterial({ + uniforms: { col: { value: c } }, + vertexShader: 'varying vec3 vN; varying vec3 vV; void main(){ vec4 mv = modelViewMatrix * vec4(position, 1.0); vN = normalize(normalMatrix * normal); vV = normalize(-mv.xyz); gl_Position = projectionMatrix * mv; }', + fragmentShader: 'uniform vec3 col; varying vec3 vN; varying vec3 vV; void main(){ float f = pow(1.0 - abs(dot(normalize(vN), normalize(vV))), 2.4); gl_FragColor = vec4(col * (0.035 + f * 0.95), 1.0); }', + transparent: true, + depthWrite: false, + side: DoubleSide, + ...ADDITIVE_KEEP_ALPHA, + }) +} + +let sharedMats: { clay: MeshStandardMaterial; overhang: MeshStandardMaterial; edgeDark: LineBasicMaterial; edgeXray: LineBasicMaterial } | null = null + +/** Pulls line vertices a hair toward the camera so feature edges win the depth test against their own faces. */ +function edgeBias(m: M): M { + m.onBeforeCompile = (sh) => { + sh.vertexShader = sh.vertexShader.replace('#include ', '#include \n\tmvPosition.xyz *= 0.99935;\n\tgl_Position = projectionMatrix * mvPosition;') + } + m.customProgramCacheKey = () => 'sx-edge' + return m +} + +export function sharedMaterials(): NonNullable { + if (sharedMats) return sharedMats + const clay = withLayerLines(new MeshStandardMaterial({ color: lin(SCENE.clay), roughness: 0.74, metalness: 0, envMapIntensity: 0.85, polygonOffset: true }), 'clay') + const overhang = new MeshStandardMaterial({ color: lin(SCENE.overhangBase), roughness: 0.7, metalness: 0, flatShading: true, envMapIntensity: 0.8, polygonOffset: true }) + overhang.onBeforeCompile = (sh) => { + sh.uniforms.uTh = shared.overhangDeg + sh.uniforms.uRed = shared.red + sh.uniforms.uAmber = shared.amber + addWorldPos(sh) + sh.fragmentShader = + 'uniform float uTh;\nuniform vec3 uRed;\nuniform vec3 uAmber;\n' + + sh.fragmentShader.replace( + '#include ', + [ + '#include ', + 'vec3 fnw = normalize(cross(dFdx(vSxW), dFdy(vSxW)));', + 'float ang = degrees(asin(clamp(-fnw.y, 0.0, 1.0)));', + 'if (vSxW.y > 0.45) { if (ang > uTh) diffuseColor.rgb = uRed; else if (ang > uTh - 15.0) diffuseColor.rgb = uAmber; }', + ].join('\n'), + ) + } + overhang.customProgramCacheKey = () => 'sx-over' + const edgeDark = edgeBias(new LineBasicMaterial({ color: lin(SCENE.edgeDark), transparent: true, opacity: 0.22, depthWrite: false })) + const edgeXray = edgeBias(new LineBasicMaterial({ color: lin(SCENE.edgeXray), transparent: true, opacity: 0.5, depthWrite: false, ...ADDITIVE_KEEP_ALPHA, blendSrc: SrcAlphaFactor })) + sharedMats = { clay, overhang, edgeDark, edgeXray } + return sharedMats +} + +export interface PartLook { + color: string + finish: FilamentFinish +} + +/** Caches one material per (mode, color, finish) so switching modes never recompiles. */ +export class MaterialCache { + private readonly map = new Map() + + get(mode: RenderMode, look: PartLook): Material { + const s = sharedMaterials() + if (mode === 'clay') return s.clay + if (mode === 'overhang') return s.overhang + const key = `${mode}:${look.color}:${look.finish}` + let m = this.map.get(key) + if (!m) { + m = mode === 'xray' ? xrayMaterial(look.color) : mode === 'filament' ? filamentMaterial(look.color) : studioMaterial(look.color, look.finish) + this.map.set(key, m) + } + return m + } + + dispose(): void { + for (const m of this.map.values()) m.dispose() + this.map.clear() + } +} + +/** + * Applies scene colors to the materials every viewport on the page shares + * (clay, overhang heat map, edges). Cached per-color materials are dropped by + * MaterialCache.dispose(), so call that too when the x-ray tint changes. + */ +export function setSharedSceneColors(scene: SceneColors): void { + shared.red.value.set(scene.overhangRed) + shared.amber.value.set(scene.overhangAmber) + xrayTint = scene.xrayTint + if (!sharedMats) return + sharedMats.clay.color.copy(lin(scene.clay)) + sharedMats.overhang.color.copy(lin(scene.overhangBase)) + sharedMats.edgeDark.color.copy(lin(scene.edgeDark)) + sharedMats.edgeXray.color.copy(lin(scene.edgeXray)) +} + +/** sleipnir heights for the Prepare shaders. Null clears them. Shared by every viewport on the page. */ +export function setSharedLayerTops(tops: ArrayLike | null, band: boolean): void { + const old = shared.tops.value + if (!tops || tops.length === 0) { + shared.topsN.value = 0 + shared.band.value = 0 + return + } + const n = Math.min(tops.length, 4096 * 8) + const rows = Math.ceil(n / 4096) + const data = new Float32Array(4096 * rows) + let mn = Infinity + let mx = 0 + let prev = 0 + for (let i = 0; i < n; i++) { + const t = tops[i] ?? 0 + data[i] = t + mn = Math.min(mn, t - prev) + mx = Math.max(mx, t - prev) + prev = t + } + const tex = new DataTexture(data, 4096, rows, RedFormat, FloatType) + tex.minFilter = tex.magFilter = NearestFilter + tex.needsUpdate = true + shared.tops.value = tex + old.dispose() + shared.topsN.value = n + // Keep a visible span even when every layer is the same thickness. + shared.bandRange.value = mx - mn < 0.01 ? [Math.max(0, mn - 0.05), mx + 0.05] : [mn, mx] + shared.band.value = band ? 0.55 : 0 +} + +/** Colors of the thin, middle and thick ends of the heat band. */ +export function setSharedBandColors(thin: string, mid: string, thick: string): void { + shared.bandThin.value.set(thin) + shared.bandMid.value.set(mid) + shared.bandThick.value.set(thick) +} diff --git a/desktop/src/vendor/slicerx/viewport/model.ts b/desktop/src/vendor/slicerx/viewport/model.ts new file mode 100644 index 00000000..6b1ee5cb --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/model.ts @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Turns plate objects into scene meshes: creased normals so flat faces and +// pixel steps stay crisp, thin feature edges, and per-part polygon offset so +// coplanar faces between stacked color parts resolve the same way every frame. +import { + BufferAttribute, + BufferGeometry, + EdgesGeometry, + Group, + LineSegments, + Matrix4, + Mesh, + type Material, +} from 'three' +import type { FilamentFinish, ViewportObject, ViewportPart } from './types' + +const CREASE_DEG = 40 +const EDGE_DEG = 38 + +export interface PartEntry { + mesh: Mesh + edges: LineSegments + color: string + finish: FilamentFinish + index: number +} + +export interface ObjectEntry { + id: string + name: string + group: Group + parts: PartEntry[] +} + +/** Welds positions at 1 micrometer so normals and edges see shared vertices even in unindexed files. */ +function weld(pos: Float32Array): { map: Int32Array; count: number } { + const n = pos.length / 3 + const map = new Int32Array(n) + const seen = new Map() + let count = 0 + for (let i = 0; i < n; i++) { + const k = `${Math.round((pos[3 * i] ?? 0) * 1000)},${Math.round((pos[3 * i + 1] ?? 0) * 1000)},${Math.round((pos[3 * i + 2] ?? 0) * 1000)}` + let id = seen.get(k) + if (id === undefined) { + id = count++ + seen.set(k, id) + } + map[i] = id + } + return { map, count } +} + +/** Unindexed geometry whose normals average only faces within CREASE_DEG of each other. */ +export function creasedGeometry(P: Float32Array, I: ArrayLike): BufferGeometry { + const nt = Math.floor(I.length / 3) + const fn = new Float32Array(nt * 3) + const fu = new Float32Array(nt * 3) + const at = (k: number): number => I[k] ?? 0 + const p = (k: number): number => P[k] ?? 0 + for (let t = 0; t < nt; t++) { + const a = at(3 * t) * 3 + const b = at(3 * t + 1) * 3 + const c = at(3 * t + 2) * 3 + const ux = p(b) - p(a), uy = p(b + 1) - p(a + 1), uz = p(b + 2) - p(a + 2) + const vx = p(c) - p(a), vy = p(c + 1) - p(a + 1), vz = p(c + 2) - p(a + 2) + const x = uy * vz - uz * vy, y = uz * vx - ux * vz, z = ux * vy - uy * vx + const l = Math.hypot(x, y, z) || 1 + fu[3 * t] = x; fu[3 * t + 1] = y; fu[3 * t + 2] = z + fn[3 * t] = x / l; fn[3 * t + 1] = y / l; fn[3 * t + 2] = z / l + } + const { map: wmap, count: nw } = weld(P) + const w = (k: number): number => wmap[at(k)] ?? 0 + const cnt = new Int32Array(nw + 1) + for (let i = 0; i < nt * 3; i++) { + const c = w(i) + 1 + cnt[c] = (cnt[c] ?? 0) + 1 + } + for (let i = 0; i < nw; i++) cnt[i + 1] = (cnt[i + 1] ?? 0) + (cnt[i] ?? 0) + const fill = cnt.slice(0, nw) + const lst = new Int32Array(nt * 3) + for (let i = 0; i < nt * 3; i++) { + const c = w(i) + const slot = fill[c] ?? 0 + lst[slot] = (i / 3) | 0 + fill[c] = slot + 1 + } + const f = (k: number): number => fn[k] ?? 0 + const u = (k: number): number => fu[k] ?? 0 + const pos = new Float32Array(nt * 9) + const nrm = new Float32Array(nt * 9) + const cosA = Math.cos((CREASE_DEG * Math.PI) / 180) + for (let t = 0; t < nt; t++) { + const tx = f(3 * t), ty = f(3 * t + 1), tz = f(3 * t + 2) + for (let j = 0; j < 3; j++) { + const vi = at(3 * t + j) + const wi = w(3 * t + j) + const o = 9 * t + 3 * j + let x = 0, y = 0, z = 0 + const end = cnt[wi + 1] ?? 0 + for (let k = cnt[wi] ?? 0; k < end; k++) { + const g = lst[k] ?? 0 + if (f(3 * g) * tx + f(3 * g + 1) * ty + f(3 * g + 2) * tz >= cosA) { + x += u(3 * g); y += u(3 * g + 1); z += u(3 * g + 2) + } + } + const l = Math.hypot(x, y, z) || 1 + pos[o] = p(3 * vi); pos[o + 1] = p(3 * vi + 1); pos[o + 2] = p(3 * vi + 2) + nrm[o] = x / l; nrm[o + 1] = y / l; nrm[o + 2] = z / l + } + } + const out = new BufferGeometry() + out.setAttribute('position', new BufferAttribute(pos, 3)) + out.setAttribute('normal', new BufferAttribute(nrm, 3)) + out.computeBoundingBox() + out.computeBoundingSphere() + return out +} + +function edgeGeometry(part: ViewportPart): EdgesGeometry { + const g = new BufferGeometry() + g.setAttribute('position', new BufferAttribute(part.positions, 3)) + g.setIndex(new BufferAttribute(part.indices, 1)) + const e = new EdgesGeometry(g, EDGE_DEG) + g.dispose() + return e +} + +/** Later parts win coplanar ties, the same way every frame. */ +function partOffset(i: number): Mesh['onBeforeRender'] { + return (_r, _s, _c, _g, mat) => { + const m = mat as Material + if (m.polygonOffset) { + m.polygonOffsetFactor = -0.12 * i + m.polygonOffsetUnits = -4 * i + } + } +} + +export function buildObject(obj: ViewportObject, material: (p: ViewportPart) => Material, edgeMaterial: Material): ObjectEntry { + const group = new Group() + group.name = obj.name + group.userData.objectId = obj.id + group.matrixAutoUpdate = false + group.matrix.copy(new Matrix4().fromArray(obj.transform)) + const parts: PartEntry[] = obj.parts.map((p, i) => { + const mesh = new Mesh(creasedGeometry(p.positions, p.indices), material(p)) + mesh.castShadow = true + mesh.receiveShadow = true + mesh.userData.objectId = obj.id + mesh.userData.partIndex = i + // Kept for the lay-on-face tool: triangle t of the creased geometry is triangle t of these. + mesh.userData.source = { positions: p.positions, indices: p.indices } + mesh.onBeforeRender = partOffset(i) + const edges = new LineSegments(edgeGeometry(p), edgeMaterial) + edges.raycast = () => {} + mesh.add(edges) + group.add(mesh) + return { mesh, edges, color: p.color, finish: p.finish ?? 'basic', index: i } + }) + return { id: obj.id, name: obj.name, group, parts } +} + +export function disposeObject(o: ObjectEntry): void { + for (const p of o.parts) { + p.mesh.geometry.dispose() + p.edges.geometry.dispose() + } + o.group.removeFromParent() +} diff --git a/desktop/src/vendor/slicerx/viewport/paint.ts b/desktop/src/vendor/slicerx/viewport/paint.ts new file mode 100644 index 00000000..ecfa8be6 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/paint.ts @@ -0,0 +1,793 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Painted triangles. One text per triangle in the format Bambu Studio and +// OrcaSlicer write to 3MF (`paint_color`, `paint_seam`, `paint_supports`): +// a stream of 4-bit codes, written last code first. A code is a leaf (bits 0 +// and 1 are 0; the state sits in bits 2 and 3, or both set and the next code +// plus 3) or a split (bits 0 and 1 count the split sides, bits 2 and 3 name +// the special corner) followed by its children. The child layout matches +// sx-core's reader (packages/core/src/paint.rs), which was fitted to +// OrcaSlicer. Pure math, no three.js. + +export type V3 = [number, number, number] +export type Tri = [V3, V3, V3] + +/** A leaf, or a split into two to four children in the order sx-core reads them. */ +export type PaintNode = { state: number } | { splits: 1 | 2 | 3; special: 0 | 1 | 2; kids: PaintNode[] } + +export const isLeaf = (n: PaintNode): n is { state: number } => 'state' in n + +/** Deepest nesting written or read. */ +export const MAX_PAINT_DEPTH = 12 + +const mid = (a: V3, b: V3): V3 => [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2] + +/** Corners of each child of a split, already rotated the way the child's own codes expect. */ +export function childCorners(v: Tri, splits: 1 | 2 | 3, special: 0 | 1 | 2): Tri[] { + const p: Tri = [v[special], v[(special + 1) % 3] as V3, v[(special + 2) % 3] as V3] + const mA = mid(p[0], p[1]) + const mB = mid(p[2], p[0]) + const mC = mid(p[1], p[2]) + const rot = (c: Tri, k: number): Tri => (k === 0 ? c : ([c[1], c[2], c[0]] as Tri)) + if (splits === 1) return [rot([p[0], mC, p[2]], 1), [p[0], p[1], mC]] + if (splits === 2) return [rot([mB, p[1], p[2]], 1), [mA, p[1], mB], [p[0], mA, mB]] + return [[mA, mC, mB], rot([mB, mC, p[2]], 1), [mA, p[1], mC], [p[0], mA, mB]] +} + +// ---- text <-> tree ---- + +function nibbles(text: string): number[] | null { + const out: number[] = [] + const s = text.trim() + for (let i = s.length - 1; i >= 0; i--) { + const d = Number.parseInt(s[i] as string, 16) + if (Number.isNaN(d)) return null + out.push(d) + } + return out +} + +/** Parses a paint text. Null when it is malformed or nests too deep. Trailing codes are ignored, as sx-core does. */ +export function decodeTree(text: string): PaintNode | null { + const stream = nibbles(text) + if (!stream || stream.length === 0) return null + let at = 0 + const node = (depth: number): PaintNode | null => { + const code = stream[at++] + if (code === undefined) return null + const splits = code & 3 + const special = code >> 2 + if (splits === 0) { + if (special === 3) { + const ext = stream[at++] + return ext === undefined ? null : { state: ext + 3 } + } + return { state: special } + } + if (depth >= MAX_PAINT_DEPTH || special > 2) return null + const count = splits + 1 + const kids: PaintNode[] = [] + for (let i = 0; i < count; i++) { + const k = node(depth + 1) + if (!k) return null + kids.push(k) + } + return { splits: splits as 1 | 2 | 3, special: special as 0 | 1 | 2, kids } + } + return node(0) +} + +/** Writes a tree as paint text. A single unpainted leaf gives null: write no attribute. */ +export function encodeTree(root: PaintNode): string | null { + if (isLeaf(root) && root.state === 0) return null + const out: number[] = [] + const walk = (n: PaintNode): void => { + if (isLeaf(n)) { + if (n.state < 3) out.push(n.state << 2) + else { + out.push(0b1100) + out.push(n.state - 3) + } + return + } + out.push((n.special << 2) | n.splits) + for (const k of n.kids) walk(k) + } + walk(root) + return out + .reverse() + .map((d) => d.toString(16).toUpperCase()) + .join('') +} + +// ---- geometry of a tree ---- + +export interface PaintLeaf { + v: Tri + state: number +} + +/** Every leaf piece of a triangle with its state, unpainted pieces included. */ +export function leavesOf(tri: Tri, node: PaintNode, out: PaintLeaf[] = []): PaintLeaf[] { + if (isLeaf(node)) { + out.push({ v: tri, state: node.state }) + return out + } + const cs = childCorners(tri, node.splits, node.special) + node.kids.forEach((k, i) => leavesOf(cs[i] as Tri, k, out)) + return out +} + +/** Merges children that are all leaves of one state, so strokes do not grow the text for nothing. */ +export function simplify(node: PaintNode): PaintNode { + if (isLeaf(node)) return node + const kids = node.kids.map(simplify) + const first = kids[0] + if (first && isLeaf(first) && kids.every((k) => isLeaf(k) && k.state === first.state)) return { state: first.state } + return { ...node, kids } +} + +// ---- regions ---- + +/** A volume or slab to paint, in the mesh's own frame. */ +export interface PaintRegion { + /** `inside`: the whole triangle is in the region. `outside`: none of it. Otherwise `partial`. */ + classify(tri: Tri): 'inside' | 'outside' | 'partial' + contains(p: V3): boolean +} + +const sub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +const dot = (a: V3, b: V3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + +/** Closest point of triangle abc to p (Ericson, Real-Time Collision Detection). */ +export function closestPointOnTriangle(p: V3, a: V3, b: V3, c: V3): V3 { + const ab = sub(b, a), ac = sub(c, a), ap = sub(p, a) + const d1 = dot(ab, ap), d2 = dot(ac, ap) + if (d1 <= 0 && d2 <= 0) return a + const bp = sub(p, b) + const d3 = dot(ab, bp), d4 = dot(ac, bp) + if (d3 >= 0 && d4 <= d3) return b + const vc = d1 * d4 - d3 * d2 + if (vc <= 0 && d1 >= 0 && d3 <= 0) { + const v = d1 / (d1 - d3) + return [a[0] + v * ab[0], a[1] + v * ab[1], a[2] + v * ab[2]] + } + const cp = sub(p, c) + const d5 = dot(ab, cp), d6 = dot(ac, cp) + if (d6 >= 0 && d5 <= d6) return c + const vb = d5 * d2 - d1 * d6 + if (vb <= 0 && d2 >= 0 && d6 <= 0) { + const w = d2 / (d2 - d6) + return [a[0] + w * ac[0], a[1] + w * ac[1], a[2] + w * ac[2]] + } + const va = d3 * d6 - d5 * d4 + if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) { + const w = (d4 - d3) / (d4 - d3 + (d5 - d6)) + return [b[0] + w * (c[0] - b[0]), b[1] + w * (c[1] - b[1]), b[2] + w * (c[2] - b[2])] + } + const denom = 1 / (va + vb + vc) + const v = vb * denom, w = vc * denom + return [a[0] + ab[0] * v + ac[0] * w, a[1] + ab[1] * v + ac[1] * w, a[2] + ab[2] * v + ac[2] * w] +} + +/** Sphere brush. */ +export function sphereRegion(center: V3, radius: number): PaintRegion { + const r2 = radius * radius + const d2 = (p: V3): number => { + const d = sub(p, center) + return dot(d, d) + } + return { + classify(t) { + if (d2(t[0]) <= r2 && d2(t[1]) <= r2 && d2(t[2]) <= r2) return 'inside' + return d2(closestPointOnTriangle(center, t[0], t[1], t[2])) > r2 ? 'outside' : 'partial' + }, + contains: (p) => d2(p) <= r2, + } +} + +/** + * Circle brush: an infinite cylinder of `radius` around the line through `origin` along `dir` + * (the view direction). With `frontOnly`, triangles facing away from the viewer are left alone. + */ +export function cylinderRegion(origin: V3, dir: V3, radius: number, frontOnly = false): PaintRegion { + const l = Math.hypot(dir[0], dir[1], dir[2]) || 1 + const d: V3 = [dir[0] / l, dir[1] / l, dir[2] / l] + const r2 = radius * radius + const flat = (p: V3): V3 => { + const q = sub(p, origin) + const k = dot(q, d) + return [q[0] - k * d[0], q[1] - k * d[1], q[2] - k * d[2]] + } + const zero: V3 = [0, 0, 0] + const facing = (t: Tri): boolean => { + const n = cross(sub(t[1], t[0]), sub(t[2], t[0])) + return dot(n, d) < 0 + } + return { + classify(t) { + if (frontOnly && !facing(t)) return 'outside' + const a = flat(t[0]), b = flat(t[1]), c = flat(t[2]) + if (dot(a, a) <= r2 && dot(b, b) <= r2 && dot(c, c) <= r2) return 'inside' + const cp = closestPointOnTriangle(zero, a, b, c) + return dot(cp, cp) > r2 ? 'outside' : 'partial' + }, + contains(p) { + const q = flat(p) + return dot(q, q) <= r2 + }, + } +} + +function cross(a: V3, b: V3): V3 { + return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +/** Height range: points with `lo <= up . p <= hi`, where `up` is the world up direction in the mesh frame. */ +export function slabRegion(up: V3, lo: number, hi: number): PaintRegion { + const l = Math.hypot(up[0], up[1], up[2]) || 1 + const n: V3 = [up[0] / l, up[1] / l, up[2] / l] + return { + classify(t) { + const h = [dot(n, t[0]), dot(n, t[1]), dot(n, t[2])] + const mn = Math.min(...h), mx = Math.max(...h) + if (mn >= lo && mx <= hi) return 'inside' + return mx < lo || mn > hi ? 'outside' : 'partial' + }, + contains: (p) => { + const h = dot(n, p) + return h >= lo && h <= hi + }, + } +} + +/** + * Limits a region to points that pass `allowed` (the clipping plane of the painter: what Orca skips is not painted). A + * triangle with no allowed sample point (corners and center) is outside, one with only some is partial. + */ +export function withPointFilter(region: PaintRegion, allowed: (p: V3) => boolean): PaintRegion { + return { + classify(t) { + const base = region.classify(t) + if (base === 'outside') return 'outside' + const c: V3 = [(t[0][0] + t[1][0] + t[2][0]) / 3, (t[0][1] + t[1][1] + t[2][1]) / 3, (t[0][2] + t[1][2] + t[2][2]) / 3] + let n = 0 + for (const p of [t[0], t[1], t[2], c]) if (allowed(p)) n++ + if (n === 0) return 'outside' + return n === 4 ? base : 'partial' + }, + contains: (p) => region.contains(p) && allowed(p), + } +} + +// ---- painting a triangle ---- + +export interface BrushOptions { + /** Longest edge a piece may have before a stroke stops splitting it, in mm. Smaller paints finer detail. */ + minEdge: number + /** Splitting off. Whole triangles are painted when their center is inside the region. */ + noSplit?: boolean +} + +const edge = (t: Tri): number => Math.max(Math.hypot(...sub(t[0], t[1])), Math.hypot(...sub(t[1], t[2])), Math.hypot(...sub(t[2], t[0]))) +const centroid = (t: Tri): V3 => [(t[0][0] + t[1][0] + t[2][0]) / 3, (t[0][1] + t[1][1] + t[2][1]) / 3, (t[0][2] + t[1][2] + t[2][2]) / 3] + +/** + * Paints `state` into the part of a triangle inside `region`, splitting pieces the region cuts + * until they are no longer than `minEdge`. State 0 erases. Returns the new tree (simplified), or + * the same node when nothing changed. + */ +export function paintTriangle(tri: Tri, node: PaintNode, region: PaintRegion, state: number, opts: BrushOptions): PaintNode { + const out = paintNode(tri, node, region, state, opts, 0) + return out === node ? node : simplify(out) +} + +function paintNode(tri: Tri, node: PaintNode, region: PaintRegion, state: number, opts: BrushOptions, depth: number): PaintNode { + if (!isLeaf(node)) { + const cs = childCorners(tri, node.splits, node.special) + let changed = false + const kids = node.kids.map((k, i) => { + const nk = paintNode(cs[i] as Tri, k, region, state, opts, depth + 1) + if (nk !== k) changed = true + return nk + }) + return changed ? { ...node, kids } : node + } + const c = region.classify(tri) + if (c === 'outside') return node + if (c === 'inside') return node.state === state ? node : { state } + // Partial: split while the piece is larger than the brush resolution, else decide by its center. + if (!opts.noSplit && depth < MAX_PAINT_DEPTH - 1 && edge(tri) > opts.minEdge) { + const split: PaintNode = { splits: 3, special: 0, kids: [{ state: node.state }, { state: node.state }, { state: node.state }, { state: node.state }] } + return paintNode(tri, split, region, state, opts, depth) + } + if (!region.contains(centroid(tri))) return node + return node.state === state ? node : { state } +} + +/** Replaces the state of every leaf that has `from` with `to`. Used by fill. */ +export function replaceState(node: PaintNode, from: number, to: number): PaintNode { + if (isLeaf(node)) return node.state === from ? { state: to } : node + let changed = false + const kids = node.kids.map((k) => { + const nk = replaceState(k, from, to) + if (nk !== k) changed = true + return nk + }) + return changed ? simplify({ ...node, kids }) : node +} + +/** True when some leaf has this state. */ +export function hasState(node: PaintNode, state: number): boolean { + return isLeaf(node) ? node.state === state : node.kids.some((k) => hasState(k, state)) +} + +/** The state of the leaf that contains point `p` (nearest leaf when p is off the triangle). */ +export function stateAt(tri: Tri, node: PaintNode, p: V3): number { + if (isLeaf(node)) return node.state + const cs = childCorners(tri, node.splits, node.special) + let best = 0 + let bestD = Infinity + cs.forEach((c, i) => { + const q = closestPointOnTriangle(p, c[0], c[1], c[2]) + const d = dot(sub(q, p), sub(q, p)) + if (d < bestD) { + bestD = d + best = i + } + }) + return stateAt(cs[best] as Tri, node.kids[best] as PaintNode, p) +} + +import { adjacencyOf } from './faces' + +// ---- mesh level ---- + +/** Painted triangles of one part and one kind of paint (color, seam, supports), by triangle index. */ +export type PaintMap = Map + +export function trianglePoints(positions: ArrayLike, indices: ArrayLike, t: number): Tri { + const p = (k: number): V3 => { + const i = 3 * (indices[3 * t + k] ?? 0) + return [positions[i] ?? 0, positions[i + 1] ?? 0, positions[i + 2] ?? 0] + } + return [p(0), p(1), p(2)] +} + +/** Text per painted triangle, ready for the 3MF writer. Unpainted triangles are left out. */ +export function paintTexts(map: PaintMap): Record { + const out: Record = {} + for (const [t, n] of map) { + const s = encodeTree(n) + if (s) out[t] = s + } + return out +} + +/** Reads texts from a 3MF reader. Malformed entries are skipped and listed in `bad`. */ +export function readPaintTexts(texts: Record): { map: PaintMap; bad: number[] } { + const map: PaintMap = new Map() + const bad: number[] = [] + for (const [k, text] of Object.entries(texts)) { + const t = Number(k) + const n = decodeTree(text) + if (!n) bad.push(t) + else if (!(isLeaf(n) && n.state === 0)) map.set(t, n) + } + return { map, bad } +} + +export interface PaintMesh { + positions: ArrayLike + indices: ArrayLike +} + +const gridCache = new WeakMap() + +/** Uniform grid over triangle bounding boxes, so a brush looks at nearby triangles only. */ +export class TriangleGrid { + private readonly cell: number + private readonly min: V3 + private readonly dims: [number, number, number] + private readonly bins = new Map() + + constructor(mesh: PaintMesh) { + const n = Math.floor(mesh.indices.length / 3) + const lo: V3 = [Infinity, Infinity, Infinity] + const hi: V3 = [-Infinity, -Infinity, -Infinity] + for (let i = 0; i < mesh.positions.length; i += 3) { + for (let a = 0; a < 3; a++) { + const v = mesh.positions[i + a] ?? 0 + if (v < lo[a]!) lo[a] = v + if (v > hi[a]!) hi[a] = v + } + } + if (!Number.isFinite(lo[0])) { + lo.fill(0) + hi.fill(1) + } + const diag = Math.hypot(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]) || 1 + // About 40 cells along the diagonal, fewer when the mesh is small. + this.cell = Math.max(diag / 40, 1e-3) + this.min = lo + this.dims = [Math.ceil((hi[0] - lo[0]) / this.cell) + 1, Math.ceil((hi[1] - lo[1]) / this.cell) + 1, Math.ceil((hi[2] - lo[2]) / this.cell) + 1] + for (let t = 0; t < n; t++) { + const tri = trianglePoints(mesh.positions, mesh.indices, t) + const [a0, b0] = this.range(tri, 0) + const [a1, b1] = this.range(tri, 1) + const [a2, b2] = this.range(tri, 2) + for (let x = a0; x <= b0; x++) for (let y = a1; y <= b1; y++) for (let z = a2; z <= b2; z++) { + const k = this.key(x, y, z) + const list = this.bins.get(k) + if (list) list.push(t) + else this.bins.set(k, [t]) + } + } + } + + private key(x: number, y: number, z: number): number { + return (z * this.dims[1] + y) * this.dims[0] + x + } + + private range(tri: Tri, a: number): [number, number] { + const v = [tri[0][a] as number, tri[1][a] as number, tri[2][a] as number] + const lo = Math.floor((Math.min(...v) - this.min[a]!) / this.cell) + const hi = Math.floor((Math.max(...v) - this.min[a]!) / this.cell) + return [Math.max(0, lo), Math.min(this.dims[a]! - 1, hi)] + } + + /** Triangles whose boxes touch the box lo..hi (superset of those inside it). */ + query(lo: V3, hi: V3): number[] { + const r = (a: number): [number, number] => [ + Math.max(0, Math.floor((lo[a]! - this.min[a]!) / this.cell)), + Math.min(this.dims[a]! - 1, Math.floor((hi[a]! - this.min[a]!) / this.cell)), + ] + const [a0, b0] = r(0) + const [a1, b1] = r(1) + const [a2, b2] = r(2) + const seen = new Set() + for (let x = a0; x <= b0; x++) for (let y = a1; y <= b1; y++) for (let z = a2; z <= b2; z++) { + for (const t of this.bins.get(this.key(x, y, z)) ?? []) seen.add(t) + } + return [...seen] + } +} + +export function gridFor(mesh: PaintMesh): TriangleGrid { + let g = gridCache.get(mesh.indices as object) + if (!g) { + g = new TriangleGrid(mesh) + gridCache.set(mesh.indices as object, g) + } + return g +} + +const UNPAINTED: PaintNode = { state: 0 } + +function faceNormal(mesh: PaintMesh, t: number): V3 { + const tri = trianglePoints(mesh.positions, mesh.indices, t) + const n = cross(sub(tri[1], tri[0]), sub(tri[2], tri[0])) + const l = Math.hypot(n[0], n[1], n[2]) || 1 + return [n[0] / l, n[1] / l, n[2] / l] +} + +/** + * One brush dab the way OrcaSlicer's `select_patch` does it: start at the triangle under the pointer + * and spread to neighbors that face the viewer (`normal . dir < 0`, `dir` from the camera to the hit), + * painting every triangle the region touches and continuing only through those. Nothing is painted + * behind a thin wall or on a disconnected surface, and no depth buffer is involved. The start triangle + * is taken whatever way it faces. Returns the indexes of the triangles that changed. + */ +export function paintPatch(mesh: PaintMesh, map: PaintMap, start: number, region: PaintRegion, state: number, opts: BrushOptions, dir: V3, record?: PaintRecorder, gate?: (triangle: number) => boolean): number[] { + const adj = adjacencyOf(mesh.positions, mesh.indices) + const changed: number[] = [] + const visited = new Set() + const queue = [start] + for (let i = 0; i < queue.length; i++) { + const t = queue[i] as number + if (visited.has(t)) continue + visited.add(t) + // Overhang-only painting: a triangle the gate refuses is left alone and nothing spreads through it. + if (gate && !gate(t)) continue + const tri = trianglePoints(mesh.positions, mesh.indices, t) + if (region.classify(tri) === 'outside') continue + const before = map.get(t) ?? UNPAINTED + const after = paintTriangle(tri, before, region, state, opts) + if (after !== before) { + record?.(t, map.get(t)) + if (isLeaf(after) && after.state === 0) map.delete(t) + else map.set(t, after) + changed.push(t) + } + for (let e = 0; e < 3; e++) { + const o = adj[3 * t + e] ?? -1 + if (o >= 0 && !visited.has(o) && dot(faceNormal(mesh, o), dir) < 0) queue.push(o) + } + } + return changed +} + +/** Orca's edge limit for a brush of this radius: `min(radius / 5, 0.05)` mm. */ +export function autoDetail(radiusMm: number): number { + return Math.min(radiusMm / 5, 0.05) +} + +/** Sets the leaf piece that holds point `p` to `state` (the pointer tool: one piece at a time). */ +export function paintLeafAt(tri: Tri, node: PaintNode, p: V3, state: number): PaintNode { + if (isLeaf(node)) return node.state === state ? node : { state } + const cs = childCorners(tri, node.splits, node.special) + let best = 0 + let bestD = Infinity + cs.forEach((c, i) => { + const q = closestPointOnTriangle(p, c[0], c[1], c[2]) + const d = dot(sub(q, p), sub(q, p)) + if (d < bestD) { + bestD = d + best = i + } + }) + const kid = paintLeafAt(cs[best] as Tri, node.kids[best] as PaintNode, p, state) + if (kid === node.kids[best]) return node + const kids = node.kids.slice() + kids[best] = kid + return simplify({ ...node, kids }) +} + +/** + * One brush dab: paints `state` in `region` on the triangles near `bounds`. + * Returns the indexes of the triangles that changed. The map is updated in place. + */ +export type PaintRecorder = (triangle: number, before: PaintNode | undefined) => void + +export function paintDab(mesh: PaintMesh, map: PaintMap, bounds: [V3, V3], region: PaintRegion, state: number, opts: BrushOptions, record?: PaintRecorder): number[] { + const changed: number[] = [] + for (const t of gridFor(mesh).query(bounds[0], bounds[1])) { + const tri = trianglePoints(mesh.positions, mesh.indices, t) + const before = map.get(t) ?? UNPAINTED + const after = paintTriangle(tri, before, region, state, opts) + if (after === before) continue + record?.(t, map.get(t)) + if (isLeaf(after) && after.state === 0) map.delete(t) + else map.set(t, after) + changed.push(t) + } + return changed +} + +/** + * Bucket fill (Orca's `bucket_fill_select_triangles`): every leaf that has the state under the seed point, in triangles connected to the + * seed through shared edges, takes `state`. Pieces inside split triangles are matched by leaf, so + * a fill stops at painted borders inside a triangle. Returns the changed triangle indexes. + */ +export function fillConnected(mesh: PaintMesh, map: PaintMap, seed: number, seedPoint: V3, state: number, angleDeg = -1, record?: PaintRecorder): number[] { + const adj = adjacencyOf(mesh.positions, mesh.indices) + const seedNode = map.get(seed) ?? UNPAINTED + const target = stateAt(trianglePoints(mesh.positions, mesh.indices, seed), seedNode, seedPoint) + if (target === state) return [] + const limit = angleDeg < 0 ? -1 : Math.cos((angleDeg * Math.PI) / 180) - 1e-6 + const seen = new Set([seed]) + const queue = [seed] + const changed: number[] = [] + while (queue.length) { + const t = queue.pop() as number + const before = map.get(t) ?? UNPAINTED + if (!hasState(before, target)) continue + const after = replaceState(before, target, state) + if (after !== before) { + record?.(t, map.get(t)) + if (isLeaf(after) && after.state === 0) map.delete(t) + else map.set(t, after) + changed.push(t) + } + for (let e = 0; e < 3; e++) { + const o = adj[3 * t + e] ?? -1 + if (o >= 0 && !seen.has(o)) { + seen.add(o) + if (limit < 0 || Math.min(1, Math.max(0, dot(faceNormal(mesh, t), faceNormal(mesh, o)))) >= limit) queue.push(o) + } + } + } + return changed +} + +/** + * Smart fill: whole triangles connected to the seed while the bend between neighbors stays within + * `angleDeg` (Orca measures it as the dot product of neighbor normals clamped to 0 to 1; a negative + * angle removes the limit). The seed triangle is always painted. Returns the changed triangle indexes. + */ +export function fillByAngle(mesh: PaintMesh, map: PaintMap, seed: number, state: number, angleDeg: number, record?: PaintRecorder, gate?: (triangle: number) => boolean): number[] { + const adj = adjacencyOf(mesh.positions, mesh.indices) + const normal = (t: number): V3 => { + const tri = trianglePoints(mesh.positions, mesh.indices, t) + const n = cross(sub(tri[1], tri[0]), sub(tri[2], tri[0])) + const l = Math.hypot(n[0], n[1], n[2]) || 1 + return [n[0] / l, n[1] / l, n[2] / l] + } + const cos = angleDeg < 0 ? -1 : Math.cos((angleDeg * Math.PI) / 180) - 1e-6 + const seen = new Set([seed]) + const queue = [seed] + const changed: number[] = [] + while (queue.length) { + const t = queue.pop() as number + if (gate && !gate(t)) continue + const before = map.get(t) ?? UNPAINTED + if (!(isLeaf(before) && before.state === state)) { + record?.(t, map.get(t)) + if (state === 0) map.delete(t) + else map.set(t, { state }) + changed.push(t) + } + const n = normal(t) + for (let e = 0; e < 3; e++) { + const o = adj[3 * t + e] ?? -1 + if (o >= 0 && !seen.has(o)) { + seen.add(o) + if (Math.min(1, Math.max(0, dot(n, normal(o)))) >= cos) queue.push(o) + } + } + } + return changed +} + +/** Every leaf with state `from` becomes `to` in the triangles `allowed` accepts (PrusaSlicer's color replace). Returns the changed triangles. */ +export function replaceEverywhere(mesh: PaintMesh, map: PaintMap, from: number, to: number, allowed?: (triangle: number) => boolean, record?: PaintRecorder): number[] { + const changed: number[] = [] + const n = Math.floor(mesh.indices.length / 3) + if (from === 0) { + // Unpainted triangles are not in the map: paint those the filter allows. + for (let t = 0; t < n; t++) { + if (map.has(t) || (allowed && !allowed(t))) continue + record?.(t, undefined) + if (to !== 0) map.set(t, { state: to }) + changed.push(t) + } + } + for (const [t, node] of [...map]) { + if (allowed && !allowed(t)) continue + if (!hasState(node, from)) continue + const after = replaceState(node, from, to) + if (after === node) continue + record?.(t, node) + if (isLeaf(after) && after.state === 0) map.delete(t) + else map.set(t, after) + changed.push(t) + } + return changed +} + +function setLeaves(tri: Tri, node: PaintNode, next: (leaf: PaintLeaf, index: number) => number, counter: { i: number }): PaintNode { + if (isLeaf(node)) { + const i = counter.i++ + const s = next({ v: tri, state: node.state }, i) + return s === node.state ? node : { state: s } + } + const cs = childCorners(tri, node.splits, node.special) + let changed = false + const kids = node.kids.map((k, j) => { + const nk = setLeaves(cs[j] as Tri, k, next, counter) + if (nk !== k) changed = true + return nk + }) + return changed ? { ...node, kids } : node +} + +const triArea = (t: Tri): number => { + const c = cross(sub(t[1], t[0]), sub(t[2], t[0])) + return Math.hypot(c[0], c[1], c[2]) / 2 +} + +/** + * Gap fill as in Orca and Bambu Studio: patches (connected pieces of one state) whose area is under `areaMm2` take the + * state of a neighboring patch (the lowest state number, as Orca's ordered set does, so a patch next to unpainted surface + * becomes unpainted). Pieces touch when they share an edge or lie on the same edge of the original mesh, which also joins + * pieces on both sides of a split triangle's T-junction. Returns the changed triangles. + */ +export function gapFill(mesh: PaintMesh, map: PaintMap, areaMm2: number, record?: PaintRecorder): number[] { + if (areaMm2 <= 0) return [] + const n = Math.floor(mesh.indices.length / 3) + const q = (p: V3): string => `${Math.round(p[0] * 1000)},${Math.round(p[1] * 1000)},${Math.round(p[2] * 1000)}` + const segKey = (a: V3, b: V3): string => { + const ka = q(a) + const kb = q(b) + return ka < kb ? `${ka}|${kb}` : `${kb}|${ka}` + } + const onSegment = (p: V3, a: V3, b: V3): boolean => { + const ab = sub(b, a) + const l2 = dot(ab, ab) + if (l2 === 0) return false + const t = Math.max(0, Math.min(1, dot(sub(p, a), ab) / l2)) + const c: V3 = [a[0] + t * ab[0], a[1] + t * ab[1], a[2] + t * ab[2]] + const d = sub(p, c) + return dot(d, d) < 1e-8 + } + interface Piece { tri: number; index: number; state: number; area: number } + const pieces: Piece[] = [] + const groups = new Map() + const add = (k: string, id: number): void => { + const g = groups.get(k) + if (g) g.push(id) + else groups.set(k, [id]) + } + for (let t = 0; t < n; t++) { + const orig = trianglePoints(mesh.positions, mesh.indices, t) + const node = map.get(t) ?? UNPAINTED + const leaves = leavesOf(orig, node) + leaves.forEach((leaf, index) => { + const id = pieces.length + pieces.push({ tri: t, index, state: leaf.state, area: triArea(leaf.v) }) + for (let e = 0; e < 3; e++) { + const a = leaf.v[e] as V3 + const b = leaf.v[(e + 1) % 3] as V3 + add(`s:${segKey(a, b)}`, id) + for (let oe = 0; oe < 3; oe++) { + const pa = orig[oe] as V3 + const pb = orig[(oe + 1) % 3] as V3 + if (onSegment(a, pa, pb) && onSegment(b, pa, pb)) add(`o:${segKey(pa, pb)}`, id) + } + } + }) + } + // Patches: connected pieces of one state. + const patch = new Int32Array(pieces.length).fill(-1) + const neighbors: Set[] = pieces.map(() => new Set()) + for (const [key, g] of groups) { + const orig = key.startsWith('o:') + for (let i = 0; i < g.length; i++) { + for (let j = i + 1; j < g.length; j++) { + const a = g[i] as number + const b = g[j] as number + // Pieces of one triangle along its original edge are not neighbors through that edge; shared segments join them. + if (orig && (pieces[a] as Piece).tri === (pieces[b] as Piece).tri) continue + neighbors[a]?.add(b) + neighbors[b]?.add(a) + } + } + } + const patches: { members: number[]; state: number; area: number; touching: Set }[] = [] + for (let i = 0; i < pieces.length; i++) { + if (patch[i] !== -1) continue + const p = { members: [] as number[], state: (pieces[i] as Piece).state, area: 0, touching: new Set() } + const stack = [i] + patch[i] = patches.length + while (stack.length) { + const c = stack.pop() as number + p.members.push(c) + p.area += (pieces[c] as Piece).area + for (const o of neighbors[c] ?? []) { + if ((pieces[o] as Piece).state === p.state) { + if (patch[o] === -1) { + patch[o] = patches.length + stack.push(o) + } + } else p.touching.add((pieces[o] as Piece).state) + } + } + patches.push(p) + } + // New state per piece for fragments that have a neighbor. + const newState = new Map() + for (const p of patches) { + if (p.area >= areaMm2 || p.touching.size === 0) continue + const to = Math.min(...p.touching) + for (const m of p.members) newState.set(m, to) + } + if (newState.size === 0) return [] + const changed: number[] = [] + let id = 0 + for (let t = 0; t < n; t++) { + const node = map.get(t) ?? UNPAINTED + const count = leavesOf(trianglePoints(mesh.positions, mesh.indices, t), node).length + const base = id + id += count + let touched = false + for (let k = 0; k < count; k++) if (newState.has(base + k)) touched = true + if (!touched) continue + const after = simplify(setLeaves(trianglePoints(mesh.positions, mesh.indices, t), node, (leaf, i) => newState.get(base + i) ?? leaf.state, { i: 0 })) + if (JSON.stringify(after) === JSON.stringify(node)) continue + record?.(t, map.get(t)) + if (isLeaf(after) && after.state === 0) map.delete(t) + else map.set(t, after) + changed.push(t) + } + return changed +} diff --git a/desktop/src/vendor/slicerx/viewport/painter.ts b/desktop/src/vendor/slicerx/viewport/painter.ts new file mode 100644 index 00000000..00cbde84 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/painter.ts @@ -0,0 +1,714 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Paint tools on the plate: the paint maps of every part, strokes, the clipping plane, cursors and the +// overlay meshes that draw painted pieces on top of the models. How the tools behave (buttons, wheel keys, +// steps, defaults) comes from the preset's paint bindings (gizmobindings.ts). +import { + BufferAttribute, BufferGeometry, Box3, CircleGeometry, Color, DoubleSide, Group, LineBasicMaterial, LineDashedMaterial, LineLoop, LineSegments, Mesh, MeshBasicMaterial, MeshStandardMaterial, Plane, SphereGeometry, + Matrix3, Vector3, type Camera, type Object3D, +} from 'three' +import { planeContour } from './contour' +import type { PaintBindings } from './gizmobindings' +import type { ObjectEntry } from './model' +import { + autoDetail, cylinderRegion, decodeTree, encodeTree, fillByAngle, fillConnected, gapFill, gridFor, isLeaf, leavesOf, paintDab, paintLeafAt, paintPatch, readPaintTexts, replaceEverywhere, + slabRegion, sphereRegion, stateAt, trianglePoints, withPointFilter, + type PaintMap, type PaintNode, type PaintRecorder, type PaintRegion, type V3, +} from './paint' +import type { PaintEdit, PaintLayer, PaintSettings, PaintStroke } from './types' + +export const DEFAULT_PAINT: PaintSettings = { + layer: 'color', + tool: 'brush', + shape: 'sphere', + radiusMm: 1, + state: 1, + erase: false, + splitTriangles: true, + detailMm: 0, + angleDeg: 30, + fillAngleDeg: 30, + heightMm: 0.2, + heightRangeMm: [0, 10], + gapAreaMm2: 0, + secondState: 2, + overhangOnlyDeg: 0, + clipRatio: 0, +} + +// Cursor tints from OrcaSlicer's painter: hover black, left button blue, right button red, each at 25 percent. +const CURSOR_HOVER = { color: '#000000' } +const CURSOR_LEFT = { color: '#0000ff' } +const CURSOR_RIGHT = { color: '#ff0000' } +const ENFORCER = '#50fa7b' +const BLOCKER = '#ff5555' +// Painted fuzzy skin: Subban orange, apart from the support and seam green and red. +const FUZZY = '#ffb86c' +const SLOT_FALLBACK = ['#f7d959', '#fec600', '#ebebe6', '#1d1d21', '#ff9016', '#de4343', '#56b7e6', '#61c680'] + +interface PartPaint { + map: PaintMap + overlay: Mesh | null + dirty: boolean +} + +/** What a pointer hit tells the painter. Point and direction are in world space. */ +export interface PaintHit { + entry: ObjectEntry + part: number + point: Vector3 + dir: Vector3 + face: number +} + +export class Painter { + settings: PaintSettings = { ...DEFAULT_PAINT, heightRangeMm: [...DEFAULT_PAINT.heightRangeMm] } + private colors: readonly string[] = SLOT_FALLBACK + private readonly parts = new Map() + /** Edits of the running stroke, by part: a drag can cross onto another part of the model. */ + private stroke: { objectId: string; layer: PaintLayer; parts: Map> } | null = null + private cursorGroup: Group | null = null + active = false + private strokeErase = false + private strokeState: number | null = null + + /** The clipping plane (Alt and the wheel in Orca, Ctrl in PrusaSlicer): what lies in front of it is hidden and not painted. */ + private clip: { ratio: number; normal: Vector3 | null; center: Vector3; radius: number } = { ratio: 0, normal: null, center: new Vector3(), radius: 1 } + onClip: (() => void) | null = null + private button: 'none' | 'left' | 'right' = 'none' + private contours: { key: string; lines: LineSegments[] } | null = null + + constructor( + private readonly entryOf: (id: string) => ObjectEntry | undefined, + private readonly parent: Object3D, + private readonly invalidate: () => void, + private readonly emitStroke: (s: PaintStroke) => void, + private readonly bindings: () => PaintBindings, + ) {} + + /** Puts the tool defaults of the current preset into the settings (radius, band, angles, gap area). */ + applyPreset(): void { + const b = this.bindings() + this.settings = { + ...this.settings, + radiusMm: b.radius.default, + heightMm: b.height.default, + angleDeg: b.angle.smart, + fillAngleDeg: b.angle.bucket, + gapAreaMm2: b.gapArea?.default ?? 0, + tool: b.tools.includes(this.settings.tool) ? this.settings.tool : 'brush', + } + this.invalidate() + } + + // ---- clipping plane ---- + + /** Plane that keeps what is behind the clip (three.js keeps points with a non-negative distance). Null when off. */ + clipPlane(): Plane | null { + const c = this.clip + if (c.ratio === 0 || !c.normal) return null + return new Plane(c.normal.clone().negate(), c.normal.dot(c.center) + c.radius * (1 - 2 * c.ratio)) + } + + /** True when a world point is in front of the clip and so hidden and skipped by the tools. */ + isClipped(p: Vector3): boolean { + const c = this.clip + if (c.ratio === 0 || !c.normal) return false + return c.normal.dot(p.clone().sub(c.center)) > c.radius * (1 - 2 * c.ratio) + } + + /** + * Moves the clip to `ratio` (0 off, 1 everything). The normal points at the camera when the clip first turns on and is + * kept after that, as in Orca; the plane sweeps from the front of the model's bounding sphere to its back. + */ + setClip(ratio: number, camera: Camera | null, entry: ObjectEntry | null): void { + const r = Math.min(1, Math.max(0, Math.round(ratio * 100) / 100)) + if (r === 0) this.clip = { ...this.clip, ratio: 0, normal: null } + else { + if (!this.clip.normal && camera) this.clip.normal = camera.getWorldDirection(new Vector3()).negate() + if (entry) { + entry.group.updateMatrixWorld(true) + const box = new Box3().setFromObject(entry.group) + this.clip.center = box.getCenter(new Vector3()) + this.clip.radius = Math.max(1e-3, box.getSize(new Vector3()).length() / 2) + } + this.clip.ratio = r + } + this.settings = { ...this.settings, clipRatio: this.clip.ratio } + for (const p of this.parts.values()) if (p.overlay) this.applyClip(p.overlay.material as MeshStandardMaterial) + this.onClip?.() + this.onSettings?.(this.settings) + this.invalidate() + } + + /** Puts the clipping plane on a material (the overlays use it; the viewport does the models). */ + applyClip(m: { clippingPlanes: Plane[] | null; needsUpdate: boolean }): void { + const plane = this.clipPlane() + const had = m.clippingPlanes !== null && m.clippingPlanes.length > 0 + m.clippingPlanes = plane ? [plane] : null + if (had !== !!plane) m.needsUpdate = true + } + + private key(id: string, part: number, layer: PaintLayer): string { + return `${id}|${part}|${layer}` + } + + private get(id: string, part: number, layer: PaintLayer): PartPaint { + const k = this.key(id, part, layer) + let p = this.parts.get(k) + if (!p) { + p = { map: new Map(), overlay: null, dirty: true } + this.parts.set(k, p) + } + return p + } + + setColors(colors: readonly string[]): void { + this.colors = colors.length ? colors : SLOT_FALLBACK + for (const p of this.parts.values()) p.dirty = true + this.invalidate() + } + + update(s: Partial): void { + const tools = this.bindings().tools + const next = { ...this.settings, ...s, heightRangeMm: s.heightRangeMm ? ([s.heightRangeMm[0], s.heightRangeMm[1]] as [number, number]) : this.settings.heightRangeMm } + // A tool the look's source app does not have is ignored. + if (s.tool && !tools.includes(s.tool)) next.tool = this.settings.tool + if (s.clipRatio !== undefined && s.clipRatio !== this.clip.ratio) { + this.settings = next + this.setClip(s.clipRatio, null, null) + return + } + this.settings = next + this.showLayerOverlays() + this.invalidate() + } + + /** + * The wheel in the paint tool, one step per notch (`dir` +1 up, -1 down). `param` changes what the tool has (radius, height + * band, fill angle or gap area) in the steps of the preset; `clip` moves the clipping plane by 0.01. + */ + wheel(dir: 1 | -1, what: 'param' | 'clip', camera: Camera | null = null, entry: ObjectEntry | null = null): void { + const b = this.bindings() + const s = this.settings + const clamp = (v: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, Math.round(v * 100) / 100)) + if (what === 'clip') { + this.setClip(this.clip.ratio + dir * 0.01, camera, entry) + return + } + if (s.tool === 'height') s.heightMm = clamp(s.heightMm + dir * b.height.step, b.height.min, b.height.max) + else if (s.tool === 'fill' || s.tool === 'smart') { + const a = b.angle + const cur = s.tool === 'smart' ? s.angleDeg : s.fillAngleDeg + const next = clamp(cur + dir * a.step, a.min, a.max) + if (a.shared) { + s.angleDeg = next + s.fillAngleDeg = next + } else if (s.tool === 'smart') s.angleDeg = next + else s.fillAngleDeg = next + } else if (s.tool === 'gap' && b.gapArea) s.gapAreaMm2 = clamp(s.gapAreaMm2 + dir * b.gapArea.step, b.gapArea.min, b.gapArea.max) + else if (s.tool === 'brush') s.radiusMm = clamp(s.radiusMm + dir * b.radius.step, b.radius.min, b.radius.max) + this.invalidate() + this.onSettings?.(this.settings) + } + + onSettings: ((s: PaintSettings) => void) | null = null + + setActive(on: boolean): void { + this.active = on + if (!on) { + this.setCursor(null, new Vector3()) + if (this.clip.ratio !== 0) this.setClip(0, null, null) + } + this.showLayerOverlays() + this.invalidate() + } + + private showLayerOverlays(): void { + for (const [k, p] of this.parts) { + if (!p.overlay) continue + const layer = k.split('|')[2] as PaintLayer + p.overlay.visible = layer === 'color' || (this.active && layer === this.settings.layer) + } + } + + // ---- data ---- + + getData(id: string, part: number, layer: PaintLayer): Record { + const out: Record = {} + const m = this.parts.get(this.key(id, part, layer))?.map + if (!m) return out + for (const [t, n] of m) { + const s = encodeTree(n) + if (s) out[t] = s + } + return out + } + + setData(id: string, part: number, layer: PaintLayer, texts: Record | null): number[] { + const p = this.get(id, part, layer) + const { map, bad } = readPaintTexts(texts ?? {}) + p.map = map + p.dirty = true + this.invalidate() + return bad + } + + applyEdits(id: string, part: number, layer: PaintLayer, edits: readonly { triangle: number; text: string | null }[]): void { + const p = this.get(id, part, layer) + for (const e of edits) { + const n = e.text ? decodeTree(e.text) : null + if (n && !(isLeaf(n) && n.state === 0)) p.map.set(e.triangle, n) + else p.map.delete(e.triangle) + } + p.dirty = true + this.invalidate() + } + + hasPaint(id: string, part: number, layer: PaintLayer): boolean { + return (this.parts.get(this.key(id, part, layer))?.map.size ?? 0) > 0 + } + + // ---- strokes ---- + + private state(): number { + if (this.settings.erase || this.strokeErase) return 0 + return this.strokeState ?? this.settings.state + } + + /** Starts a stroke. `erase` (the erase key) writes state 0; `state` overrides the setting (a blocker, the second color). */ + begin(entry: ObjectEntry, part: number, opts: { erase?: boolean; state?: number; button?: 'left' | 'right' } = {}): void { + this.strokeErase = opts.erase ?? false + this.strokeState = opts.state ?? null + this.button = opts.button ?? 'left' + this.stroke = { objectId: entry.id, layer: this.settings.layer, parts: new Map([[part, new Map()]]) } + } + + private strokeBefore(entry: ObjectEntry, part: number): PaintRecorder { + if (!this.stroke || this.stroke.objectId !== entry.id) this.begin(entry, part) + const st = this.stroke as NonNullable + let before = st.parts.get(part) + if (!before) { + before = new Map() + st.parts.set(part, before) + } + const b = before + return (t, prev) => { + if (!b.has(t)) b.set(t, prev ?? null) + } + } + + /** Gate for the tools that spread over triangles: overhang-only painting and the clipping plane. Null when neither is on. */ + private gateFor(mesh: Mesh, src: { positions: Float32Array; indices: Uint32Array | Uint16Array }, useOverhang: boolean): ((t: number) => boolean) | null { + const limit = useOverhang && this.settings.overhangOnlyDeg > 0 ? -Math.cos((this.settings.overhangOnlyDeg * Math.PI) / 180) : null + const clipped = this.clipPlane() !== null + if (limit === null && !clipped) return null + const nm = new Matrix3().getNormalMatrix(mesh.matrixWorld) + const tmp = new Vector3() + return (t) => { + const tri = trianglePoints(src.positions, src.indices, t) + if (limit !== null) { + const a = tri[0] + const b = tri[1] + const c = tri[2] + tmp.set((b[1] - a[1]) * (c[2] - a[2]) - (b[2] - a[2]) * (c[1] - a[1]), (b[2] - a[2]) * (c[0] - a[0]) - (b[0] - a[0]) * (c[2] - a[2]), (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])).applyMatrix3(nm).normalize() + // World up is the y axis of the scene; Orca compares the world z of the face normal with -cos of the angle. + if (!(tmp.y < limit)) return false + } + if (clipped) for (const v of tri) if (this.isClipped(mesh.localToWorld(new Vector3(v[0], v[1], v[2])))) return false + return true + } + } + + /** One dab or one fill at a hit. Returns true if anything changed. */ + apply(hit: PaintHit): boolean { + const s = this.settings + const mesh = hit.entry.parts[hit.part]?.mesh + const src = mesh?.userData.source as { positions: Float32Array; indices: Uint32Array | Uint16Array } | undefined + if (!mesh || !src) return false + const record = this.strokeBefore(hit.entry, hit.part) + const layer = (this.stroke as NonNullable).layer + const pp = this.get(hit.entry.id, hit.part, layer) + mesh.updateWorldMatrix(true, false) + const local = mesh.worldToLocal(hit.point.clone()) + const scale = mesh.matrixWorld.getMaxScaleOnAxis() || 1 + const rLocal = s.radiusMm / scale + const state = this.state() + const b = this.bindings() + const mesh2 = { positions: src.positions, indices: src.indices } + let changed: number[] = [] + if (s.tool === 'brush') { + const c: V3 = [local.x, local.y, local.z] + const dirLocal = hit.dir.clone().transformDirection(mesh.matrixWorld.clone().invert()) + const d: V3 = [dirLocal.x, dirLocal.y, dirLocal.z] + let region: PaintRegion = s.shape === 'sphere' ? sphereRegion(c, rLocal) : cylinderRegion(c, d, rLocal, false) + if (this.clipPlane()) { + const tmp = new Vector3() + region = withPointFilter(region, (p) => !this.isClipped(mesh.localToWorld(tmp.set(p[0], p[1], p[2])))) + } + const limit = s.detailMm > 0 ? s.detailMm : Math.min(s.radiusMm / b.detail.divisor, b.detail.cap ?? Infinity) + changed = paintPatch(mesh2, pp.map, hit.face, region, state, { minEdge: Math.max(0.005, limit / scale), noSplit: !s.splitTriangles }, d, record, this.gateFor(mesh, src, true) ?? undefined) + } else if (s.tool === 'triangle') { + const t = hit.face + const tri = trianglePoints(src.positions, src.indices, t) + const before = pp.map.get(t) ?? { state: 0 } + const after = paintLeafAt(tri, before, [local.x, local.y, local.z], state) + if (after !== before) { + record(t, pp.map.get(t)) + if (isLeaf(after) && after.state === 0) pp.map.delete(t) + else pp.map.set(t, after) + changed = [t] + } + } else if (s.tool === 'fill') { + changed = fillConnected(mesh2, pp.map, hit.face, [local.x, local.y, local.z], state, s.fillAngleDeg, record) + } else if (s.tool === 'smart') { + changed = fillByAngle(mesh2, pp.map, hit.face, state, s.angleDeg, record, this.gateFor(mesh, src, true) ?? undefined) + } else if (s.tool === 'replace') { + changed = this.replaceAll(hit, state) + } else if (s.tool === 'height') { + const z = hit.point.y + const [lo, hi] = b.height.anchor === 'center' ? [z - s.heightMm / 2, z + s.heightMm / 2] : [z, z + s.heightMm] + changed = this.heightRange(hit.entry, hit.part, pp, state, lo, hi, record) + // Orca paints the band on every part of the model, not only the one under the pointer. + hit.entry.parts.forEach((_, i) => { + if (i === hit.part) return + const other = this.get(hit.entry.id, i, layer) + const rec = this.strokeBefore(hit.entry, i) + if (this.heightRange(hit.entry, i, other, state, lo, hi, rec).length) other.dirty = true + }) + } + if (!changed.length) return false + pp.dirty = true + this.invalidate() + return true + } + + /** PrusaSlicer's color replace: every piece of the color under the pointer, on every part, takes the new state. */ + private replaceAll(hit: PaintHit, state: number): number[] { + const layer = this.settings.layer + const mesh = hit.entry.parts[hit.part]?.mesh + const src = mesh?.userData.source as { positions: Float32Array; indices: Uint32Array | Uint16Array } | undefined + if (!mesh || !src) return [] + const local = mesh.worldToLocal(hit.point.clone()) + const pp = this.get(hit.entry.id, hit.part, layer) + const tri = trianglePoints(src.positions, src.indices, hit.face) + const target = stateAt(tri, pp.map.get(hit.face) ?? { state: 0 }, [local.x, local.y, local.z]) + if (target === state) return [] + let first: number[] = [] + hit.entry.parts.forEach((part, i) => { + const m = part.mesh + const sr = m.userData.source as { positions: Float32Array; indices: Uint32Array | Uint16Array } | undefined + if (!sr) return + const p = this.get(hit.entry.id, i, layer) + const rec = this.strokeBefore(hit.entry, i) + m.updateWorldMatrix(true, false) + const gate = this.gateFor(m, sr, false) + const changed = replaceEverywhere({ positions: sr.positions, indices: sr.indices }, p.map, target, state, gate ?? undefined, rec) + if (changed.length) p.dirty = true + if (i === hit.part) first = changed + }) + return first + } + + /** + * Gap fill (Orca and Bambu Studio's Perform button): patches smaller than `gapAreaMm2` merge into a neighbor, on every part of + * the model, as one stroke per part. + */ + performGapFill(entry: ObjectEntry): void { + const layer = this.settings.layer + entry.parts.forEach((part, i) => { + const sr = part.mesh.userData.source as { positions: Float32Array; indices: Uint32Array | Uint16Array } | undefined + if (!sr) return + const pp = this.get(entry.id, i, layer) + const before = new Map() + part.mesh.updateWorldMatrix(true, false) + const scale = part.mesh.matrixWorld.getMaxScaleOnAxis() || 1 + const changed = gapFill({ positions: sr.positions, indices: sr.indices }, pp.map, this.settings.gapAreaMm2 / (scale * scale), (t, prev) => { + if (!before.has(t)) before.set(t, prev ?? null) + }) + if (!changed.length) return + pp.dirty = true + this.emitStroke({ objectId: entry.id, partIndex: i, layer, edits: this.edits(pp.map, before) }) + }) + this.invalidate() + } + + /** Paints the bed-height range on one part. */ + private heightRange(entry: ObjectEntry, part: number, pp: PartPaint, state: number, worldLo: number, worldHi: number, record?: PaintRecorder): number[] { + const mesh = entry.parts[part]?.mesh + const src = mesh?.userData.source as { positions: Float32Array; indices: Uint32Array | Uint16Array } | undefined + if (!mesh || !src) return [] + mesh.updateWorldMatrix(true, false) + const e = mesh.matrixWorld.elements + // World height of a local point p is row 1 of the matrix times p, plus the y translation. + const row: V3 = [e[1] ?? 0, e[5] ?? 0, e[9] ?? 0] + const sc = Math.hypot(...row) || 1 + const ty = e[13] ?? 0 + let region: PaintRegion = slabRegion(row, (Math.min(worldLo, worldHi) - ty) / sc, (Math.max(worldLo, worldHi) - ty) / sc) + if (this.clipPlane()) { + const tmp = new Vector3() + region = withPointFilter(region, (p) => !this.isClipped(mesh.localToWorld(tmp.set(p[0], p[1], p[2])))) + } + const box = mesh.geometry.boundingBox + const bb: [V3, V3] = box ? [[box.min.x, box.min.y, box.min.z], [box.max.x, box.max.y, box.max.z]] : [[-1e6, -1e6, -1e6], [1e6, 1e6, 1e6]] + // Orca's height range splits down to 0.1 mm whatever the brush radius. + return paintDab({ positions: src.positions, indices: src.indices }, pp.map, bb, region, state, { minEdge: Math.max(0.005, (this.settings.detailMm > 0 ? this.settings.detailMm : 0.1) / (mesh.matrixWorld.getMaxScaleOnAxis() || 1)), noSplit: !this.settings.splitTriangles }, record) + } + + /** The band `[lo, hi]` (bed height, mm) over every part of a model, as one stroke. Defaults to `heightRangeMm`. */ + paintHeightRange(entry: ObjectEntry, range?: [number, number]): void { + const [lo, hi] = range ?? this.settings.heightRangeMm + const layer = this.settings.layer + const st = this.settings.erase ? 0 : this.settings.state + entry.parts.forEach((_, i) => { + const pp = this.get(entry.id, i, layer) + const b = new Map() + const changed = this.heightRange(entry, i, pp, st, lo, hi, (t, prev) => { + if (!b.has(t)) b.set(t, prev ?? null) + }) + if (!changed.length) return + pp.dirty = true + this.emitStroke({ objectId: entry.id, partIndex: i, layer, edits: this.edits(pp.map, b) }) + }) + this.invalidate() + } + + private edits(map: PaintMap, before: Map): PaintEdit[] { + const out: PaintEdit[] = [] + for (const [t, b] of before) { + const a = map.get(t) ?? null + const bt = b ? encodeTree(b) : null + const at = a ? encodeTree(a) : null + if (bt !== at) out.push({ triangle: t, before: bt, after: at }) + } + return out + } + + /** Ends a stroke and reports it. */ + end(): void { + const st = this.stroke + this.stroke = null + this.strokeErase = false + this.strokeState = null + this.button = 'none' + if (!st) return + for (const [part, before] of st.parts) { + const pp = this.parts.get(this.key(st.objectId, part, st.layer)) + if (!pp) continue + const edits = this.edits(pp.map, before) + if (edits.length) this.emitStroke({ objectId: st.objectId, partIndex: part, layer: st.layer, edits }) + } + } + + cancel(): void { + this.stroke = null + this.strokeErase = false + this.strokeState = null + this.button = 'none' + } + + // ---- drawing ---- + + /** + * The cursor of the running tool, drawn as OrcaSlicer draws it (GLGizmoPainterBase): a translucent sphere at the hit for the + * sphere brush, tinted black when hovering, blue with the left button down and red with the right; for the circle brush a + * dashed green ring with a translucent disc facing the camera; for the height tool the cut of the model at the bottom and top + * of the band. Other tools show none. + */ + setCursor(hit: PaintHit | null, dir: Vector3): void { + const s = this.settings + const show = !!hit && this.active && (s.tool === 'brush' || s.tool === 'height') + if (!show || !hit) { + if (this.cursorGroup) this.cursorGroup.visible = false + this.clearContours() + return + } + if (s.tool === 'height') { + if (this.cursorGroup) this.cursorGroup.visible = false + this.showContours(hit) + return + } + this.clearContours() + if (!this.cursorGroup) { + const g = new Group() + g.renderOrder = 6 + const sphere = new Mesh(new SphereGeometry(1, 24, 16), new MeshBasicMaterial({ transparent: true, depthWrite: false, toneMapped: false })) + sphere.name = 'sphere' + const disc = new Mesh(new CircleGeometry(1, 48), new MeshBasicMaterial({ transparent: true, depthWrite: false, depthTest: false, toneMapped: false, side: DoubleSide })) + disc.name = 'disc' + const pts: number[] = [] + for (let i = 0; i < 64; i++) pts.push(Math.cos((i / 64) * Math.PI * 2), Math.sin((i / 64) * Math.PI * 2), 0) + const ringGeo = new BufferGeometry() + ringGeo.setAttribute('position', new BufferAttribute(new Float32Array(pts), 3)) + const ring = new LineLoop(ringGeo, new LineDashedMaterial({ color: new Color('#00ff4d'), dashSize: 0.12, gapSize: 0.12, depthTest: false, transparent: true })) + ring.name = 'ring' + ring.computeLineDistances() + for (const o of [sphere, disc, ring]) { + o.raycast = () => {} + o.renderOrder = 6 + g.add(o) + } + this.parent.add(g) + this.cursorGroup = g + } + const g = this.cursorGroup + g.visible = true + const sphere = g.getObjectByName('sphere') as Mesh + const disc = g.getObjectByName('disc') as Mesh + const ring = g.getObjectByName('ring') as LineLoop + const sph = s.shape === 'sphere' + sphere.visible = sph + disc.visible = !sph + ring.visible = !sph + const tint = this.button === 'left' ? CURSOR_LEFT : this.button === 'right' ? CURSOR_RIGHT : CURSOR_HOVER + for (const m of [sphere, disc]) { + const mat = m.material as MeshBasicMaterial + mat.color.set(tint.color) + mat.opacity = 0.25 + } + g.position.copy(this.parent.worldToLocal(hit.point.clone())) + g.scale.setScalar(Math.max(s.radiusMm, 0.05)) + if (!sph) { + g.up.set(0, 1, 0) + g.lookAt(g.position.clone().add(dir)) + } else g.quaternion.identity() + this.invalidate() + } + + private clearContours(): void { + if (!this.contours) return + for (const l of this.contours.lines) { + l.removeFromParent() + l.geometry.dispose() + } + this.contours = null + } + + /** The cut of each part at the bottom and top of the height band, in the part's own frame. */ + private showContours(hit: PaintHit): void { + const b = this.bindings() + const s = this.settings + const z = hit.point.y + const [lo, hi] = b.height.anchor === 'center' ? [z - s.heightMm / 2, z + s.heightMm / 2] : [z, z + s.heightMm] + const key = `${hit.entry.id}|${lo.toFixed(3)}|${hi.toFixed(3)}` + if (this.contours?.key === key) return + this.clearContours() + const lines: LineSegments[] = [] + const box = new Box3().setFromObject(hit.entry.group) + for (const part of hit.entry.parts) { + const mesh = part.mesh + const src = mesh.userData.source as { positions: Float32Array; indices: Uint32Array | Uint16Array } | undefined + if (!src) continue + mesh.updateWorldMatrix(true, false) + const e = mesh.matrixWorld.elements + const row: V3 = [e[1] ?? 0, e[5] ?? 0, e[9] ?? 0] + const sc = Math.hypot(...row) || 1 + const ty = e[13] ?? 0 + const n: V3 = [row[0] / sc, row[1] / sc, row[2] / sc] + for (const h of [lo, hi]) { + const clamped = Math.min(box.max.y, Math.max(box.min.y, h)) + const seg = planeContour(src.positions, src.indices, n, (clamped - ty) / sc) + if (!seg.length) continue + const g = new BufferGeometry() + g.setAttribute('position', new BufferAttribute(seg, 3)) + const l = new LineSegments(g, new LineBasicMaterial({ color: new Color('#00ff4d'), depthTest: false, transparent: true, toneMapped: false })) + l.raycast = () => {} + l.renderOrder = 6 + mesh.add(l) + lines.push(l) + } + } + this.contours = { key, lines } + this.invalidate() + } + + private colorOf(layer: PaintLayer, state: number): Color { + if (layer === 'color') return new Color(this.colors[state - 1] ?? SLOT_FALLBACK[(state - 1) % SLOT_FALLBACK.length] ?? '#ffffff') + if (layer === 'fuzzy') return new Color(FUZZY) + return new Color(state === 2 ? BLOCKER : ENFORCER) + } + + /** Rebuilds overlays of parts whose paint changed. Call before rendering. Returns true if any changed. */ + sync(): boolean { + let any = false + for (const [k, p] of this.parts) { + const [id, partS, layerS] = k.split('|') as [string, string, PaintLayer] + const entry = this.entryOf(id) + const part = entry?.parts[Number(partS)] + const mesh = part?.mesh + if (!mesh) { + if (p.overlay) { + p.overlay.removeFromParent() + p.overlay.geometry.dispose() + p.overlay = null + p.dirty = true + } + continue + } + if (p.overlay && p.overlay.parent !== mesh) { + p.overlay.removeFromParent() + p.overlay.geometry.dispose() + p.overlay = null + p.dirty = true + } + if (!p.dirty) continue + p.dirty = false + any = true + const src = mesh.userData.source as { positions: Float32Array; indices: Uint32Array | Uint16Array } | undefined + if (!src) continue + const pos: number[] = [] + const col: number[] = [] + for (const [t, node] of p.map) { + const tri = trianglePoints(src.positions, src.indices, t) + for (const leaf of leavesOf(tri, node)) { + if (leaf.state === 0) continue + const c = this.colorOf(layerS, leaf.state) + for (const v of leaf.v) { + pos.push(v[0], v[1], v[2]) + col.push(c.r, c.g, c.b) + } + } + } + if (p.overlay) { + p.overlay.removeFromParent() + p.overlay.geometry.dispose() + p.overlay = null + } + if (!pos.length) continue + const g = new BufferGeometry() + g.setAttribute('position', new BufferAttribute(new Float32Array(pos), 3)) + g.setAttribute('color', new BufferAttribute(new Float32Array(col), 3)) + g.computeVertexNormals() + const m = new MeshStandardMaterial({ vertexColors: true, roughness: 0.85, metalness: 0, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -6 }) + const o = new Mesh(g, m) + o.raycast = () => {} + o.castShadow = false + o.renderOrder = 1 + this.applyClip(m) + o.visible = layerS === 'color' || (this.active && layerS === this.settings.layer) + mesh.add(o) + p.overlay = o + } + return any + } + + dispose(): void { + for (const p of this.parts.values()) { + p.overlay?.removeFromParent() + p.overlay?.geometry.dispose() + } + this.parts.clear() + this.cursorGroup?.removeFromParent() + this.clearContours() + } +} + +/** Keeps `gridFor` linked so a part's triangle grid is built on first use. */ +export function warmPaintGrid(positions: ArrayLike, indices: ArrayLike): void { + gridFor({ positions, indices }) +} + +/** Whether a layer's state means anything for this tool (seam and support take 1 or 2). */ +export function validState(layer: PaintLayer, state: number): boolean { + return layer === 'color' ? state >= 1 && state <= 32 : state === 1 || state === 2 +} diff --git a/desktop/src/vendor/slicerx/viewport/palette.ts b/desktop/src/vendor/slicerx/viewport/palette.ts new file mode 100644 index 00000000..745e5eba --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/palette.ts @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Colors the renderer draws with. They follow the Subban tokens in +// packages/ui/tokens.css; GL needs them as numbers, so they are listed here. +// Apps should build legends from these exports so swatches match the scene. +// --------------------------------------------------------------------------------------------------------------- +// MODIFIED BY SNAPMAKER STUDIO (DVOpenLabs/snapmaker-studio): the only change in this file is the import path of the +// contracts module ('@slicerx/contracts' -> '../contracts/index'). Upstream: slicerx-oss/slicerx @ +// edb521fe41306dd60d01bda8a0f6bf8aa54fcb29 (Apache-2.0). See ../UPDATING.md. +// --------------------------------------------------------------------------------------------------------------- +import { FEATURE, type FeatureId } from '../contracts/index' + +export interface FeatureStyle { + id: FeatureId + label: string + color: string +} + +/** + * Preview colors by SXPV feature id. None sits on a meaning color of the UI + * (red for errors, cyan for selection and info) or on pink beside purple, so a + * toolpath never reads as a status. + */ +export const FEATURE_COLORS: readonly FeatureStyle[] = [ + { id: FEATURE.outerWall, label: 'Outer wall', color: '#f0b429' }, + { id: FEATURE.innerWall, label: 'Inner wall', color: '#bd93f9' }, + { id: FEATURE.overhangWall, label: 'Overhang wall', color: '#4f7cff' }, + { id: FEATURE.topSurface, label: 'Top surface', color: '#ff8a3d' }, + { id: FEATURE.bottomSurface, label: 'Bottom surface', color: '#8e9bd4' }, + { id: FEATURE.internalSolid, label: 'Internal solid infill', color: '#9c5a3c' }, + { id: FEATURE.sparseInfill, label: 'Sparse infill', color: '#d6c48a' }, + { id: FEATURE.bridge, label: 'Bridge', color: '#5aa9e6' }, + { id: FEATURE.support, label: 'Support', color: '#50fa7b' }, + { id: FEATURE.supportInterface, label: 'Support interface', color: '#2f9e5a' }, + { id: FEATURE.brimSkirt, label: 'Brim and skirt', color: '#9ad14b' }, + { id: FEATURE.ironing, label: 'Ironing', color: '#f1fa8c' }, + { id: FEATURE.gapFill, label: 'Gap fill', color: '#f8f8f2' }, + { id: FEATURE.primeTower, label: 'Prime tower', color: '#9aa4c1' }, + { id: FEATURE.custom, label: 'Custom', color: '#8f9abb' }, +] + +/** + * A palette for color vision deficiency, built on the Okabe and Ito set. Features differ in hue along the + * blue to orange axis and in lightness, never by red against green. The overhang heat map runs from gray + * through yellow to vermillion, and speed, flow and layer time run blue to yellow to orange to vermillion. + */ +export const COLORBLIND_THEME: Required> & { scene: Pick } = { + features: { + [FEATURE.outerWall]: '#e69f00', + [FEATURE.innerWall]: '#cc79a7', + [FEATURE.overhangWall]: '#56b4e9', + [FEATURE.topSurface]: '#d55e00', + [FEATURE.bottomSurface]: '#c8cbe0', + [FEATURE.internalSolid]: '#7a4a1e', + [FEATURE.sparseInfill]: '#f0e442', + [FEATURE.bridge]: '#0072b2', + [FEATURE.support]: '#009e73', + [FEATURE.supportInterface]: '#004d3c', + [FEATURE.brimSkirt]: '#bdbdbd', + [FEATURE.ironing]: '#fff7b3', + [FEATURE.gapFill]: '#ffffff', + [FEATURE.primeTower]: '#5f6b8a', + [FEATURE.custom]: '#9b8cff', + }, + heatRamp: ['#2f6fe0', '#56b4e9', '#f0e442', '#e69f00', '#d55e00'], + scene: { overhangRed: '#d55e00', overhangAmber: '#f0e442' }, +} + +/** Ramp for speed, flow and layer time, low to high. */ +export const HEAT_RAMP: readonly string[] = ['#4f6bed', '#8be9fd', '#f1fa8c', '#ffb86c', '#ff5555'] + +/** Default filament colors when the app has not called setToolColors. */ +export const DEFAULT_TOOL_COLORS: readonly string[] = ['#f7d959', '#fec600', '#ebebe6', '#1d1d21', '#ff9016', '#de4343', '#56b7e6', '#61c680'] + +export const SCENE = { + bgTop: '#2f3241', + bgBottom: '#20222b', + bgGlow: '#3c3f50', + selection: '#bd93f9', + selectionHidden: '#6a58a0', + liveLayer: '#8be9fd', + overhangRed: '#ff4b5c', + overhangAmber: '#ffb86c', + clay: '#cbc4b8', + overhangBase: '#767c98', + plateSide: '#3c3f50', + floorGrid: '#9aa4c1', + edgeDark: '#16171e', + edgeXray: '#c9d2ff', + xrayTint: '#a8ecff', + travel: '#8be9fd', + retraction: '#f8f8f2', + seam: '#facc15', + lift: '#38bdf8', + wipe: '#c4b5fd', + toolChange: '#f472b6', + pause: '#fb923c', +} as const + +export type SceneColors = Record + +/** + * Colors of the 3D scene an integrator can change. Every field is optional and + * falls back to the SlicerX default. Colors are `#rrggbb`. Meaning colors + * (selection, live layer, overhang red and amber) are yours to change, but keep + * them apart from the toolpath colors so a color never reads as a status. + */ +export interface ViewportTheme { + /** Background gradient, selection outline, bed, overhang heat map, travel and live layer colors. */ + scene?: Partial + /** Toolpath color per SXPV feature id. */ + features?: Partial> + /** Ramp for speed, flow and layer time, low to high; two to eight stops. */ + heatRamp?: readonly string[] + /** Filament colors used until the app calls setToolColors. */ + toolColors?: readonly string[] +} + +export interface ResolvedTheme { + scene: SceneColors + /** In FEATURE_COLORS order. */ + featureColors: string[] + heatRamp: readonly string[] + toolColors: readonly string[] +} + +const HEX = /^#[0-9a-fA-F]{6}$/ + +/** Problems in a theme, as readable strings. An empty list means the theme is usable. */ +export function themeProblems(theme: ViewportTheme | undefined): string[] { + const out: string[] = [] + if (!theme) return out + const check = (where: string, v: unknown): void => { + if (typeof v !== 'string' || !HEX.test(v)) out.push(`${where} must be a #rrggbb color, got ${String(v)}`) + } + const knownScene = new Set(Object.keys(SCENE)) + for (const [k, v] of Object.entries(theme.scene ?? {})) { + if (!knownScene.has(k)) out.push(`scene.${k} is not a scene color`) + else if (v !== undefined) check(`scene.${k}`, v) + } + const knownFeature = new Set(FEATURE_COLORS.map((f) => f.id)) + for (const [k, v] of Object.entries(theme.features ?? {})) { + if (!knownFeature.has(Number(k))) out.push(`features.${k} is not a feature id`) + else if (v !== undefined) check(`features.${k}`, v) + } + if (theme.heatRamp) { + if (theme.heatRamp.length < 2 || theme.heatRamp.length > 8) out.push('heatRamp needs two to eight colors') + theme.heatRamp.forEach((c, i) => check(`heatRamp[${i}]`, c)) + } + if (theme.toolColors) theme.toolColors.forEach((c, i) => check(`toolColors[${i}]`, c)) + return out +} + +/** Merges a theme onto the defaults. Throws if `themeProblems` is not empty. */ +export function resolveTheme(theme?: ViewportTheme): ResolvedTheme { + const problems = themeProblems(theme) + if (problems.length) throw new Error(`Invalid viewport theme: ${problems.join('; ')}`) + const scene = { ...SCENE } as SceneColors + for (const [k, v] of Object.entries(theme?.scene ?? {})) if (v !== undefined) scene[k as keyof SceneColors] = v + // the hidden outline is the selection sunk halfway into the backdrop, so a new accent never leaves the old one behind + if (theme?.scene?.selection && !theme.scene.selectionHidden) scene.selectionHidden = mixHex(scene.selection, scene.bgBottom, 0.5) + return { + scene, + featureColors: FEATURE_COLORS.map((f) => theme?.features?.[f.id] ?? f.color), + heatRamp: theme?.heatRamp ?? HEAT_RAMP, + toolColors: theme?.toolColors && theme.toolColors.length ? theme.toolColors : DEFAULT_TOOL_COLORS, + } +} + +/** `a` moved toward `b` by `t` (0 to 1), as #rrggbb. */ +export function mixHex(a: string, b: string, t: number): string { + const x = hexToRgb(a) + const y = hexToRgb(b) + return `#${x.map((v, i) => Math.round(v + ((y[i] as number) - v) * t).toString(16).padStart(2, '0')).join('')}` +} + +export function hexToRgb(hex: string): [number, number, number] { + const n = Number.parseInt(hex.slice(1, 7), 16) + return [(n >> 16) & 255, (n >> 8) & 255, n & 255] +} + +export function srgbToLinear(c: number): number { + const v = c / 255 + return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4) +} + +/** Keeps pure black and white inside a range real filament reaches, so shading still reads. */ +export function displayHex(hex: string): string { + const [r, g, b] = hexToRgb(hex) + const l = 0.2126 * r + 0.7152 * g + 0.0722 * b + if (l < 26) return '#1d1d21' + if (l > 240) return '#ebebe6' + return hex +} diff --git a/desktop/src/vendor/slicerx/viewport/post.ts b/desktop/src/vendor/slicerx/viewport/post.ts new file mode 100644 index 00000000..4f4b5388 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/post.ts @@ -0,0 +1,530 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Frame pipeline: an MSAA HDR scene pass with a depth texture, depth-only +// ambient occlusion at half resolution (no second geometry pass, which matters +// with millions of toolpath instances), a selection outline from a mask, +// then one grade pass (Khronos PBR Neutral tone mapping, background, vignette, +// dither, sRGB) and FXAA to the canvas. +import { + Color, + CustomBlending, + DepthTexture, + FloatType, + HalfFloatType, + LinearFilter, + MaxEquation, + Mesh, + NearestFilter, + NoBlending, + OneFactor, + ShaderMaterial, + UnsignedByteType, + Vector2, + WebGLRenderTarget, + type Camera, + type Material, + type Object3D, + type PerspectiveCamera, + type Scene, + type WebGLRenderer, +} from 'three' +import { FullScreenQuad } from 'three/addons/postprocessing/Pass.js' +import { FXAAShader } from 'three/addons/shaders/FXAAShader.js' +import { SCENE, hexToRgb, type SceneColors } from './palette' +import type { Quality } from './types' + +const QUAD_VS = /* glsl */ ` +varying vec2 vUv; +void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); } +` + +const AO_FS = /* glsl */ ` +uniform sampler2D tDepth; +uniform mat4 proj; +uniform mat4 invProj; +uniform vec2 fullTexel; +uniform float radius; +uniform float bias; +uniform float frame; +varying vec2 vUv; + +vec3 viewPos(vec2 uv, float d) { + vec4 v = invProj * vec4(uv * 2.0 - 1.0, d * 2.0 - 1.0, 1.0); + return v.xyz / v.w; +} +float depthAt(vec2 uv) { return texture2D(tDepth, uv).x; } + +void main() { + float d = depthAt(vUv); + if (d >= 1.0) { gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); return; } + vec3 P = viewPos(vUv, d); + // Normal from depth: take the neighbor on the same surface on each axis so + // silhouettes do not smear into the background. + vec2 dx = vec2(fullTexel.x, 0.0), dy = vec2(0.0, fullTexel.y); + vec3 pl = viewPos(vUv - dx, depthAt(vUv - dx)), pr = viewPos(vUv + dx, depthAt(vUv + dx)); + vec3 pd = viewPos(vUv - dy, depthAt(vUv - dy)), pu = viewPos(vUv + dy, depthAt(vUv + dy)); + // On a smooth surface the two one-sided steps agree, so the central difference is used: it does not + // flip between neighbors as depth quantizes, which showed as bands sweeping across the plate. + float ex1 = pr.z - P.z, ex0 = P.z - pl.z, ey1 = pu.z - P.z, ey0 = P.z - pd.z; + float tolx = 0.25 * (abs(ex1) + abs(ex0)) + 0.001 * abs(P.z); + float toly = 0.25 * (abs(ey1) + abs(ey0)) + 0.001 * abs(P.z); + vec3 ddx = abs(ex1 - ex0) < tolx ? (pr - pl) * 0.5 : (abs(ex1) < abs(ex0) ? pr - P : P - pl); + vec3 ddy = abs(ey1 - ey0) < toly ? (pu - pd) * 0.5 : (abs(ey1) < abs(ey0) ? pu - P : P - pd); + vec3 N = normalize(cross(ddx, ddy)); + if (dot(N, P) > 0.0) N = -N; + float ign = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))); + float ang = (ign + frame * 0.618034) * 6.2831853; + vec3 rv = vec3(cos(ang), sin(ang), 0.37); + vec3 T = normalize(rv - N * dot(rv, N)); + vec3 B = cross(N, T); + float occ = 0.0; + for (int i = 0; i < SAMPLES; i++) { + float fi = (float(i) + 0.5) / float(SAMPLES); + float r = sqrt(fi); + float th = float(i) * 2.3999632; + vec2 dsk = r * vec2(cos(th), sin(th)); + float h = sqrt(max(0.0, 1.0 - r * r)); + float s = radius * mix(0.15, 1.0, fi * fi); + vec3 S = P + (T * dsk.x + B * dsk.y + N * h) * s; + vec4 c = proj * vec4(S, 1.0); + vec2 suv = clamp(c.xy / c.w * 0.5 + 0.5, vec2(0.0), vec2(1.0)); + float sz = viewPos(suv, depthAt(suv)).z; + float range = smoothstep(0.0, 1.0, radius / abs(P.z - sz)); + occ += (sz >= S.z + bias + 0.002 * abs(P.z) ? 1.0 : 0.0) * range; + } + gl_FragColor = vec4(1.0 - occ / float(SAMPLES), -P.z, 0.0, 1.0); +} +` + +const BLUR_FS = /* glsl */ ` +uniform sampler2D tAO; +uniform vec2 dir; +varying vec2 vUv; +void main() { + vec4 c = texture2D(tAO, vUv); + float z = c.g; + if (z <= 0.0) { gl_FragColor = c; return; } + float W[5]; + W[0] = 0.2270; W[1] = 0.1946; W[2] = 0.1216; W[3] = 0.0541; W[4] = 0.0162; + float sum = c.r * W[0], wsum = W[0]; + float tol = 0.02 * z + 0.4; + for (int i = 1; i < 5; i++) { + vec4 a = texture2D(tAO, vUv + dir * float(i)); + vec4 b = texture2D(tAO, vUv - dir * float(i)); + float wa = a.g > 0.0 ? W[i] * max(0.0, 1.0 - abs(a.g - z) / tol) : 0.0; + float wb = b.g > 0.0 ? W[i] * max(0.0, 1.0 - abs(b.g - z) / tol) : 0.0; + sum += a.r * wa + b.r * wb; wsum += wa + wb; + } + gl_FragColor = vec4(sum / wsum, z, 0.0, 1.0); +} +` + +const MASK_VS = /* glsl */ ` +#include +#include +void main() { + #include + #include +} +` + +const MASK_FS = /* glsl */ ` +uniform sampler2D tDepth; +uniform vec2 invSize; +void main() { + float sd = texture2D(tDepth, gl_FragCoord.xy * invSize).x; + float vis = gl_FragCoord.z <= sd + 0.00035 ? 1.0 : 0.0; + gl_FragColor = vec4(1.0, vis, 0.0, 1.0); +} +` + +const GRADE_FS = /* glsl */ ` +uniform sampler2D tColor; +uniform sampler2D tAO; +uniform sampler2D tMask; +uniform float aoOn; +uniform float aoStrength; +uniform float outlineOn; +uniform float exposure; +uniform float aspect; +uniform vec2 texel; +uniform float edgePx; +uniform vec3 bgTop; +uniform vec3 bgBot; +uniform vec3 bgGlow; +uniform vec3 edgeVis; +uniform vec3 edgeHid; +varying vec2 vUv; + +// Khronos PBR Neutral: filament colors stay saturated instead of washing toward white. +vec3 neutral(vec3 color) { + const float startC = 0.76; const float desat = 0.15; + float x = min(color.r, min(color.g, color.b)); + float off = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= off; + float peak = max(color.r, max(color.g, color.b)); + if (peak < startC) return color; + float d = 1.0 - startC; + float np = 1.0 - d * d / (peak + d - startC); + color *= np / peak; + float g = 1.0 - 1.0 / (desat * (peak - np) + 1.0); + return mix(color, vec3(np), g); +} +vec3 toSRGB(vec3 c) { + c = clamp(c, 0.0, 1.0); + return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c)); +} +float hash(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); } + +void main() { + vec2 tuv = vUv; + vec4 c = texture2D(tColor, tuv); + float a = clamp(c.a, 0.0, 1.0); + vec3 col = max(c.rgb, 0.0); + if (aoOn > 0.5) col *= mix(1.0, texture2D(tAO, tuv).r, aoStrength); + col = neutral(col * exposure); + vec2 q = vec2((vUv.x - 0.5) * aspect, vUv.y - 0.58); + vec3 bg = mix(bgBot, bgTop, smoothstep(0.0, 1.0, vUv.y)); + bg = mix(bg, bgGlow, (1.0 - smoothstep(0.0, 0.85, length(q))) * 0.8); + vec3 lin = col + pow(bg, vec3(2.2)) * (1.0 - a); + if (outlineOn > 0.5) { + float cov = texture2D(tMask, tuv).r; + float mx = 0.0, vis = 0.0; + for (int i = 0; i < 8; i++) { + float an = float(i) * 0.7853982; + vec2 d = vec2(cos(an), sin(an)) * texel * edgePx; + vec2 m = max(texture2D(tMask, tuv + d).rg, texture2D(tMask, tuv + d * 0.5).rg); + mx = max(mx, m.r); vis = max(vis, m.g); + } + float e = smoothstep(0.05, 0.55, mx - cov); + lin = mix(lin, vis > 0.5 ? edgeVis : edgeHid, e); + } + vec3 o = toSRGB(lin); + vec2 v = vUv - 0.5; + o *= 1.0 - dot(v, v) * 0.42; + o += (hash(gl_FragCoord.xy) - 0.5) / 255.0; + gl_FragColor = vec4(o, 1.0); +} +` + +function srgb01(hex: string): [number, number, number] { + const [r, g, b] = hexToRgb(hex) + return [r / 255, g / 255, b / 255] +} + +function linearColor(hex: string): Color { + return new Color(hex) +} + +export interface FrameOptions { + ao: boolean + /** 0 to 1 scale on AO strength, for fading it in when the camera stops. */ + aoMix: number + /** Draw without MSAA (the camera is moving; FXAA still runs). Still frames use MSAA 4x. */ + fast: boolean + outline: readonly Object3D[] + /** Increments per frame so AO noise rotates; still frames average it away. */ + frameIndex: number +} + +export class Pipeline { + readonly main: WebGLRenderTarget + /** Single-sample twin of `main` for frames drawn while the camera moves. */ + private readonly fast: WebGLRenderTarget + private readonly ao: WebGLRenderTarget + private readonly aoBlur: WebGLRenderTarget + private readonly mask: WebGLRenderTarget + private readonly ldr: WebGLRenderTarget + /** `ldr` twin at the moving-frame scale. */ + private readonly ldrFast: WebGLRenderTarget + private readonly aoMat: ShaderMaterial + private readonly blurMat: ShaderMaterial + private readonly maskMat: ShaderMaterial + private readonly gradeMat: ShaderMaterial + private readonly fxaaMat: ShaderMaterial + private readonly quad = new FullScreenQuad() + private width = 1 + private height = 1 + private pixelRatio = 1 + private scale = 1 + aoRadius = 6 + aoStrength = 0.9 + exposure = 1 + + /** Background gradient and selection outline colors. */ + setSceneColors(scene: SceneColors): void { + const u = this.gradeMat.uniforms + if (u.bgTop) u.bgTop.value = srgb01(scene.bgTop) + if (u.bgBot) u.bgBot.value = srgb01(scene.bgBottom) + if (u.bgGlow) u.bgGlow.value = srgb01(scene.bgGlow) + if (u.edgeVis) u.edgeVis.value = linearColor(scene.selection) + if (u.edgeHid) u.edgeHid.value = linearColor(scene.selectionHidden) + } + + constructor( + private readonly renderer: WebGLRenderer, + private readonly quality: Quality, + ) { + const depthTexture = new DepthTexture(1, 1, FloatType) + this.main = new WebGLRenderTarget(1, 1, { + type: HalfFloatType, + samples: quality === 'low' ? 0 : 4, + depthTexture, + minFilter: LinearFilter, + magFilter: LinearFilter, + }) + const fastDepth = new DepthTexture(1, 1, FloatType) + fastDepth.minFilter = fastDepth.magFilter = NearestFilter + this.fast = new WebGLRenderTarget(1, 1, { type: HalfFloatType, samples: 0, depthTexture: fastDepth, minFilter: LinearFilter, magFilter: LinearFilter }) + const aoOpts = { type: HalfFloatType, depthBuffer: false, minFilter: LinearFilter, magFilter: LinearFilter } + this.ao = new WebGLRenderTarget(1, 1, aoOpts) + this.aoBlur = new WebGLRenderTarget(1, 1, aoOpts) + this.mask = new WebGLRenderTarget(1, 1, { type: UnsignedByteType, depthBuffer: false, minFilter: LinearFilter, magFilter: LinearFilter }) + this.ldr = new WebGLRenderTarget(1, 1, { type: UnsignedByteType, depthBuffer: false, minFilter: LinearFilter, magFilter: LinearFilter }) + this.ldrFast = new WebGLRenderTarget(1, 1, { type: UnsignedByteType, depthBuffer: false, minFilter: LinearFilter, magFilter: LinearFilter }) + + this.aoMat = new ShaderMaterial({ + defines: { SAMPLES: quality === 'high' ? 12 : 8 }, + uniforms: { + tDepth: { value: depthTexture }, + proj: { value: null }, + invProj: { value: null }, + fullTexel: { value: new Vector2() }, + radius: { value: this.aoRadius }, + bias: { value: 0.05 }, + frame: { value: 0 }, + }, + vertexShader: QUAD_VS, + fragmentShader: AO_FS, + depthTest: false, + depthWrite: false, + blending: NoBlending, + }) + this.blurMat = new ShaderMaterial({ + uniforms: { tAO: { value: null }, dir: { value: new Vector2() } }, + vertexShader: QUAD_VS, + fragmentShader: BLUR_FS, + depthTest: false, + depthWrite: false, + blending: NoBlending, + }) + this.maskMat = new ShaderMaterial({ + uniforms: { tDepth: { value: depthTexture }, invSize: { value: new Vector2() } }, + vertexShader: MASK_VS, + fragmentShader: MASK_FS, + depthTest: false, + depthWrite: false, + blending: CustomBlending, + blendEquation: MaxEquation, + blendSrc: OneFactor, + blendDst: OneFactor, + }) + const [tr, tg, tb] = srgb01(SCENE.bgTop) + const [br, bgc, bb] = srgb01(SCENE.bgBottom) + const [gr, gg, gb] = srgb01(SCENE.bgGlow) + this.gradeMat = new ShaderMaterial({ + uniforms: { + tColor: { value: this.main.texture }, + tAO: { value: this.ao.texture }, + tMask: { value: this.mask.texture }, + aoOn: { value: 0 }, + aoStrength: { value: this.aoStrength }, + outlineOn: { value: 0 }, + exposure: { value: this.exposure }, + aspect: { value: 1 }, + texel: { value: new Vector2() }, + edgePx: { value: 1.5 }, + bgTop: { value: [tr, tg, tb] }, + bgBot: { value: [br, bgc, bb] }, + bgGlow: { value: [gr, gg, gb] }, + edgeVis: { value: linearColor(SCENE.selection) }, + edgeHid: { value: linearColor(SCENE.selectionHidden) }, + }, + vertexShader: QUAD_VS, + fragmentShader: GRADE_FS, + depthTest: false, + depthWrite: false, + blending: NoBlending, + }) + this.fxaaMat = new ShaderMaterial({ + uniforms: { tDiffuse: { value: this.ldr.texture }, resolution: { value: new Vector2() } }, + vertexShader: FXAAShader.vertexShader, + fragmentShader: FXAAShader.fragmentShader, + depthTest: false, + depthWrite: false, + blending: NoBlending, + }) + this.mask.texture.minFilter = LinearFilter + this.ao.texture.magFilter = LinearFilter + depthTexture.minFilter = NearestFilter + depthTexture.magFilter = NearestFilter + } + + private readonly probe = new WebGLRenderTarget(1, 1, { depthBuffer: false }) + private readonly probePx = new Uint8Array(4) + + /** + * Waits until the GPU has finished every command issued so far. It clears and reads a 1x1 + * target queued after the frame; reading the canvas itself would also wait for the display. + */ + waitForGpu(): void { + const r = this.renderer + const prev = r.getRenderTarget() + r.setRenderTarget(this.probe) + r.clear(true, false, false) + r.readRenderTargetPixels(this.probe, 0, 0, 1, 1, this.probePx) + r.setRenderTarget(prev) + } + + get fxaa(): boolean { + return this.quality !== 'low' + } + + setSize(width: number, height: number, pixelRatio: number): void { + const w = Math.max(1, Math.round(width * pixelRatio)) + const h = Math.max(1, Math.round(height * pixelRatio)) + this.width = w + this.height = h + this.pixelRatio = pixelRatio + this.main.setSize(w, h) + this.resizeFast() + const aw = Math.max(1, Math.round(w / 2)) + const ah = Math.max(1, Math.round(h / 2)) + this.ao.setSize(aw, ah) + this.aoBlur.setSize(aw, ah) + this.mask.setSize(w, h) + this.ldr.setSize(w, h) + ;(this.aoMat.uniforms.fullTexel?.value as Vector2).set(1 / w, 1 / h) + ;(this.maskMat.uniforms.invSize?.value as Vector2).set(1 / w, 1 / h) + const g = this.gradeMat.uniforms + if (g.aspect) g.aspect.value = width / Math.max(1, height) + ;(g.texel?.value as Vector2).set(1 / w, 1 / h) + if (g.edgePx) g.edgePx.value = 2 * pixelRatio + } + + private resizeFast(): void { + const w = Math.max(1, Math.round(this.width * this.scale)) + const h = Math.max(1, Math.round(this.height * this.scale)) + this.fast.setSize(w, h) + this.ldrFast.setSize(w, h) + } + + /** Resolution of moving frames as a fraction of the still frame (1 = same). The final pass upsamples them to the canvas. */ + get motionScale(): number { + return this.scale + } + + set motionScale(k: number) { + const v = Math.min(1, Math.max(0.25, Math.round(k * 20) / 20)) + if (v === this.scale) return + this.scale = v + this.resizeFast() + } + + render(scene: Scene, camera: PerspectiveCamera, opts: FrameOptions): void { + const r = this.renderer + const target = opts.fast ? this.fast : this.main + if (this.aoMat.uniforms.tDepth) this.aoMat.uniforms.tDepth.value = target.depthTexture + if (this.maskMat.uniforms.tDepth) this.maskMat.uniforms.tDepth.value = target.depthTexture + if (this.gradeMat.uniforms.tColor) this.gradeMat.uniforms.tColor.value = target.texture + r.setRenderTarget(target) + r.setClearColor(0x000000, 0) + r.clear(true, true, true) + r.render(scene, camera) + + const g = this.gradeMat.uniforms + const ao = opts.ao + if (ao) { + const u = this.aoMat.uniforms + if (u.proj) u.proj.value = camera.projectionMatrix + if (u.invProj) u.invProj.value = camera.projectionMatrixInverse + if (u.radius) u.radius.value = this.aoRadius + if (u.frame) u.frame.value = 0 + this.pass(this.aoMat, this.ao) + const b = this.blurMat.uniforms + if (b.tAO) b.tAO.value = this.ao.texture + ;(b.dir?.value as Vector2).set(1 / this.ao.width, 0) + this.pass(this.blurMat, this.aoBlur) + if (b.tAO) b.tAO.value = this.aoBlur.texture + ;(b.dir?.value as Vector2).set(0, 1 / this.ao.height) + this.pass(this.blurMat, this.ao) + } + if (g.aoOn) g.aoOn.value = ao ? 1 : 0 + if (g.aoStrength) g.aoStrength.value = this.aoStrength * opts.aoMix + if (g.exposure) g.exposure.value = this.exposure + + const outline = opts.outline.length > 0 + if (outline) this.renderMask(opts.outline, camera) + if (g.outlineOn) g.outlineOn.value = outline ? 1 : 0 + + if (this.fxaa) { + const ldr = opts.fast ? this.ldrFast : this.ldr + const gu = g.texel?.value as Vector2 + gu.set(1 / ldr.width, 1 / ldr.height) + if (g.edgePx) g.edgePx.value = 2 * this.pixelRatio * (ldr.width / this.width) + ;(this.fxaaMat.uniforms.resolution?.value as Vector2).set(1 / ldr.width, 1 / ldr.height) + if (this.fxaaMat.uniforms.tDiffuse) this.fxaaMat.uniforms.tDiffuse.value = ldr.texture + this.pass(this.gradeMat, ldr) + this.pass(this.fxaaMat, null) + } else { + this.pass(this.gradeMat, null) + } + } + + private pass(mat: Material, target: WebGLRenderTarget | null): void { + this.quad.material = mat + this.renderer.setRenderTarget(target) + this.quad.render(this.renderer) + } + + private renderMask(objects: readonly Object3D[], camera: Camera): void { + const r = this.renderer + r.setRenderTarget(this.mask) + r.setClearColor(0x000000, 0) + r.clear(true, false, false) + const swapped: { mesh: Mesh; mat: Material | Material[] }[] = [] + const hidden: Object3D[] = [] + for (const root of objects) { + root.traverse((o) => { + if ((o as Mesh).isMesh && o.visible) { + const m = o as Mesh + swapped.push({ mesh: m, mat: m.material }) + m.material = this.maskMat + } else if (o !== root && o.visible && !(o as Mesh).isMesh && (o.type === 'LineSegments' || o.type === 'Line')) { + hidden.push(o) + o.visible = false + } + }) + } + const prevAuto = r.shadowMap.autoUpdate + r.shadowMap.autoUpdate = false + for (const root of objects) r.render(root, camera) + r.shadowMap.autoUpdate = prevAuto + for (const s of swapped) s.mesh.material = s.mat + for (const h of hidden) h.visible = true + } + + dispose(): void { + this.main.depthTexture?.dispose() + this.main.dispose() + this.fast.depthTexture?.dispose() + this.fast.dispose() + + this.ao.dispose() + this.aoBlur.dispose() + this.mask.dispose() + this.ldr.dispose() + this.ldrFast.dispose() + this.aoMat.dispose() + this.blurMat.dispose() + this.maskMat.dispose() + this.gradeMat.dispose() + this.fxaaMat.dispose() + this.quad.dispose() + this.probe.dispose() + } + + get size(): { width: number; height: number; pixelRatio: number } { + return { width: this.width, height: this.height, pixelRatio: this.pixelRatio } + } +} diff --git a/desktop/src/vendor/slicerx/viewport/probe.ts b/desktop/src/vendor/slicerx/viewport/probe.ts new file mode 100644 index 00000000..956d63ef --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/probe.ts @@ -0,0 +1,171 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Frame probe for profiling: page frame times (requestAnimationFrame deltas), what each viewport render cost on the +// CPU and, where EXT_disjoint_timer_query_webgl2 exists, on the GPU, plus draw calls, triangles and live textures. +// Off unless asked for: `setProbe(true)` on the viewport, or localStorage `slicerx.probe` = 1 before it starts. +import type { WebGLRenderer } from 'three' + +export interface ProbeStats { + /** Wall time the probe covered, ms. */ + spanMs: number + /** Page frames seen (requestAnimationFrame callbacks). */ + pageFrames: number + /** Page frame deltas, ms. A long one is a dropped frame whatever caused it (render, React, layout). */ + pageMs: Spread + /** Frames the viewport drew. Zero while idle when rendering on demand works. */ + renders: number + /** CPU time of each viewport render (scene, passes and the calls that queue them), ms. */ + cpuMs: Spread + /** GPU time of each viewport render from timer queries, ms; null where the extension is missing. */ + gpuMs: Spread | null + /** Per render, from the last one. */ + drawCalls: number + triangles: number + /** Live textures and geometries the renderer holds now. */ + textures: number + geometries: number + programs: number +} + +export interface Spread { + n: number + mean: number + p50: number + p95: number + max: number +} + +interface TimerExt { + TIME_ELAPSED_EXT: number + GPU_DISJOINT_EXT: number +} + +export function spread(values: readonly number[]): Spread { + const s = values.slice().sort((a, b) => a - b) + const at = (q: number): number => (s.length ? (s[Math.min(s.length - 1, Math.floor(q * s.length))] as number) : 0) + const sum = s.reduce((a, b) => a + b, 0) + return { n: s.length, mean: s.length ? sum / s.length : 0, p50: at(0.5), p95: at(0.95), max: s.length ? (s[s.length - 1] as number) : 0 } +} + +/** True when the page asked for the probe (localStorage `slicerx.probe` = 1). */ +export function probeRequested(): boolean { + try { + return typeof localStorage !== 'undefined' && localStorage.getItem('slicerx.probe') === '1' + } catch { + return false + } +} + +export class FrameProbe { + private readonly gl: WebGL2RenderingContext + private readonly ext: TimerExt | null + private readonly pending: WebGLQuery[] = [] + private query: WebGLQuery | null = null + private raf = 0 + private last = 0 + private t0 = 0 + private page: number[] = [] + private cpu: number[] = [] + private gpu: number[] = [] + private renders = 0 + private calls = 0 + private tris = 0 + private cpuStart = 0 + + constructor(private readonly renderer: WebGLRenderer) { + this.gl = renderer.getContext() as WebGL2RenderingContext + this.ext = (this.gl.getExtension('EXT_disjoint_timer_query_webgl2') as TimerExt | null) ?? null + this.reset() + this.loop() + } + + get gpuTimer(): boolean { + return this.ext !== null + } + + private readonly onFrame = (now: number): void => { + if (this.last) this.page.push(now - this.last) + this.last = now + this.collect() + this.raf = requestAnimationFrame(this.onFrame) + } + + private loop(): void { + if (typeof requestAnimationFrame === 'function') this.raf = requestAnimationFrame(this.onFrame) + } + + /** Called by the viewport right before it draws a frame. */ + begin(): void { + this.cpuStart = performance.now() + if (!this.ext || this.query) return + const q = this.gl.createQuery() + if (!q) return + this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT, q) + this.query = q + } + + /** Called by the viewport right after the frame's last pass. */ + end(): void { + this.cpu.push(performance.now() - this.cpuStart) + this.renders++ + const info = this.renderer.info.render + this.calls = info.calls + this.tris = info.triangles + if (this.ext && this.query) { + this.gl.endQuery(this.ext.TIME_ELAPSED_EXT) + this.pending.push(this.query) + this.query = null + } + } + + /** Reads finished timer queries; a disjoint event (power state, context switch) voids the ones in flight. */ + private collect(): void { + if (!this.ext || this.pending.length === 0) return + const gl = this.gl + const disjoint = gl.getParameter(this.ext.GPU_DISJOINT_EXT) as boolean + while (this.pending.length) { + const q = this.pending[0] as WebGLQuery + if (!disjoint && !(gl.getQueryParameter(q, gl.QUERY_RESULT_AVAILABLE) as boolean)) break + this.pending.shift() + if (!disjoint) this.gpu.push((gl.getQueryParameter(q, gl.QUERY_RESULT) as number) / 1e6) + gl.deleteQuery(q) + } + } + + reset(): void { + this.page = [] + this.cpu = [] + this.gpu = [] + this.renders = 0 + this.last = 0 + this.t0 = performance.now() + } + + stats(): ProbeStats { + this.collect() + const mem = this.renderer.info.memory + return { + spanMs: performance.now() - this.t0, + pageFrames: this.page.length + (this.last ? 1 : 0), + pageMs: spread(this.page), + renders: this.renders, + cpuMs: spread(this.cpu), + gpuMs: this.ext ? spread(this.gpu) : null, + drawCalls: this.calls, + triangles: this.tris, + textures: mem.textures, + geometries: mem.geometries, + programs: this.renderer.info.programs?.length ?? 0, + } + } + + dispose(): void { + if (this.raf) cancelAnimationFrame(this.raf) + this.raf = 0 + if (this.query && this.ext) this.gl.endQuery(this.ext.TIME_ELAPSED_EXT) + for (const q of this.pending) this.gl.deleteQuery(q) + if (this.query) this.gl.deleteQuery(this.query) + this.pending.length = 0 + this.query = null + } +} diff --git a/desktop/src/vendor/slicerx/viewport/purge.ts b/desktop/src/vendor/slicerx/viewport/purge.ts new file mode 100644 index 00000000..4903d225 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/purge.ts @@ -0,0 +1,650 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// The purge at the chute, for Bambu Lab printers that flush there (docs/toolchanger-sim.md, "Purge"): +// - the flush of each change, read from the G-code the engine wrote: the extrusion between `; FLUSH_START` +// and `; FLUSH_END` (X1, P1, A1 extrude it themselves), or the virtual `;VG1` moves between +// `; VFLUSH_START` and `; VFLUSH_END` that stand for the firmware's own flush on the H2D and H2C, or +// failing both the length the change hands the firmware (`M620.10 A1 ... L`); +// - when it plays: at the end of the change's load, at the feed rates of those moves, until the head +// leaves over the wiper; +// - the blob: a soft coiled shape hanging from the nozzle whose volume is the plastic pushed out so far, +// its color running from the filament the nozzle held to the new one the way the purge mixes; the wiper +// catches it as the head leaves and it drops down the chute. +// Everything here is a pure function of the change's clock, so a scrub lands on the same frame both ways. +import { + BoxGeometry, + BufferAttribute, + BufferGeometry, + Color, + Group, + Mesh, + MeshPhysicalMaterial, + MeshStandardMaterial, + type Material, +} from 'three' +import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js' +import { displayHex } from './palette' +import { poseAt, type ChangeSequence, type ToolChangerSpec } from './toolchanger' + +// ---------- the flush in the G-code ---------- + +export interface FlushStep { + /** Filament pushed, mm. */ + e: number + /** Seconds at the move's feed rate. */ + seconds: number +} + +export interface Flush { + /** Filament pushed through at the chute, mm. */ + e: number + seconds: number + steps: FlushStep[] + /** Real extrusion moves, the virtual moves Bambu writes for a firmware flush, or the length handed to the firmware. */ + source: 'moves' | 'virtual' | 'firmware' +} + +const param = (words: string, letter: string): number | null => { + const m = new RegExp(`(?:^|\\s)${letter}(-?\\d*\\.?\\d+(?:e-?\\d+)?)`, 'i').exec(words) + return m ? Number(m[1]) : null +} + +/** + * The flush in the lines of one change, or null when it has none. `relative` is the extrusion mode in force + * where the lines start (Bambu prints in M83); M82, M83 and G92 inside are followed. + */ +export function flushOf(lines: Iterable, relative = true): Flush | null { + const real: FlushStep[] = [] + const virtual: FlushStep[] = [] + let firmware: FlushStep | null = null + let rel = relative + let lastE = 0 + let feed = 0 + let block: 'real' | 'virtual' | null = null + for (const raw of lines) { + const line = raw.trim() + if (!line) continue + if (line.startsWith(';')) { + const c = line.slice(1).trim() + if (/^FLUSH_START\b/.test(c)) block = 'real' + else if (/^VFLUSH_START\b/.test(c)) block = 'virtual' + else if (/^V?FLUSH_END\b/.test(c)) block = null + else if (block === 'virtual' && /^VG[01]\s/i.test(c)) { + const words = c.slice(3) + const e = param(words, 'E') + const f = param(words, 'F') + if (e !== null && e > 0) virtual.push({ e, seconds: f && f > 0 ? (e / f) * 60 : 0 }) + } + continue + } + const words = line.split(';')[0]!.trim() + const head = words.split(/\s+/)[0]!.toUpperCase() + if (head === 'M82') rel = false + else if (head === 'M83') rel = true + else if (head === 'G92') { + const e = param(words.slice(3), 'E') + if (e !== null) lastE = e + } else if (head === 'G0' || head === 'G1') { + const rest = words.slice(head.length) + const f = param(rest, 'F') + if (f !== null && f > 0) feed = f + const e = param(rest, 'E') + if (e === null) continue + const de = rel ? e : e - lastE + if (!rel) lastE = e + if (block === 'real' && de !== 0) real.push({ e: de, seconds: feed > 0 ? (Math.abs(de) / feed) * 60 : 0 }) + } else if (head === 'M620.10' && param(words.slice(7), 'A') === 1) { + const l = param(words.slice(7), 'L') + const f = param(words.slice(7), 'F') + if (l !== null && l > 0) firmware = { e: l, seconds: f && f > 0 ? (l / f) * 60 : 0 } + } + } + const pick = (steps: FlushStep[], source: Flush['source']): Flush | null => { + const e = steps.reduce((s, x) => s + x.e, 0) + return e > 0.01 ? { e, seconds: steps.reduce((s, x) => s + x.seconds, 0), steps, source } : null + } + return pick(real, 'moves') ?? pick(virtual, 'virtual') ?? (firmware ? pick([firmware], 'firmware') : null) +} + +/** Plastic volume of `e` mm of filament `diameter` mm across, mm3. */ +export function purgeVolume(e: number, diameter: number): number { + return Math.max(0, e) * Math.PI * (diameter / 2) ** 2 +} + +/** Grams of `volume` mm3 at `density` g/cm3. */ +export function purgeGrams(volume: number, density: number): number { + return (Math.max(0, volume) * Math.max(0, density)) / 1000 +} + +/** One change's purge as the playback shows it. */ +export interface PurgePlan { + /** The change's first segment (the change plays before it). */ + segment: number + /** Filament pushed, mm. */ + e: number + /** mm3. */ + volume: number + grams: number + /** The flush moves at their own feed rates. */ + steps: FlushStep[] + /** The filament the nozzle held (the purge starts in its color) and the new one; the same when the nozzle keeps its filament. */ + from: number + to: number +} + +/** + * The filament each purge starts with: what the purging nozzle last held. On the H2C a rack hotend keeps its + * filament, so a swap to it purges in its own color; a nozzle that changes filament purges from the old one + * to the new one. `first` is the tool the print starts with. + */ +export function purgeFromTools(spec: Pick, first: number, changes: readonly { from: number; to: number }[]): number[] { + const held = new Map() + const ex = (t: number) => spec.extruderOf[t] ?? 0 + const rack = spec.kind === 'hotend-rack' ? Math.max(...spec.extruderOf, 0) : -1 + held.set(ex(first), first) + return changes.map((c) => { + const e = ex(c.to) + const before = e === rack ? c.to : (held.get(e) ?? c.to) + held.set(e, c.to) + return before + }) +} + +// ---------- when it plays ---------- + +export interface PurgeWindow { + /** Seconds into the change: the flush starts, ends, and the head starts over the wiper. */ + start: number + end: number + kick: number +} + +/** + * The flush inside a change: at the end of the last load before the head leaves over the wiper, at the + * flush moves' own pace (squeezed into the load when they would take longer). Null for a change with no + * chute stop. + */ +export function purgeWindow(seq: ChangeSequence, seconds: number): PurgeWindow | null { + const wipe = seq.phases.findIndex((p) => p.name === 'wipe') + if (wipe < 0) return null + let load = -1 + for (let i = wipe - 1; i >= 0; i--) + if (seq.phases[i]!.name === 'load') { + load = i + break + } + if (load < 0) return null + const p = seq.phases[load]! + const end = p.t0 + p.move + p.dwell + return { start: Math.max(p.t0 + p.move, end - Math.max(0, seconds)), end, kick: seq.phases[wipe]!.t0 } +} + +/** Share of the flush out of the nozzle at `t` seconds into the change (0 to 1), following the moves' feed rates. */ +export function flushedShare(plan: Pick, w: PurgeWindow, t: number): number { + if (t <= w.start || plan.e <= 0) return 0 + if (t >= w.end) return 1 + const total = plan.steps.reduce((s, x) => s + x.seconds, 0) + const span = w.end - w.start + // Steps without a feed rate share the window by length. + if (total <= 0) return (t - w.start) / span + let clock = (t - w.start) * (total / span) + let e = 0 + for (const s of plan.steps) { + if (clock <= s.seconds) return Math.min(1, (e + (s.seconds > 0 ? (s.e * clock) / s.seconds : s.e)) / plan.e) + clock -= s.seconds + e += s.e + } + return 1 +} + +// ---------- the blob ---------- + +/** mm/s2. */ +const GRAVITY = 9810 +/** The wiper flicks the caught blob back into the chute (mm/s) and sets it turning (rad/s2), so its top clears the nozzle as it goes. */ +const KICK = { vy: 70, spin: 58 } +/** Fallen this far the blob is deep in the chute, out of view. */ +const FALL_OUT = 72 + +/** + * The chute and wiper, in mm from the nozzle tip over the chute (x right, y back, z up). The purge hangs in the + * air between the nozzle and the chute's mouth, which sits below the largest blob; the wiper is a short blade + * at the nozzle's height in front of it, on an arm from a post at the front rim's right, so the head leaving + * forward drags the blob into it. The blade's back face is flush with the inside of the front wall. + */ +export const CHUTE = { + x: [-17, 17] as const, + y: [-12, 18] as const, + wall: 2, + rim: -26, + depth: 80, + wiper: { x: [-6, 6] as const, y: [-13.4, -12] as const, z: [-3.4, -0.4] as const, holder: -4.6, arm: 12.6, post: [11.2, 12.6] as const }, +} as const + +export interface BlobState { + /** Nothing to draw, plastic on the nozzle, or plastic dropping down the chute. */ + phase: 'none' | 'growing' | 'falling' + /** mm3 in the blob. */ + volume: number + /** The whole flush, mm3. */ + total: number + /** World position of the blob's top (the nozzle tip while it hangs), mm. */ + at: [number, number, number] + /** Tumble about x since it left the nozzle, rad. */ + spin: number +} + +/** The blob's shape, from its volume alone; `seed` varies the lean and lumps from change to change. */ +export interface BlobShape { + positions: Float32Array + /** 0 to 1 per vertex: where the plastic at the vertex sits in the flush, first out to last out. */ + order: Float32Array + /** Per vertex 0 to 1: groove to crest of the coil. */ + rope: Float32Array + /** Per vertex 0 to 1: how far into the mix the new color shows there (low shows it early). */ + streak: Float32Array + index: Uint32Array + /** Furthest the shape reaches toward -y and its height below the tip, mm. */ + front: number + height: number +} + +const RINGS = 64 +const AROUND = 80 +const smoothstep = (a: number, b: number, x: number) => { + const u = Math.min(1, Math.max(0, (x - a) / (b - a))) + return u * u * (3 - 2 * u) +} + +/** Strand radius as it leaves a 0.4 mm nozzle at flush speed, and the coil's pitch, mm. */ +const STRAND = { r: 0.55, pitch: 1.2 } + +/** + * A soft pendant of coiled strand: a neck at the nozzle, a body that sags as it grows, helical coils with + * rounded crests and narrow grooves, a slight lean and lumps. Scaled across so the closed mesh holds exactly + * `volume` mm3. Deterministic in its arguments. + */ +export function blobShape(volume: number, total: number, seed = 0): BlobShape { + const V = Math.max(1e-3, volume) + // Small blobs sit as a bead on the tip; heavy ones sag. + const k = 0.8 + 0.7 * smoothstep(0, 450, V) + // A first guess of the body radius from a profile integral of about 0.53; the exact volume comes after. + const rb = Math.cbrt(V / (2 * Math.PI * k * 0.53)) + const H = Math.max(0.6, 2 * k * rb) + const neck = STRAND.r + const turns = H / STRAND.pitch + // Plastic winds out of the nozzle: the coils turn as the blob grows. + const twist = V / 55 + const lean = 0.16 * Math.sin(seed * 1.7 + 0.4) + const leanY = 0.06 * Math.cos(seed * 2.3) + const n = RINGS * AROUND + 2 + const pos = new Float32Array(n * 3) + const order = new Float32Array(n) + const rope = new Float32Array(n) + const streak = new Float32Array(n).fill(0.5) + const ringR = new Float64Array(RINGS) + const amp = Math.min(STRAND.r * 0.85, rb * 0.22) + for (let i = 0; i < RINGS; i++) { + const s = (i + 0.5) / RINGS + // A round-bottomed pendant, fullest a little below its middle where the coils pile up. + const u = Math.pow(s, 1.25) + const body = Math.pow(Math.max(0, 1 - Math.pow(Math.abs(2 * u - 1), 2.3)), 1 / 2.3) * (0.88 + 0.24 * s) + const R = rb * body + neck * Math.pow(1 - s, 6) + ringR[i] = R + const fade = smoothstep(0.02, 0.14, s) * smoothstep(1, 0.86, s) + const cx = lean * rb * Math.sin(Math.PI * s) + const cy = leanY * rb * Math.sin(Math.PI * s) + for (let j = 0; j < AROUND; j++) { + const th = (j / AROUND) * Math.PI * 2 + const wob = 0.16 * Math.sin(2 * th + seed + 3.1 * s) + 0.09 * Math.sin(3 * th - 1.3 * seed + 5 * s) + const phi = turns * s + th / (Math.PI * 2) + twist + wob + 0.3 * Math.sin(Math.PI * 1.3 * s + seed) + const crest = Math.pow(Math.abs(Math.sin(Math.PI * phi)), 0.55) * (0.78 + 0.22 * Math.sin(3 * th + 11 * s + seed)) + const lump = 1 + 0.07 * Math.sin(th + 0.7 * seed + 2.5 * s) + 0.055 * Math.sin(2 * th + 2.1 + seed + 4 * s) + 0.035 * Math.sin(3 * th - 1.3 + 7 * s - seed) + const r = Math.max(0.05, R * lump + amp * fade * (crest - 0.62)) + const v = i * AROUND + j + pos[3 * v] = cx + r * Math.cos(th) + pos[3 * v + 1] = cy + r * Math.sin(th) + pos[3 * v + 2] = -s * H + rope[v] = crest + // Where the new color shows through first: threads that run along the coil and drift around it. + streak[v] = 0.5 + 0.42 * Math.sin(Math.PI * 2 * phi + 2.2 * Math.sin(2 * th + 9 * s + seed)) * fade + } + } + const top = RINGS * AROUND + const bottom = top + 1 + pos[3 * top + 2] = 0 + pos[3 * bottom + 2] = -H + rope[top] = 1 + rope[bottom] = 1 + const tris: number[] = [] + for (let i = 0; i + 1 < RINGS; i++) + for (let j = 0; j < AROUND; j++) { + const a = i * AROUND + j + const b = i * AROUND + ((j + 1) % AROUND) + const c = (i + 1) * AROUND + j + const d = (i + 1) * AROUND + ((j + 1) % AROUND) + tris.push(a, c, b, b, c, d) + } + for (let j = 0; j < AROUND; j++) { + tris.push(top, j, (j + 1) % AROUND) + const l = (RINGS - 1) * AROUND + tris.push(bottom, l + ((j + 1) % AROUND), l + j) + } + const index = new Uint32Array(tris) + // Exactly `volume`: scale across the axis (x and y), which scales the enclosed volume by the square. + const f = Math.sqrt(V / Math.max(1e-9, meshVolume(pos, index))) + for (let v = 0; v < n; v++) { + pos[3 * v] = (pos[3 * v] ?? 0) * f + pos[3 * v + 1] = (pos[3 * v + 1] ?? 0) * f + } + // Order of the plastic: the first out is pushed to the bottom, the last is at the nozzle. + let above = 0 + const T = Math.max(V, total) + for (let i = 0; i < RINGS; i++) { + const R = (ringR[i] ?? 0) * f + const slab = Math.PI * R * R * (H / RINGS) + const q = (V - above - slab / 2) / T + above += slab + for (let j = 0; j < AROUND; j++) { + const v = i * AROUND + j + order[v] = Math.min(1, Math.max(0, q)) + } + } + order[top] = Math.min(1, V / T) + order[bottom] = 0 + let front = 0 + for (let v = 0; v < n; v++) front = Math.max(front, -(pos[3 * v + 1] ?? 0)) + return { positions: pos, order, rope, streak, index, front, height: H } +} + +/** Volume enclosed by a closed, outward wound triangle mesh, mm3. */ +export function meshVolume(pos: ArrayLike, index: ArrayLike): number { + let v = 0 + for (let t = 0; t + 2 < index.length; t += 3) { + const a = 3 * (index[t] ?? 0) + const b = 3 * (index[t + 1] ?? 0) + const c = 3 * (index[t + 2] ?? 0) + const ax = pos[a] ?? 0, ay = pos[a + 1] ?? 0, az = pos[a + 2] ?? 0 + const bx = pos[b] ?? 0, by = pos[b + 1] ?? 0, bz = pos[b + 2] ?? 0 + const cx = pos[c] ?? 0, cy = pos[c + 1] ?? 0, cz = pos[c + 2] ?? 0 + v += (ax * (by * cz - bz * cy) - ay * (bx * cz - bz * cx) + az * (bx * cy - by * cx)) / 6 + } + return v +} + +/** + * The blob at `t` seconds into the change: nothing before the flush, growing on the nozzle tip while it runs, + * dragged along by the head as it leaves until the wiper catches it (`front` is how far the blob reaches + * forward of the tip), then falling down the chute with the wiper's flick and out of view. A pure function + * of its arguments. + */ +export function blobAt(seq: ChangeSequence, plan: Pick, w: PurgeWindow, t: number, front: number, wiperY: number, exit: ChuteExit = 'front'): BlobState { + const none: BlobState = { phase: 'none', volume: 0, total: plan.volume, at: [0, 0, 0], spin: 0 } + if (t <= w.start || plan.volume <= 0) return none + const share = flushedShare(plan, w, t) + const volume = plan.volume * share + if (t < w.kick) { + const p = poseAt(seq, t) + return { phase: 'growing', volume, total: plan.volume, at: [p.x, p.y, p.z], spin: 0 } + } + // The head pulls the blob forward over the wiper; it lets go where the blob's front meets the wiper. + const caught = catchTime(seq, w.kick, front, wiperY, exit) + if (t < caught) { + const p = poseAt(seq, t) + return { phase: 'growing', volume, total: plan.volume, at: [p.x, p.y, p.z], spin: 0 } + } + const p = poseAt(seq, caught) + const dt = t - caught + const fall = 0.5 * GRAVITY * dt * dt + if (fall > FALL_OUT) return none + const [dx, dy] = EXIT[exit] + return { phase: 'falling', volume, total: plan.volume, at: [p.x - dx * KICK.vy * dt, p.y - dy * KICK.vy * dt, p.z - fall], spin: 0.5 * KICK.spin * dt * dt } +} + +/** Which way the head leaves the chute over the wiper. */ +export type ChuteExit = 'front' | 'right' +/** The leaving direction in bed coordinates, and the chute's turn about z from the H2 family's (which leaves to the front). */ +const EXIT: Record = { front: [0, -1], right: [1, 0] } +const TURN: Record = { front: 0, right: Math.PI / 2 } + +/** A point's position along the chute's back axis (opposite the leaving direction), mm. */ +const along = (x: number, y: number, exit: ChuteExit) => -(x * EXIT[exit][0] + y * EXIT[exit][1]) + +/** When the blob, carried by the head from `kick` on, first reaches the wiper. */ +function catchTime(seq: ChangeSequence, kick: number, front: number, wiperY: number, exit: ChuteExit): number { + const wipe = seq.phases.find((p) => p.name === 'wipe' && p.t0 >= kick - 1e-9) + if (!wipe) return kick + const end = wipe.t0 + wipe.move + const reach = (t: number) => { + const p = poseAt(seq, t) + return along(p.x, p.y, exit) - front + } + if (reach(kick) <= wiperY) return kick + if (reach(end) > wiperY) return end + let lo = kick + let hi = end + for (let i = 0; i < 40; i++) { + const mid = (lo + hi) / 2 + if (reach(mid) > wiperY) lo = mid + else hi = mid + } + return hi +} + +// ---------- drawing ---------- + +const chuteBlack = new MeshStandardMaterial({ color: new Color('#26272e'), metalness: 0.3, roughness: 0.55 }) +const chuteInside = new MeshStandardMaterial({ color: new Color('#0d0d10'), metalness: 0.1, roughness: 0.9 }) +const chuteSteel = new MeshStandardMaterial({ color: new Color('#a9aeb9'), metalness: 0.85, roughness: 0.32 }) +const wiperMat = new MeshStandardMaterial({ color: new Color('#3b3d47'), metalness: 0.02, roughness: 0.7 }) +const framePlastic = new MeshStandardMaterial({ color: new Color('#c9ccd3'), metalness: 0.05, roughness: 0.55 }) + +const slab = (mat: Material, x0: number, x1: number, y0: number, y1: number, z0: number, z1: number, name: string, r = 0): Mesh => { + const geo = r > 0 ? new RoundedBoxGeometry(x1 - x0, y1 - y0, z1 - z0, 2, r) : new BoxGeometry(x1 - x0, y1 - y0, z1 - z0) + const m = new Mesh(geo, mat) + m.position.set((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2) + m.name = name + return m +} + +/** + * The chute behind the bed and the purge blob. It stands still at the bed's level; on printers whose bed moves in z + * it comes up to the head's height while a change flushes into it, where it meets the head in bed coordinates. On the + * A1 and A1 mini it stays at the bed's level throughout (`chute.frame`). + */ +export class PurgeRig { + readonly root = new Group() + private readonly chute = new Group() + private exit: ChuteExit = 'front' + private mouth: { x: readonly [number, number]; y: readonly [number, number] } = CHUTE + private readonly blob: Mesh + private readonly geo = new BufferGeometry() + private readonly mat = new MeshPhysicalMaterial({ vertexColors: true, roughness: 0.24, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.07 }) + private spec: ToolChangerSpec | null = null + private colors: readonly string[] = [] + private lastKey = '' + private shapeKey = '' + private shape: BlobShape | null = null + + constructor() { + this.root.name = 'purge' + this.chute.name = 'chute' + this.blob = new Mesh(this.geo, this.mat) + this.blob.name = 'blob' + this.blob.castShadow = true + this.blob.frustumCulled = false + this.blob.visible = false + this.root.add(this.chute, this.blob) + this.root.visible = false + } + + set visible(on: boolean) { + this.root.visible = on + } + + get visible(): boolean { + return this.root.visible + } + + setSpec(spec: ToolChangerSpec | null): void { + const ch = spec?.chute + const key = ch ? `${ch.x}:${ch.y}:${ch.exit ?? 'front'}:${JSON.stringify(ch.mouth ?? null)}` : '' + this.spec = spec + if (key === this.lastKey) return + this.lastKey = key + for (const c of this.chute.children) (c as Mesh).geometry.dispose() + this.chute.clear() + this.exit = ch?.exit ?? 'front' + this.mouth = ch?.mouth ?? CHUTE + this.chute.rotation.z = TURN[this.exit] + if (ch?.frame) this.buildFrameChute() + else if (ch) this.buildChute() + } + + setColors(colors: readonly string[]): void { + this.colors = colors + this.shapeKey = '' + } + + /** + * The chute: an open shaft with a steel rim, its mouth `CHUTE.x` by `CHUTE.y` around the nozzle's spot and + * below the blob, dark inside so a falling blob fades into it; the wiper blade on its holder and posts at the + * front. Everything stays under the nozzle tip, so the head passes over it. Built facing the front and turned + * to the side the head leaves by; the mouth is the machine's where it has its own. + */ + private buildChute(): void { + const [x0, x1] = this.mouth.x + const [y0, y1] = this.mouth.y + const w = CHUTE.wall + const top = CHUTE.rim + const bot = top - CHUTE.depth + const wp = { ...CHUTE.wiper, y: [y0 - 1.4, y0] as const } + this.chute.add( + slab(chuteInside, x0 - w, x1 + w, y0 - w, y0, bot, top - 1.2, 'front wall'), + slab(chuteInside, x0 - w, x1 + w, y1, y1 + w, bot, top - 1.2, 'back wall'), + slab(chuteInside, x0 - w, x0, y0, y1, bot, top - 1.2, 'side wall'), + slab(chuteInside, x1, x1 + w, y0, y1, bot, top - 1.2, 'side wall'), + // Black anodized skin outside the walls, a hair apart so no face is shared. + slab(chuteBlack, x0 - w - 1.2, x1 + w + 1.2, y0 - w - 1.2, y0 - w - 0.01, bot, top - 1.2, 'skin'), + slab(chuteBlack, x0 - w - 1.2, x0 - w - 0.01, y0 - w - 0.01, y1 + w + 1.2, bot, top - 1.2, 'skin'), + slab(chuteBlack, x1 + w + 0.01, x1 + w + 1.2, y0 - w - 0.01, y1 + w + 1.2, bot, top - 1.2, 'skin'), + slab(chuteBlack, x0 - w - 0.01, x1 + w + 0.01, y1 + w + 0.01, y1 + w + 1.2, bot, top - 1.2, 'skin'), + // A brushed steel rim around the mouth. + slab(chuteSteel, x0 - w - 1.2, x1 + w + 1.2, y0 - w - 1.2, y0, top - 1.2, top, 'rim', 0.5), + slab(chuteSteel, x0 - w - 1.2, x1 + w + 1.2, y1, y1 + w + 1.2, top - 1.2, top, 'rim', 0.5), + slab(chuteSteel, x0 - w - 1.2, x0, y0 + 0.01, y1 - 0.01, top - 1.2, top, 'rim', 0.5), + slab(chuteSteel, x1, x1 + w + 1.2, y0 + 0.01, y1 - 0.01, top - 1.2, top, 'rim', 0.5), + // The wiper: a silicone blade at the nozzle's height on a steel arm, its post down to the front rim. + slab(wiperMat, wp.x[0], wp.x[1], wp.y[0], wp.y[1], wp.z[0], wp.z[1], 'wiper', 0.35), + slab(chuteSteel, wp.x[0], wp.arm, wp.y[0], wp.y[1], wp.holder, wp.z[0], 'arm', 0.3), + slab(chuteBlack, wp.post[0], wp.post[1], wp.y[0], wp.y[1], top, wp.holder, 'post'), + ) + this.chute.traverse((o) => void ((o as Mesh).isMesh && ((o as Mesh).receiveShadow = true))) + } + + /** + * The A1 and A1 mini chute, estimated from Bambu's product photos (docs/toolchanger-sim.md): a small, low shaft in + * the frame's light gray plastic at the bed's left, open below so the purge drops through, its mouth just under the + * bed's surface, with the wiper blade on a block at the side the head leaves by, toward the bed. + */ + private buildFrameChute(): void { + const [x0, x1] = this.mouth.x + const [y0, y1] = this.mouth.y + const w = CHUTE.wall + const top = -2 + const bot = top - 22 + const wp = { ...CHUTE.wiper, y: [y0 - w - 1.4, y0 - w] as const } + this.chute.add( + slab(framePlastic, x0 - w, x1 + w, y0 - w, y0, bot, top, 'front wall', 0.6), + slab(framePlastic, x0 - w, x1 + w, y1, y1 + w, bot, top, 'back wall', 0.6), + slab(framePlastic, x0 - w, x0, y0 + 0.01, y1 - 0.01, bot, top, 'side wall', 0.6), + slab(framePlastic, x1, x1 + w, y0 + 0.01, y1 - 0.01, bot, top, 'side wall', 0.6), + // The wiper: a silicone blade at the nozzle's height on a gray block against the front wall. + slab(wiperMat, wp.x[0], wp.x[1], wp.y[0], wp.y[1], wp.z[0], wp.z[1], 'wiper', 0.35), + slab(framePlastic, wp.x[0] - 1, wp.x[1] + 1, wp.y[0], wp.y[1], bot, wp.z[0] - 0.01, 'wiper block'), + ) + this.chute.traverse((o) => void ((o as Mesh).isMesh && ((o as Mesh).receiveShadow = true))) + } + + /** The blob's shape for a plan at `volume`, reused while the volume stands still. */ + shapeFor(plan: PurgePlan, volume: number): BlobShape { + const key = `${plan.segment}:${volume.toFixed(4)}:${plan.from}:${plan.to}` + if (this.shape && this.shapeKey === key) return this.shape + this.shape = blobShape(volume, plan.volume, plan.segment % 97) + this.shapeKey = key + this.upload(this.shape, plan) + return this.shape + } + + private colorOf(tool: number): Color { + return new Color(displayHex(this.colors[tool] ?? this.colors[this.colors.length - 1] ?? '#9aa4c1')) + } + + private upload(s: BlobShape, plan: PurgePlan): void { + const n = s.order.length + const col = new Float32Array(n * 3) + const a = this.colorOf(plan.from) + const b = this.colorOf(plan.to) + const c = new Color() + for (let v = 0; v < n; v++) { + // The purge runs old at first, mixes through the middle and comes out clean at the end. Two melts do not + // blend into one color: the new one shows as threads along the coil that thicken until they take over. + const m = smoothstep(0.08, 0.8, s.order[v] ?? 0) + const u = s.streak[v] ?? 0.5 + c.copy(a).lerp(b, smoothstep(u - 0.1, u + 0.1, m)) + // Grooves between the coils catch less light. + const shade = 0.7 + 0.3 * (s.rope[v] ?? 1) + col[3 * v] = c.r * shade + col[3 * v + 1] = c.g * shade + col[3 * v + 2] = c.b * shade + } + this.geo.setAttribute('position', new BufferAttribute(s.positions, 3)) + this.geo.setAttribute('color', new BufferAttribute(col, 3)) + this.geo.setIndex(new BufferAttribute(s.index, 1)) + this.geo.computeVertexNormals() + this.geo.computeBoundingBox() + this.geo.computeBoundingSphere() + } + + /** + * Places the chute at the head's height `z` and the blob for `seconds` into the change `seq` with its + * purge `plan`; without a change in progress only the chute shows. + */ + place(z: number, at: { seq: ChangeSequence; plan: PurgePlan; seconds: number } | null): BlobState | null { + const ch = this.spec?.chute + this.chute.visible = !!ch + this.blob.visible = false + if (!ch) return null + // The chute stands still on the frame. Where the bed drops in z (X1, P1, H2) it meets the head at the head's height + // in bed coordinates, so it comes up to it for a change and is back at the bed's level the rest of the print. + this.chute.position.set(ch.x, ch.y, ch.frame || !at ? 0 : z) + if (!at) return null + const w = purgeWindow(at.seq, totalSeconds(at.plan)) + if (!w) return null + const share = flushedShare(at.plan, w, at.seconds) + if (share <= 0) return null + const shape = this.shapeFor(at.plan, at.plan.volume * share) + const st = blobAt(at.seq, at.plan, w, at.seconds, shape.front, along(ch.x, ch.y, this.exit) + this.mouth.y[0], this.exit) + if (st.phase === 'none') return st + this.blob.visible = true + // The blob's top sits on the nozzle tip; falling, it turns about its middle, tipping back into the chute. + const mid = shape.height / 2 + const turn = TURN[this.exit] + const back = -Math.sin(st.spin) * mid + this.blob.rotation.set(st.spin, 0, turn, 'ZYX') + this.blob.position.set(st.at[0] - back * Math.sin(turn), st.at[1] + back * Math.cos(turn), st.at[2] + 0.05 - mid + Math.cos(st.spin) * mid) + this.blob.updateMatrix() + return st + } + + dispose(): void { + for (const c of this.chute.children) (c as Mesh).geometry.dispose() + this.geo.dispose() + this.mat.dispose() + } +} + +/** Seconds of a plan's flush moves at their feed rates. */ +export function totalSeconds(plan: Pick): number { + return plan.steps.reduce((s, x) => s + x.seconds, 0) +} diff --git a/desktop/src/vendor/slicerx/viewport/rings.ts b/desktop/src/vendor/slicerx/viewport/rings.ts new file mode 100644 index 00000000..54a1ceb1 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/rings.ts @@ -0,0 +1,219 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Rotation rings: the rotate tool's three rings and the cut plane's two tilt rings. Laid out as in +// OrcaSlicer's GLGizmoRotate3D (v2.4.2): one ring per axis around the selection's box center, a little +// wider than the box. A ring drag turns by the angle the cursor sweeps around the center on the +// ring's plane (GLGizmoRotate::on_dragging); a ring seen edge on turns by the cursor's travel along +// the ring's screen tangent instead. Everything is in bed coordinates (mm, Z up). The math is pure +// and unit tested; RingSet only draws. +import { BufferAttribute, BufferGeometry, Color, DoubleSide, Group, Matrix4, Mesh, MeshBasicMaterial, Quaternion, TorusGeometry, Vector3 } from 'three' +import type { V3 } from './scaling' + +export type RingAxis = 'x' | 'y' | 'z' +export type RotateSpace = 'world' | 'local' + +const dot = (a: V3, b: V3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +const sub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +const cross = (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +const len = (a: V3): number => Math.hypot(a[0], a[1], a[2]) +export const unit = (a: V3): V3 => { + const l = len(a) + return l > 1e-12 ? [a[0] / l, a[1] / l, a[2] / l] : [0, 0, 1] +} + +/** Signed angle in radians that turns `a` onto `b` about `n`, with `a` and `b` taken on the plane square to `n`. */ +export function angleAround(a: V3, b: V3, n: V3): number { + const flat = (v: V3): V3 => { + const k = dot(v, n) + return [v[0] - n[0] * k, v[1] - n[1] * k, v[2] - n[2] * k] + } + const fa = flat(a) + const fb = flat(b) + return Math.atan2(dot(cross(fa, fb), n), dot(fa, fb)) +} + +/** `raw` (in -PI to PI) moved by whole turns to land nearest `prev`, so a drag can go past half a turn. */ +export function unwrapAngle(prev: number, raw: number): number { + const turn = Math.PI * 2 + return raw + Math.round((prev - raw) / turn) * turn +} + +/** An angle in radians rounded to a step in degrees. */ +export function snapAngle(rad: number, stepDeg: number): number { + const step = (stepDeg * Math.PI) / 180 + return step > 0 ? Math.round(rad / step) * step : rad +} + +/** Where a ray meets the plane through `p` square to `n`, or null when it runs along the plane. */ +export function rayPlane(o: V3, d: V3, p: V3, n: V3): V3 | null { + const den = dot(d, n) + if (Math.abs(den) < 1e-9) return null + const t = dot(sub(p, o), n) / den + return t < 0 ? null : [o[0] + d[0] * t, o[1] + d[1] * t, o[2] + d[2] * t] +} + +/** Two unit vectors square to `n` and to each other, so (u, v, n) is right handed. */ +export function planeBasis(n: V3): [V3, V3] { + const a: V3 = Math.abs(n[2]) < 0.9 ? [0, 0, 1] : [1, 0, 0] + const u = unit(cross(a, n)) + return [u, cross(n, u)] +} + +/** + * Distance from a ray to the nearest point of a ring, and how far along the ray that point lies. + * Sampled: a ring seen edge on still has a nearest point, which a plane hit would miss. + */ +export function ringDistance(o: V3, d: V3, center: V3, axis: V3, radius: number, samples = 96): { dist: number; along: number } { + const [u, v] = planeBasis(axis) + const dd = dot(d, d) + let best = { dist: Infinity, along: Infinity } + for (let i = 0; i < samples; i++) { + const a = (i / samples) * Math.PI * 2 + const c = Math.cos(a) * radius + const s = Math.sin(a) * radius + const p: V3 = [center[0] + u[0] * c + v[0] * s, center[1] + u[1] * c + v[1] * s, center[2] + u[2] * c + v[2] * s] + const w = sub(p, o) + const t = Math.max(0, dot(w, d) / dd) + const q: V3 = [o[0] + d[0] * t, o[1] + d[1] * t, o[2] + d[2] * t] + const dist = len(sub(p, q)) + if (dist < best.dist) best = { dist, along: t } + } + return best +} + +/** The ring a ray picks: the nearest to the camera of those within `tol` mm, or null. */ +export function pickRing(o: V3, d: V3, center: V3, axes: readonly { id: K; axis: V3 }[], radius: number, tol: number): K | null { + let best: { id: K; along: number } | null = null + for (const r of axes) { + const h = ringDistance(o, d, center, r.axis, radius) + if (h.dist <= tol && (!best || h.along < best.along)) best = { id: r.id, along: h.along } + } + return best?.id ?? null +} + +/** The three rotation axes in bed coordinates: the bed's own, or the columns of the object's transform (scale removed). */ +export function ringAxes(m: ArrayLike, space: RotateSpace): Record { + if (space === 'world') return { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] } + const col = (i: number): V3 => unit([m[i * 4] ?? 0, m[i * 4 + 1] ?? 0, m[i * 4 + 2] ?? 0]) + const x = col(0) + const y = col(1) + // A mirrored object has a left handed frame; its z is taken from x and y so the rings stay a proper rotation. + return { x, y, z: unit(cross(x, y)) } +} + +/** Column-major transform `m` turned by `rad` about the line through `center` along unit `axis` (bed coordinates). */ +export function rotateAbout(m: ArrayLike, center: V3, axis: V3, rad: number): number[] { + const r = new Matrix4().makeTranslation(center[0], center[1], center[2]).multiply(new Matrix4().makeRotationAxis(new Vector3(...axis), rad)).multiply(new Matrix4().makeTranslation(-center[0], -center[1], -center[2])) + return new Matrix4().fromArray(Array.from(m)).premultiply(r).toArray() +} + +/** Turns a vector by `rad` about unit `axis`. */ +export function turnVector(v: V3, axis: V3, rad: number): V3 { + return new Vector3(...v).applyAxisAngle(new Vector3(...axis), rad).toArray() as V3 +} + +const RING_COLOR: Record = { x: '#ff6b6b', y: '#51cf66', z: '#4dabf7' } +const HOT = '#ffe066' +const FAN_STEPS = 360 + +/** + * The rings and the swept sector of a running drag. Lives in the bed frame (add `group` under the bed root). `place` + * is called from the render pass, so it only writes transforms and colors; geometry is built once. + */ +export class RingSet { + readonly group = new Group() + private readonly rings = new Map() + private readonly fan: Mesh + private hover: K | null = null + private active: K | null = null + + constructor(ids: readonly K[], colors: Partial> = RING_COLOR as Partial>) { + this.group.name = 'ring-gizmo' + this.group.visible = false + const torus = new TorusGeometry(1, 0.012, 6, 128) + for (const id of ids) { + const m = new Mesh(torus, new MeshBasicMaterial({ color: new Color(colors[id] ?? '#ffffff'), depthTest: false, transparent: true, opacity: 0.95, toneMapped: false })) + m.renderOrder = 10 + m.raycast = () => {} + m.userData.color = colors[id] ?? '#ffffff' + this.rings.set(id, m) + this.group.add(m) + } + // One triangle per degree; a drag shows the first |angle| of them. + const pos = new Float32Array(FAN_STEPS * 9) + for (let i = 0; i < FAN_STEPS; i++) { + const a0 = (i / FAN_STEPS) * Math.PI * 2 + const a1 = ((i + 1) / FAN_STEPS) * Math.PI * 2 + pos.set([0, 0, 0, Math.cos(a0), Math.sin(a0), 0, Math.cos(a1), Math.sin(a1), 0], i * 9) + } + const g = new BufferGeometry() + g.setAttribute('position', new BufferAttribute(pos, 3)) + this.fan = new Mesh(g, new MeshBasicMaterial({ color: new Color(HOT), side: DoubleSide, depthTest: false, transparent: true, opacity: 0.22, toneMapped: false })) + this.fan.renderOrder = 9 + this.fan.raycast = () => {} + this.fan.visible = false + this.group.add(this.fan) + } + + /** Puts ring `id` around `center` square to `axis`, `radius` mm wide. A ring left out of a call keeps its place. */ + place(id: K, center: V3, axis: V3, radius: number): void { + const m = this.rings.get(id) + if (!m) return + m.position.set(center[0], center[1], center[2]) + m.quaternion.setFromUnitVectors(new Vector3(0, 0, 1), new Vector3(...axis)) + m.scale.setScalar(radius) + ;(m.material as MeshBasicMaterial).color.set(id === (this.active ?? this.hover) ? HOT : (m.userData.color as string)) + } + + show(on: boolean): void { + this.group.visible = on + } + + /** Recolors ring `id`; a hovered or dragged ring keeps the hot color until it is placed again. */ + setColor(id: K, hex: string): void { + const m = this.rings.get(id) + if (!m) return + m.userData.color = hex + if (id !== (this.active ?? this.hover)) (m.material as MeshBasicMaterial).color.set(hex) + } + + get visible(): boolean { + return this.group.visible + } + + setHover(id: K | null): boolean { + if (id === this.hover) return false + this.hover = id + return true + } + + setActive(id: K | null): void { + this.active = id + if (id === null) this.fan.visible = false + } + + /** The sector swept by a drag: from `from` (a unit vector on the ring's plane) by `rad` about `axis`. */ + sweep(center: V3, axis: V3, from: V3, rad: number, radius: number): void { + const steps = Math.min(FAN_STEPS, Math.ceil((Math.abs(rad) * 180) / Math.PI)) + this.fan.visible = steps > 0 + if (!steps) return + // The fan always turns the positive way, so a negative sweep starts where it ends. + const start = rad < 0 ? turnVector(from, axis, rad) : from + const v = cross(axis, start) + const basis = new Matrix4().makeBasis(new Vector3(...start), new Vector3(...v), new Vector3(...axis)) + this.fan.quaternion.copy(new Quaternion().setFromRotationMatrix(basis)) + this.fan.position.set(center[0], center[1], center[2]) + this.fan.scale.setScalar(radius) + this.fan.geometry.setDrawRange(0, steps * 3) + } + + dispose(): void { + const geos = new Set() + for (const m of [...this.rings.values(), this.fan]) { + geos.add(m.geometry) + ;(m.material as MeshBasicMaterial).dispose() + } + for (const g of geos) g.dispose() + this.group.removeFromParent() + } +} diff --git a/desktop/src/vendor/slicerx/viewport/scaling.ts b/desktop/src/vendor/slicerx/viewport/scaling.ts new file mode 100644 index 00000000..4981c9aa --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/scaling.ts @@ -0,0 +1,202 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Scale gizmo math: how a handle drag becomes a scale factor and how a factor +// changes an object transform. Pure, so it is unit tested. + +export type V3 = [number, number, number] + +/** Factor limits of one drag, relative to the size when the drag began. */ +export const MIN_SCALE = 0.01 +export const MAX_SCALE = 50 +/** Snap step while Shift is held: 5 percent, as in OrcaSlicer. */ +export const SNAP_STEP = 0.05 + +function mul(a: number[], b: number[]): number[] { + const o = new Array(16).fill(0) + for (let c = 0; c < 4; c++) for (let r = 0; r < 4; r++) for (let k = 0; k < 4; k++) o[c * 4 + r] = (o[c * 4 + r] ?? 0) + (a[k * 4 + r] ?? 0) * (b[c * 4 + k] ?? 0) + return o +} + +/** + * Object transform after scaling its own axes by `factors` about `anchorLocal` (a point in the + * object's frame that stays where it is). `m` and the result are column-major 4x4. + */ +export function scaleTransform(m: number[], factors: V3, anchorLocal: V3): number[] { + const [sx, sy, sz] = factors + const [ax, ay, az] = anchorLocal + const s = [sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, sz, 0, ax * (1 - sx), ay * (1 - sy), az * (1 - sz), 1] + return mul(m, s) +} + +/** Parameter t of the point on the line P + t d nearest the ray O + s r (d and r need not be unit). Null when they are parallel. */ +export function nearestOnLine(rayO: V3, rayD: V3, lineP: V3, lineD: V3): number | null { + const w: V3 = [lineP[0] - rayO[0], lineP[1] - rayO[1], lineP[2] - rayO[2]] + const dot = (a: V3, b: V3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + const a = dot(lineD, lineD) + const b = dot(lineD, rayD) + const c = dot(rayD, rayD) + const d = dot(lineD, w) + const e = dot(rayD, w) + const den = a * c - b * b + if (Math.abs(den) < 1e-9 * a * c) return null + return (b * e - c * d) / den +} + +/** Scale factor of a drag: where the cursor projects now over where it projected at the start, both measured from the anchor. */ +export function dragFactor(tNow: number, tStart: number): number { + if (Math.abs(tStart) < 1e-6) return 1 + return clampScale(tNow / tStart) +} + +export function clampScale(f: number): number { + return Math.min(MAX_SCALE, Math.max(MIN_SCALE, f)) +} + +/** Rounds a factor to the nearest step, never below one step. */ +export function snapScale(f: number, step = SNAP_STEP): number { + return Math.max(step, Math.round(f / step) * step) +} + +export type HandleId = 'xn' | 'xp' | 'yn' | 'yp' | 'zn' | 'zp' | 'cnn' | 'cpn' | 'cpp' | 'cnp' +export type ScaleLayout = 'bottom' | 'faces' + +/** + * Handle ids of a layout. `bottom` (Orca, Bambu Studio): x and y handles at the middle of the bottom edges, one z handle + * on top, four uniform handles at the bottom corners. `faces` (PrusaSlicer): all six face centers and four corners at + * the middle height. `n` and `p` are the negative and positive side. + */ +export function handleIds(layout: ScaleLayout): readonly HandleId[] { + return layout === 'faces' ? ['xn', 'xp', 'yn', 'yp', 'zn', 'zp', 'cnn', 'cpn', 'cpp', 'cnp'] : ['xn', 'xp', 'yn', 'yp', 'zp', 'cnn', 'cpn', 'cpp', 'cnp'] +} + +export function handleAxis(id: HandleId): 'x' | 'y' | 'z' | 'uniform' { + return id[0] === 'c' ? 'uniform' : (id[0] as 'x' | 'y' | 'z') +} + +/** Position of a handle on the box `min..max`, in the box's own frame. */ +export function handleLocal(id: HandleId, min: V3, max: V3, layout: ScaleLayout = 'bottom'): V3 { + const cx = (min[0] + max[0]) / 2 + const cy = (min[1] + max[1]) / 2 + const cz = (min[2] + max[2]) / 2 + const low = layout === 'faces' ? cz : min[2] + switch (id) { + case 'xn': return [min[0], cy, low] + case 'xp': return [max[0], cy, low] + case 'yn': return [cx, min[1], low] + case 'yp': return [cx, max[1], low] + case 'zn': return [cx, cy, min[2]] + case 'zp': return [cx, cy, max[2]] + case 'cnn': return [min[0], min[1], low] + case 'cpn': return [max[0], min[1], low] + case 'cpp': return [max[0], max[1], low] + default: return [min[0], max[1], low] + } +} + +const OPPOSITE: Record = { xn: 'xp', xp: 'xn', yn: 'yp', yp: 'yn', zn: 'zp', zp: null, cnn: 'cpp', cpn: 'cnp', cpp: 'cnn', cnp: 'cpn' } + +/** The handle that a pinned drag keeps fixed. The z handle of the `bottom` layout pins the bottom center instead. */ +export function oppositeHandle(id: HandleId, layout: ScaleLayout): HandleId | null { + return id === 'zp' && layout === 'faces' ? 'zn' : OPPOSITE[id] +} + +export interface ScaleOrigin { + layout: ScaleLayout + pivot: 'bottom-center' | 'center' + cornerPinLocksZ: boolean +} + +function basePivot(min: V3, max: V3, pivot: 'bottom-center' | 'center'): V3 { + return [(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, pivot === 'center' ? (min[2] + max[2]) / 2 : min[2]] +} + +/** + * The point a drag keeps fixed. Unpinned it is the layout's pivot. Pinned, an axis handle keeps the opposite handle where it + * is, and (when `cornerPinLocksZ`) a corner keeps the opposite corner in x and y. + */ +export function pivotFor(id: HandleId, min: V3, max: V3, o: ScaleOrigin, pinned: boolean): V3 { + const base = basePivot(min, max, o.pivot) + if (!pinned) return base + const axis = handleAxis(id) + if (axis === 'uniform') { + if (!o.cornerPinLocksZ) return base + const opp = oppositeHandle(id, o.layout) + const p = opp ? handleLocal(opp, min, max, o.layout) : base + return [p[0], p[1], base[2]] + } + const opp = oppositeHandle(id, o.layout) + if (!opp || (id === 'zp' && o.layout === 'bottom')) return base + return handleLocal(opp, min, max, o.layout) +} + +/** The pivot a drag's ratio is measured from: only a pinned axis handle moves it off the layout's pivot. */ +export function ratioPivotFor(id: HandleId, min: V3, max: V3, o: ScaleOrigin, pinned: boolean): V3 { + return handleAxis(id) === 'uniform' ? basePivot(min, max, o.pivot) : pivotFor(id, min, max, o, pinned) +} + +/** Per-axis factors: one axis for an axis handle, all three for a corner (x and y only for a pinned corner that locks z). */ +export function factorsFor(id: HandleId, f: number, pinnedCornerLocksZ: boolean): V3 { + switch (handleAxis(id)) { + case 'x': return [f, 1, 1] + case 'y': return [1, f, 1] + case 'z': return [1, 1, f] + default: return [f, f, pinnedCornerLocksZ ? 1 : f] + } +} + +/** The factor below which a drag would leave less than `minSizeMm` (PrusaSlicer keeps at least 1 mm). `sizesMm` are the box sizes in world mm. */ +export function minFactorFor(id: HandleId, sizesMm: V3, minSizeMm: number | null): number { + if (minSizeMm === null) return 0 + const axis = handleAxis(id) + const size = axis === 'x' ? sizesMm[0] : axis === 'y' ? sizesMm[1] : axis === 'z' ? sizesMm[2] : Math.min(...sizesMm) + return size > 0 ? minSizeMm / size : 0 +} + +// ---- how the pointer becomes a ratio, one function per source ---- + +const dot3 = (a: V3, b: V3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +const sub3 = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +const norm3 = (a: V3): V3 => { + const l = Math.hypot(...a) || 1 + return [a[0] / l, a[1] / l, a[2] / l] +} + +/** PrusaSlicer: where the handle line meets the pointer, measured from the start of the drag: (len + (t - tStart)) / len. */ +export function ratioLine(tNow: number, tStart: number, len: number): number { + return len > 0 ? (len + (tNow - tStart)) / len : 1 +} + +/** Bambu Studio: the point of the ray nearest the handle's start position, projected on the pivot to handle direction. */ +export function ratioPoint(rayO: V3, rayD: V3, drag: V3, pivot: V3): number { + const start = sub3(drag, pivot) + const len = Math.hypot(...start) + if (len === 0) return 1 + const d = norm3(rayD) + const k = dot3(sub3(drag, rayO), d) / dot3(d, d) + const near: V3 = [rayO[0] + k * d[0], rayO[1] + k * d[1], rayO[2] + k * d[2]] + return (len + dot3(sub3(near, drag), norm3(start))) / len +} + +/** + * Orca: the ray meets the plane through the handle's start position whose normal is the box's up axis (for the z handle, a + * plane containing that axis and facing the ray), and the offset is projected on the pivot to handle direction. A ray + * nearly parallel to the plane (85 to 95 degrees) leaves the ratio at 1. + */ +export function ratioPlane(rayO: V3, rayD: V3, drag: V3, pivot: V3, up: V3, isZHandle: boolean): number { + const start = sub3(drag, pivot) + const len = Math.hypot(...start) + if (len === 0) return 1 + const d = norm3(rayD) + let n = norm3(up) + if (isZHandle) { + const cross = (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] + n = norm3(cross(cross(d, n), n)) + } + const angle = (Math.acos(Math.max(-1, Math.min(1, dot3(n, d)))) * 180) / Math.PI + if (angle > 85 && angle < 95) return 1 + const denom = dot3(n, d) + if (Math.abs(denom) < 1e-12) return 1 + const t = dot3(n, sub3(drag, rayO)) / denom + const hit: V3 = [rayO[0] + t * d[0], rayO[1] + t * d[1], rayO[2] + t * d[2]] + return (len + dot3(sub3(hit, drag), norm3(start))) / len +} diff --git a/desktop/src/vendor/slicerx/viewport/stage.ts b/desktop/src/vendor/slicerx/viewport/stage.ts new file mode 100644 index 00000000..11a64cea --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/stage.ts @@ -0,0 +1,643 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// The studio set: generated room environment (PMREM, no HDR files), key light +// with soft PCF shadows, cool rim light, the textured build plate, the floor +// grid and the baked contact shadow under objects. +// --------------------------------------------------------------------------------------------------------------- +// MODIFIED BY SNAPMAKER STUDIO (DVOpenLabs/snapmaker-studio): the only change in this file is the import path of the +// contracts module ('@slicerx/contracts' -> '../contracts/index'). Upstream: slicerx-oss/slicerx @ +// edb521fe41306dd60d01bda8a0f6bf8aa54fcb29 (Apache-2.0). See ../UPDATING.md. +// --------------------------------------------------------------------------------------------------------------- +import { + BufferGeometry, + DoubleSide, + Sprite, + SpriteMaterial, + type PerspectiveCamera, + CanvasTexture, + Line, + LineBasicMaterial, + ShapeGeometry, + Vector2, + Color, + CubeCamera, + HalfFloatType, + DirectionalLight, + Group, + Matrix4, + Mesh, + MeshBasicMaterial, + OneFactor, + OneMinusSrcAlphaFactor, + OrthographicCamera, + PCFShadowMap, + PMREMGenerator, + PlaneGeometry, + Scene, + Shape, + ShaderMaterial, + CustomBlending, + DataTexture, + LinearFilter, + LinearMipmapLinearFilter, + MeshStandardMaterial, + RepeatWrapping, + RGBAFormat, + Vector3, + WebGLCubeRenderTarget, + WebGLRenderTarget, + type Object3D, + type Texture, + type WebGLRenderer, +} from 'three' +import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js' +import { LightProbeGenerator } from 'three/addons/lights/LightProbeGenerator.js' +import { FullScreenQuad } from 'three/addons/postprocessing/Pass.js' +import type { Bed } from '../contracts/index' +import { SCENE, type SceneColors } from './palette' +import type { PlateStyle } from './types' + +/** Objects sit this far above the plate top so their bottoms never fight it for depth. */ +export const LIFT_MM = 0.02 +/** + * The floor overlays (the plate outline and grid, nozzle zones, excluded areas, the contact shadow) all lie at + * FLOOR_Y, under the bed root's lift, so the first layer's beads (which start at LIFT_MM) never share a depth with + * them. They had sat a few thousandths of a millimetre apart around LIFT_MM, closer than a depth buffer resolves at + * a normal viewing distance, and the floor flickered against the first layer as the view moved. Being transparent + * and writing no depth, the overlays stack by render order alone, and a polygon offset keeps them behind any bead. + */ +export const FLOOR_Y = 0 +export const FLOOR_ORDER = { plate: -4, fill: -3, line: -2, contact: 1 } as const +/** Pushes a floor overlay back in depth, so a bead at the same depth always draws over it. */ +const FLOOR_OFFSET = { polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 2 } as const + +const CONTACT_BLUR_FS = /* glsl */ ` +uniform sampler2D tDiffuse; uniform vec2 dir; varying vec2 vUv; +void main(){ + vec4 s = vec4(0.0); + s += texture2D(tDiffuse, vUv - 4.0*dir)*0.051; s += texture2D(tDiffuse, vUv - 3.0*dir)*0.0918; + s += texture2D(tDiffuse, vUv - 2.0*dir)*0.12245; s += texture2D(tDiffuse, vUv - dir)*0.1531; + s += texture2D(tDiffuse, vUv)*0.1633; s += texture2D(tDiffuse, vUv + dir)*0.1531; + s += texture2D(tDiffuse, vUv + 2.0*dir)*0.12245; s += texture2D(tDiffuse, vUv + 3.0*dir)*0.0918; + s += texture2D(tDiffuse, vUv + 4.0*dir)*0.051; + gl_FragColor = s; +}` + +const CONTACT_DEPTH_FS = /* glsl */ ` +uniform float darkness; uniform float range; varying float vH; +void main(){ gl_FragColor = vec4(0.0, 0.0, 0.0, min(1.0, max(clamp(1.0 - vH / range, 0.0, 1.0) * darkness, 0.6))); }` + +const CONTACT_DEPTH_VS = /* glsl */ ` +varying float vH; +void main(){ vec4 w = modelMatrix * vec4(position, 1.0); vH = w.y; gl_Position = projectionMatrix * viewMatrix * w; }` + +const PLATE_OUTLINE_FS = /* glsl */ ` +uniform vec3 edge; uniform vec3 edgeAlt; uniform float alert; uniform float ground; uniform float surface; uniform vec3 grid; uniform vec2 hb; varying vec2 vP; +float lines(vec2 p, float s){ vec2 q = p / s; vec2 w = fwidth(q); vec2 g = abs(fract(q - 0.5) - 0.5) / max(w, vec2(1e-4)); return (1.0 - min(min(g.x, g.y), 1.0)) * (1.0 - smoothstep(0.3, 0.7, max(w.x, w.y))); } +void main(){ + vec2 q = abs(vP) - hb; + float d = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0); + float px = max(fwidth(d), 1e-3); + float line = 1.0 - smoothstep(0.0, 1.0, abs(d) / (px * 1.1)); + float glow = exp(-abs(d) / 2.2) * (d < 0.0 ? 0.18 : 0.1); + // Four identical L brackets starting exactly at each corner, both legs inside the outline. + vec2 c = hb - abs(vP); + float inset = 1.1, th = 0.8, len = 14.0; + float bx = (1.0 - smoothstep(th, th + px, abs(c.y - inset))) * step(0.0, c.x) * (1.0 - smoothstep(len, len + px, c.x)); + float by = (1.0 - smoothstep(th, th + px, abs(c.x - inset))) * step(0.0, c.y) * (1.0 - smoothstep(len, len + px, c.y)); + float br = max(bx, by); + vec2 r = abs(vP) / hb; + float fade = 1.0 - smoothstep(0.35, 1.0, max(r.x, r.y)); + // ground: no outline or corner marks, the grid runs to the quad's edge and fades out there. + float inside = mix(1.0 - smoothstep(-0.4, 0.0, d), 1.0, ground); + // On a plate surface the grid is a faint guide over the sheet. + float gl = (lines(vP + hb, 10.0) * 0.35 + lines(vP + hb, 50.0) * 0.75) * fade * inside * 0.3 * (1.0 - 0.7 * surface); + float inner = exp(d / 10.0) * inside * 0.045 * (1.0 - ground); + float aEdge = clamp(line * 0.9 + glow + br * 0.7, 0.0, 1.0) * (1.0 - ground); + float aG = clamp(gl + inner, 0.0, 1.0); + float a = clamp(aEdge + aG * (1.0 - aEdge), 0.0, 1.0); + vec3 col = (mix(edge, edgeAlt, alert) * aEdge + grid * aG * (1.0 - aEdge)); + gl_FragColor = vec4(col, a); +}` + +/** How each build plate surface looks: base color, roughness, how coarse its texture is, and a touch of metal. */ +const PLATE_SURFACES: Record, { color: string; roughness: number; grain: number; metalness: number }> = { + 'textured-pei': { color: '#7a6a4f', roughness: 0.7, grain: 1, metalness: 0.2 }, + 'smooth-pei': { color: '#8a7552', roughness: 0.32, grain: 0.12, metalness: 0.25 }, + cool: { color: '#2c2f36', roughness: 0.5, grain: 0.25, metalness: 0 }, + engineering: { color: '#383b42', roughness: 0.72, grain: 0.75, metalness: 0.05 }, +} + +/** Fine random grain for a plate surface, tiled across it: the speckle of a textured sheet, faint on a smooth one. */ +function grainTexture(): DataTexture { + const n = 128 + const data = new Uint8Array(n * n * 4) + let seed = 7 + for (let i = 0; i < n * n; i++) { + seed = (seed * 1103515245 + 12345) >>> 0 + const v = 96 + ((seed >>> 16) & 127) + data.set([v, v, v, 255], i * 4) + } + const t = new DataTexture(data, n, n, RGBAFormat) + t.wrapS = RepeatWrapping + t.wrapT = RepeatWrapping + t.magFilter = LinearFilter + t.minFilter = LinearMipmapLinearFilter + t.generateMipmaps = true + t.needsUpdate = true + return t +} + +/** An area only one nozzle can reach, in bed coordinates (mm, origin front left). */ +export interface NozzleZone { + id: string + label: string + color: string + polygon: [number, number][] +} + +/** The irradiance bake ended after its stage was disposed; nothing is wrong, the result is just not wanted. */ +export class StageDisposedError extends Error { + constructor() { + super('The stage was disposed before the environment bake finished') + this.name = 'StageDisposedError' + } +} + +export class Stage { + readonly scene = new Scene() + /** Bed frame: Z up, mm, origin at the bed's front left corner. Everything slicer-side hangs here. */ + readonly bedRoot = new Group() + readonly objectsRoot = new Group() + readonly previewRoot = new Group() + readonly key: DirectionalLight + readonly rim: DirectionalLight + bed: Bed = { widthMm: 256, depthMm: 256, heightMm: 256 } + private decor = new Group() + private zoneGroup = new Group() + private outline: ShaderMaterial | null = null + private zoneLabels: { sprite: Sprite; centre: Vector3; thin: Vector3 }[] = [] + private alert = false + private ground = false + private zones: readonly NozzleZone[] = [] + private zoneDisposables: { dispose(): void }[] = [] + private excluded: readonly (readonly [number, number])[][] = [] + private excludeGroup = new Group() + private excludeDisposables: { dispose(): void }[] = [] + private envTex: Texture | null = null + private contact: { + plane: Mesh + rt: WebGLRenderTarget + rtb: WebGLRenderTarget + cam: OrthographicCamera + mat: ShaderMaterial + blur: ShaderMaterial + quad: FullScreenQuad + size: number + } | null = null + private label = 'Textured PEI' + private plateStyle: PlateStyle = 'grid' + private colors: SceneColors = SCENE + private disposables: { dispose(): void }[] = [] + + constructor( + private readonly renderer: WebGLRenderer, + private readonly weak: boolean, + ) { + renderer.shadowMap.enabled = true + renderer.shadowMap.type = PCFShadowMap + renderer.shadowMap.autoUpdate = false + + const pm = new PMREMGenerator(renderer) + const room = new RoomEnvironment() + // Prefiltering runs before the first frame; on a software renderer the 256 px cube took about 140 ms of it. + this.envTex = pm.fromScene(room, 0.04, 0.1, 100, { size: weak ? 128 : 256 }).texture + pm.dispose() + this.scene.environment = this.envTex + this.envSH = this.bakeSH(room).finally(() => room.dispose()) + + // Intensities are the concept's legacy-light values times pi (three.js now uses physical units). + const key = new DirectionalLight(new Color(0xfff3e6), 1.6 * Math.PI) + key.position.set(-150, 300, 190) + key.castShadow = true + const sz = weak ? 1024 : 2048 + key.shadow.mapSize.set(sz, sz) + key.shadow.bias = -0.00025 + key.shadow.normalBias = 0.35 + key.shadow.radius = 3 + this.scene.add(key, key.target) + this.key = key + const rim = new DirectionalLight(new Color(0xb7c3ff), 0.75 * Math.PI) + rim.position.set(180, 140, -260) + this.scene.add(rim) + this.rim = rim + + this.bedRoot.matrixAutoUpdate = false + this.bedRoot.add(this.objectsRoot, this.previewRoot) + this.scene.add(this.decor, this.bedRoot) + this.setBed(this.bed, this.label) + } + + /** Bed coordinates (Z up, front left origin) to three.js world (Y up, bed center at origin). */ + /** Spherical-harmonic irradiance of the room environment, for materials that skip the prefiltered map. */ + readonly envSH: Promise + + /** The cube target the irradiance bake reads back, until the bake ends or the stage is disposed. */ + private shTarget: WebGLCubeRenderTarget | null = null + private disposed = false + + /** + * Runs once per stage. The read back spans several frames (one async read per cube face), so the stage can be + * disposed, and the renderer with it, before it ends: then the target was already released by `dispose` while the + * renderer still knew it. Releasing it again after `renderer.dispose()` makes three.js look up framebuffers it has + * forgotten and throw. + */ + private async bakeSH(room: Scene): Promise { + const rt = new WebGLCubeRenderTarget(32, { type: HalfFloatType }) + this.shTarget = rt + const cam = new CubeCamera(0.1, 100, rt) + cam.update(this.renderer, room) + try { + const probe = await LightProbeGenerator.fromCubeRenderTarget(this.renderer, rt) + if (this.disposed) throw new StageDisposedError() + return probe.sh.coefficients.map((c) => c.clone()) + } finally { + this.releaseShTarget(rt) + } + } + + private releaseShTarget(rt: WebGLCubeRenderTarget): void { + if (this.shTarget !== rt) return + this.shTarget = null + rt.dispose() + } + + bedMatrix(): Matrix4 { + const { widthMm: W, depthMm: D } = this.bed + return new Matrix4().set(1, 0, 0, -W / 2, 0, 0, 1, LIFT_MM, 0, -1, 0, D / 2, 0, 0, 0, 1) + } + + setBed(bed: Bed, label?: string): void { + const same = bed.widthMm === this.bed.widthMm && bed.depthMm === this.bed.depthMm && (label ?? this.label) === this.label && this.decor.children.length > 0 + this.bed = { ...bed } + if (label !== undefined) this.label = label + this.bedRoot.matrix.copy(this.bedMatrix()) + this.bedRoot.matrixWorldNeedsUpdate = true + if (same) return + for (const d of this.disposables) d.dispose() + this.disposables = [] + this.decor.clear() + this.buildPlate() + this.buildContact() + const span = Math.max(bed.widthMm, bed.depthMm) * 0.75 + const sc = this.key.shadow.camera + sc.left = -span + sc.right = span + sc.top = span + sc.bottom = -span + sc.near = 60 + sc.far = 800 + Math.max(0, bed.heightMm - 256) + sc.updateProjectionMatrix() + this.renderer.shadowMap.needsUpdate = true + } + + /** + * What the bed looks like under the print: `grid` is the outline and grid on the floor; the others lay a lit build + * plate surface under them (textured or smooth PEI, a cool plate, an engineering plate). Rebuilds the plate decor. + */ + setPlateStyle(style: PlateStyle): void { + if (style === this.plateStyle) return + this.plateStyle = style + this.setSceneColors(this.colors) + } + + /** Bed and floor colors. Rebuilds the plate decor. */ + setSceneColors(colors: SceneColors): void { + this.colors = colors + for (const d of this.disposables) d.dispose() + this.disposables = [] + this.decor.clear() + this.buildPlate() + this.buildContact() + this.renderer.shadowMap.needsUpdate = true + } + + /** Areas only one nozzle reaches, drawn as tinted floor patches (bed coordinates, mm, origin front left). */ + setNozzleZones(zones: readonly NozzleZone[]): void { + this.zones = zones + for (const d of this.zoneDisposables) d.dispose() + this.zoneDisposables = [] + this.zoneGroup.clear() + this.zoneLabels = [] + this.buildZones() + } + + /** + * Parts of the bed nothing may print on (the printer's `bed_exclude_area`), as polygons in bed coordinates (mm, + * origin front left). Drawn once as hatched patches with an outline; nothing about them changes per frame. + */ + setExcludedAreas(areas: readonly (readonly [number, number])[][]): void { + this.excluded = areas + for (const d of this.excludeDisposables) d.dispose() + this.excludeDisposables = [] + this.excludeGroup.clear() + const { widthMm: W, depthMm: D } = this.bed + const color = new Color(this.colors.floorGrid) + for (const poly of areas) { + if (poly.length < 3) continue + const geo = new ShapeGeometry(new Shape(poly.map(([x, y]) => new Vector2(x - W / 2, D / 2 - y)))).rotateX(Math.PI / 2) + const mat = new ShaderMaterial({ + uniforms: { col: { value: color } }, + transparent: true, + depthWrite: false, + side: DoubleSide, + vertexShader: 'varying vec2 vP; void main(){ vP = position.xz; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }', + // Diagonal hatching 2.5 mm apart over a faint wash, antialiased with the screen derivative. + fragmentShader: 'uniform vec3 col; varying vec2 vP; void main(){ float s = (vP.x + vP.y) / 2.5; float w = fwidth(s); float f = abs(fract(s) - 0.5); float stripe = 1.0 - smoothstep(0.16 - w, 0.16 + w, f); float a = 0.08 + stripe * 0.26; gl_FragColor = vec4(col * a, a); }', + blending: CustomBlending, + blendSrc: OneFactor, + blendDst: OneMinusSrcAlphaFactor, + blendSrcAlpha: OneFactor, + blendDstAlpha: OneMinusSrcAlphaFactor, + ...FLOOR_OFFSET, + }) + const fill = new Mesh(geo, mat) + fill.position.y = FLOOR_Y + fill.renderOrder = FLOOR_ORDER.fill + fill.name = 'excluded-area' + const loop: Vector3[] = poly.map(([x, y]) => new Vector3(x - W / 2, FLOOR_Y, D / 2 - y)) + const lg = new BufferGeometry().setFromPoints([...loop, loop[0] as Vector3]) + const lm = new LineBasicMaterial({ color, transparent: true, opacity: 0.65, depthWrite: false, toneMapped: false }) + const line = new Line(lg, lm) + line.renderOrder = FLOOR_ORDER.line + this.excludeGroup.add(fill, line) + this.excludeDisposables.push(geo, mat, lg, lm) + } + } + + /** The outline turns orange while an object sits off the bed. */ + /** Design draws a plain ground grid at bed level: no bed outline, corner marks, nozzle zones or excluded areas. */ + setGround(on: boolean): void { + this.ground = on + if (this.outline?.uniforms.ground) this.outline.uniforms.ground.value = on ? 1 : 0 + this.zoneGroup.visible = !on + this.excludeGroup.visible = !on + } + + setBedAlert(on: boolean): void { + this.alert = on + if (this.outline?.uniforms.alert) this.outline.uniforms.alert.value = on ? 1 : 0 + } + + /** Brightens one zone (by id) and leaves the others as they were; null resets all. */ + setZoneHighlight(id: string | null): void { + for (const o of this.zoneGroup.children) { + const on = id !== null && o.userData.zone === id + const m = (o as Mesh).material as { opacity?: number; uniforms?: { boost?: { value: number } } } + if (o.type === 'Line' && m.opacity !== undefined) m.opacity = on ? 1 : 0.8 + else if (m.uniforms?.boost) m.uniforms.boost.value = on ? 1.7 : 1 + } + } + + private buildZones(): void { + const { widthMm: W, depthMm: D } = this.bed + for (const z of this.zones) { + if (z.polygon.length < 3) continue + const color = new Color(z.color) + const xs = z.polygon.map((p) => p[0] - W / 2) + const zs = z.polygon.map((p) => D / 2 - p[1]) + const [x0, x1, z0, z1] = [Math.min(...xs), Math.max(...xs), Math.min(...zs), Math.max(...zs)] + // The strip runs along the bed edge it touches: full tint at its inner boundary, fading to the bed edge. + const alongX = x1 - x0 < z1 - z0 + const outerIsLow = alongX ? x0 <= -W / 2 + 0.5 : z0 <= -D / 2 + 0.5 + const geo = new ShapeGeometry(new Shape(z.polygon.map(([x, y]) => new Vector2(x - W / 2, D / 2 - y)))).rotateX(Math.PI / 2) + const mat = new ShaderMaterial({ + uniforms: { col: { value: color }, lo: { value: alongX ? x0 : z0 }, hi: { value: alongX ? x1 : z1 }, axisX: { value: alongX ? 1 : 0 }, outerLow: { value: outerIsLow ? 1 : 0 }, boost: { value: 1 } }, + transparent: true, + depthWrite: false, + side: DoubleSide, + vertexShader: 'varying vec2 vP; void main(){ vP = position.xz; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }', + fragmentShader: 'uniform vec3 col; uniform float lo; uniform float hi; uniform float axisX; uniform float outerLow; uniform float boost; varying vec2 vP; void main(){ float t = clamp(((axisX > 0.5 ? vP.x : vP.y) - lo) / max(hi - lo, 1e-3), 0.0, 1.0); float inner = outerLow > 0.5 ? t : 1.0 - t; float a = mix(0.07, 0.3, inner) * boost; gl_FragColor = vec4(col * a, a); }', + blending: CustomBlending, + blendSrc: OneFactor, + blendDst: OneMinusSrcAlphaFactor, + blendSrcAlpha: OneFactor, + blendDstAlpha: OneMinusSrcAlphaFactor, + ...FLOOR_OFFSET, + }) + const fill = new Mesh(geo, mat) + fill.position.y = FLOOR_Y + fill.renderOrder = FLOOR_ORDER.fill + const loop: Vector3[] = z.polygon.map(([x, y]) => new Vector3(x - W / 2, FLOOR_Y, D / 2 - y)) + const lg = new BufferGeometry().setFromPoints([...loop, loop[0] as Vector3]) + const lm = new LineBasicMaterial({ color, transparent: true, opacity: 0.8, depthWrite: false, toneMapped: false }) + const line = new Line(lg, lm) + line.renderOrder = FLOOR_ORDER.line + fill.userData.zone = z.id + line.userData.zone = z.id + this.zoneGroup.add(fill, line) + this.zoneDisposables.push(geo, mat, lg, lm) + // A screen-space mono label at the middle of the strip: horizontal, 11 px, faded out when the strip gets too thin. + if (typeof document !== 'undefined') { + const cv = document.createElement('canvas') + cv.width = 384 + cv.height = 64 + const g = cv.getContext('2d') + if (g) { + g.font = '500 36px ui-monospace, Menlo, monospace' + g.textAlign = 'center' + g.textBaseline = 'middle' + g.fillStyle = z.color + g.fillText(z.label, 192, 34) + } + const tex = new CanvasTexture(cv) + const lmat = new SpriteMaterial({ map: tex, transparent: true, depthWrite: false, depthTest: false, sizeAttenuation: false, toneMapped: false, opacity: 0.8 }) + const label = new Sprite(lmat) + label.position.set((x0 + x1) / 2, 0.3, (z0 + z1) / 2) + label.renderOrder = 5 + label.userData.zone = z.id + this.zoneGroup.add(label) + const thin = alongX ? new Vector3(x1 - x0, 0, 0) : new Vector3(0, 0, z1 - z0) + this.zoneLabels.push({ sprite: label, centre: label.position.clone(), thin }) + this.zoneDisposables.push(tex, lmat) + } + } + } + + /** Keeps the zone labels 11 px tall whatever the camera does, and hides one while its strip is under 40 px wide on screen. */ + updateZoneLabels(camera: PerspectiveCamera, heightPx: number): void { + if (this.zoneLabels.length === 0) return + const k = 2 * Math.tan((camera.fov * Math.PI) / 360) + const cssH = 16 + const p0 = new Vector3() + const p1 = new Vector3() + for (const l of this.zoneLabels) { + l.sprite.scale.set((cssH * 6) / heightPx * k, (cssH / heightPx) * k, 1) + const world = this.decor.localToWorld(l.centre.clone()) + p0.copy(world).project(camera) + p1.copy(world).add(l.thin).project(camera) + const px = Math.hypot((p1.x - p0.x) * camera.aspect, p1.y - p0.y) * 0.5 * heightPx + const m = l.sprite.material + m.opacity = px < 120 ? 0 : 0.8 + } + } + + /** + * The bed is an empty floor: a thin glowing outline of the printable area with corner marks and a faint grid + * that fades toward the edges, all in one transparent quad, so nothing is shaded and no texture is sampled. + */ + private buildPlate(): void { + const bed = this.bed + const half = new Vector2(bed.widthMm / 2, bed.depthMm / 2) + const pad = 24 + const mat = new ShaderMaterial({ + uniforms: { edge: { value: new Color(this.colors.selection) }, edgeAlt: { value: new Color(this.colors.overhangAmber) }, alert: { value: this.alert ? 1 : 0 }, ground: { value: this.ground ? 1 : 0 }, surface: { value: this.plateStyle === 'grid' ? 0 : 1 }, grid: { value: new Color(this.colors.floorGrid) }, hb: { value: half } }, + transparent: true, + depthWrite: false, + vertexShader: 'varying vec2 vP; void main(){ vP = position.xy; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }', + fragmentShader: PLATE_OUTLINE_FS, + ...FLOOR_OFFSET, + blending: CustomBlending, + blendSrc: OneFactor, + blendDst: OneMinusSrcAlphaFactor, + blendSrcAlpha: OneFactor, + blendDstAlpha: OneMinusSrcAlphaFactor, + }) + if (this.plateStyle !== 'grid') { + const look = PLATE_SURFACES[this.plateStyle] + const grain = grainTexture() + // One grain tile every 6 mm reads as a textured sheet at a normal distance and stays fine up close. + grain.repeat.set(bed.widthMm / 6, bed.depthMm / 6) + const surfMat = new MeshStandardMaterial({ color: new Color(look.color), roughness: look.roughness, metalness: look.metalness, roughnessMap: grain, bumpMap: grain, bumpScale: 0.6 * look.grain, envMapIntensity: 0.8 }) + const surfGeo = new PlaneGeometry(bed.widthMm, bed.depthMm) + const surf = new Mesh(surfGeo, surfMat) + surf.rotation.x = -Math.PI / 2 + // Just under the floor overlays, so the outline, zones and contact shadow draw over it. + surf.position.y = FLOOR_Y - 0.05 + surf.receiveShadow = true + surf.renderOrder = FLOOR_ORDER.plate - 1 + surf.name = 'plate-surface' + this.decor.add(surf) + this.disposables.push(surfGeo, surfMat, grain) + } + const geo = new PlaneGeometry(bed.widthMm + pad * 2, bed.depthMm + pad * 2) + const quad = new Mesh(geo, mat) + // Plane xy is bed xz: lie it flat with +y up. + quad.rotation.x = -Math.PI / 2 + quad.position.y = FLOOR_Y + quad.renderOrder = FLOOR_ORDER.plate + this.outline = mat + this.decor.add(quad) + this.decor.add(this.zoneGroup) + this.decor.add(this.excludeGroup) + this.setNozzleZones(this.zones) + this.setExcludedAreas(this.excluded) + this.disposables.push(geo, mat) + } + + private buildContact(): void { + const bed = this.bed + const SZ = Math.max(bed.widthMm, bed.depthMm) + 34 + const RES = this.weak ? 512 : 1024 + const rt = new WebGLRenderTarget(RES, RES) + const rtb = new WebGLRenderTarget(RES, RES) + rt.texture.generateMipmaps = false + rtb.texture.generateMipmaps = false + const planeGeo = new PlaneGeometry(SZ, SZ).rotateX(Math.PI / 2) + const planeMat = new MeshBasicMaterial({ map: rt.texture, transparent: true, opacity: 0.95, depthWrite: false, toneMapped: false, ...FLOOR_OFFSET }) + const plane = new Mesh(planeGeo, planeMat) + plane.scale.y = -1 + plane.position.y = FLOOR_Y + plane.renderOrder = FLOOR_ORDER.contact + this.decor.add(plane) + const cam = new OrthographicCamera(-SZ / 2, SZ / 2, SZ / 2, -SZ / 2, 0, 22) + cam.rotation.x = Math.PI / 2 + cam.updateMatrixWorld() + const mat = new ShaderMaterial({ uniforms: { darkness: { value: 2.1 }, range: { value: 22 } }, vertexShader: CONTACT_DEPTH_VS, fragmentShader: CONTACT_DEPTH_FS, depthTest: false, depthWrite: false, transparent: true }) + const blur = new ShaderMaterial({ + uniforms: { tDiffuse: { value: null }, dir: { value: [0, 0] } }, + vertexShader: 'varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }', + fragmentShader: CONTACT_BLUR_FS, + depthTest: false, + depthWrite: false, + }) + const quad = new FullScreenQuad(blur) + this.contact = { plane, rt, rtb, cam, mat, blur, quad, size: RES } + this.disposables.push(rt, rtb, planeGeo, planeMat, mat, blur, quad) + } + + setContactVisible(on: boolean): void { + if (this.contact) this.contact.plane.visible = on + } + + private contactDirty = false + + /** Objects moved: the contact shadow is baked again before the next frame, once however many moves come first. */ + requestContact(): void { + this.contactDirty = true + } + + /** Bakes the contact shadow if objects moved since the last bake. The viewport calls it before each frame. */ + bakePendingContact(): void { + if (!this.contactDirty) return + this.contactDirty = false + this.bakeContact() + } + + /** Renders the objects from below the plate, darker where they are closer, and blurs it. */ + bakeContact(): void { + const C = this.contact + if (!C) return + const r = this.renderer + const sc = this.scene + const hidden: Object3D[] = [] + sc.traverse((o) => { + if (o.visible && (o === this.decor || o === this.previewRoot || o.type === 'LineSegments')) { + hidden.push(o) + o.visible = false + } + }) + const prevOverride = sc.overrideMaterial + const prevEnv = sc.environment + sc.overrideMaterial = C.mat + r.setRenderTarget(C.rt) + r.setClearColor(0x000000, 0) + r.clear(true, true, true) + r.render(sc, C.cam) + sc.overrideMaterial = prevOverride + sc.environment = prevEnv + for (const o of hidden) o.visible = true + const blur = (amt: number): void => { + const u = C.blur.uniforms + if (u.tDiffuse) u.tDiffuse.value = C.rt.texture + if (u.dir) u.dir.value = [amt / C.size, 0] + r.setRenderTarget(C.rtb) + r.clear(true, false, false) + C.quad.render(r) + if (u.tDiffuse) u.tDiffuse.value = C.rtb.texture + if (u.dir) u.dir.value = [0, amt / C.size] + r.setRenderTarget(C.rt) + r.clear(true, false, false) + C.quad.render(r) + } + // A halo about 8 mm wide around the footprint, then progressively finer passes to remove banding. + blur(9) + blur(4.5) + blur(2) + blur(0.8) + r.setRenderTarget(null) + } + + dispose(): void { + if (this.disposed) return + this.disposed = true + // Released here, while the renderer is alive; the bake's own release then does nothing. + if (this.shTarget) this.releaseShTarget(this.shTarget) + for (const d of [...this.disposables, ...this.zoneDisposables, ...this.excludeDisposables]) d.dispose() + this.disposables = [] + this.zoneDisposables = [] + this.excludeDisposables = [] + this.envTex?.dispose() + this.key.shadow.map?.dispose() + } +} diff --git a/desktop/src/vendor/slicerx/viewport/strikes.ts b/desktop/src/vendor/slicerx/viewport/strikes.ts new file mode 100644 index 00000000..2437eb5d --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/strikes.ts @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// The strike: heimdall's mark where the machine would meet a printed part. The slicerx X drawn as two offset +// perimeters per stroke, cracked at the point of contact, inside a ring. Drawn over the toolpaths at a fixed size on +// screen, so a strike inside a part still shows. +import { CanvasTexture, Group, Sprite, SpriteMaterial, type Texture } from 'three' + +export interface StrikeMark { + /** Bed frame, mm. */ + x: number + y: number + z: number + /** Only inside the profile's clearance radius: drawn in the warning color. */ + close?: boolean + /** The strike the list has selected: drawn larger. */ + selected?: boolean + /** Before the layer it starts on, picked or pointed at in the list: a faint mark that shows where to look. */ + ghost?: boolean +} + +/** The outline under every mark. */ +const OUTLINE = '#15161c' + +/** Screen share of a strike's width, and of the selected one's. */ +const SIZE = 0.05 +const SELECTED = 0.075 + +/** The strike on a 128 px canvas in `color`; null where there is no canvas (tests in Node). */ +function strikeTexture(color: string): Texture | null { + if (typeof document === 'undefined') return null + const c = document.createElement('canvas') + c.width = c.height = 128 + const g = c.getContext('2d') + if (!g) return null + g.translate(64, 64) + g.scale(2, 2) + g.lineCap = 'round' + // A dark outline under the ring and the X, so the mark reads on a part of its own color (an amber close call on + // an orange print). + const strokes: [number, number, number, number][] = [ + [-17.5, -14.5, -5.5, -2.5], [3.5, 6.5, 14.5, 17.5], [-14.5, -17.5, -2.5, -5.5], [6.5, 3.5, 17.5, 14.5], + [14.5, -17.5, 3.5, -6.5], [-6.5, 3.5, -17.5, 14.5], [17.5, -14.5, 6.5, -3.5], [-3.5, 6.5, -14.5, 17.5], + ] + g.strokeStyle = OUTLINE + g.lineWidth = 4.4 + g.beginPath() + g.arc(0, 0, 27, 0, Math.PI * 2) + g.stroke() + g.lineWidth = 5.2 + g.beginPath() + for (const [x0, y0, x1, y1] of strokes) { + g.moveTo(x0, y0) + g.lineTo(x1, y1) + } + g.stroke() + g.strokeStyle = color + g.lineWidth = 2 + g.beginPath() + g.arc(0, 0, 27, 0, Math.PI * 2) + g.stroke() + g.globalAlpha = 0.18 + g.fillStyle = color + g.beginPath() + g.arc(0, 0, 20, 0, Math.PI * 2) + g.fill() + g.globalAlpha = 1 + g.lineWidth = 2.8 + // Each stroke of the X as two parallel perimeters, broken at the center where it lands. + g.beginPath() + for (const [x0, y0, x1, y1] of strokes) { + g.moveTo(x0, y0) + g.lineTo(x1, y1) + } + g.stroke() + g.fillStyle = '#ffffff' + g.rotate(Math.PI / 4) + g.fillRect(-2.6, -2.6, 5.2, 5.2) + const t = new CanvasTexture(c) + t.needsUpdate = true + return t +} + +export class Strikes { + readonly root = new Group() + private readonly materials = new Map() + private colors = { hit: '#ff4b5c', close: '#ffb86c' } + + constructor() { + this.root.name = 'strikes' + this.root.renderOrder = 10 + } + + /** The colors of hits and close calls (the theme's overhang red and amber). */ + setColors(hit: string, close: string): void { + if (hit === this.colors.hit && close === this.colors.close) return + this.colors = { hit, close } + this.disposeMaterials() + } + + private material(color: string, ghost = false): SpriteMaterial { + const key = ghost ? `${color} ghost` : color + let m = this.materials.get(key) + if (!m) { + m = new SpriteMaterial({ map: strikeTexture(color), color: 0xffffff, depthTest: false, depthWrite: false, transparent: true, opacity: ghost ? 0.35 : 1, sizeAttenuation: false }) + this.materials.set(key, m) + } + return m + } + + /** Places one strike per mark; null or an empty list clears them. */ + set(marks: readonly StrikeMark[] | null): void { + this.root.clear() + for (const m of marks ?? []) { + const s = new Sprite(this.material(m.close ? this.colors.close : this.colors.hit, m.ghost)) + s.name = `${m.selected ? 'strike selected' : 'strike'}${m.ghost ? ' ghost' : ''}` + s.position.set(m.x, m.y, m.z) + const k = m.selected ? SELECTED : SIZE + s.scale.set(k, k, 1) + s.renderOrder = m.selected ? 12 : 11 + this.root.add(s) + } + } + + private disposeMaterials(): void { + for (const m of this.materials.values()) { + m.map?.dispose() + m.dispose() + } + this.materials.clear() + } + + dispose(): void { + this.root.clear() + this.disposeMaterials() + } +} diff --git a/desktop/src/vendor/slicerx/viewport/summary.ts b/desktop/src/vendor/slicerx/viewport/summary.ts new file mode 100644 index 00000000..f5636ddd --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/summary.ts @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Numbers for preview legends, computed from the same buffers the renderer draws. +// --------------------------------------------------------------------------------------------------------------- +// MODIFIED BY SNAPMAKER STUDIO (DVOpenLabs/snapmaker-studio): the only change in this file is the import path of the +// contracts module ('@slicerx/contracts' -> '../contracts/index'). Upstream: slicerx-oss/slicerx @ +// edb521fe41306dd60d01bda8a0f6bf8aa54fcb29 (Apache-2.0). See ../UPDATING.md. +// --------------------------------------------------------------------------------------------------------------- +import { SXPV_SEGMENT_BYTES, type PreviewBuffers } from '../contracts/index' + +export interface PreviewSummary { + /** Extruded path length per feature id, mm. */ + featureMm: number[] + /** Extrusion time per feature id, seconds (path length over speed). */ + featureTimeS: number[] + /** Extruded path length per tool index, mm. */ + toolMm: number[] + speedRange: [number, number] + flowRange: [number, number] + layerTimeRange: [number, number] + widthRange: [number, number] + heightRange: [number, number] + /** Sum of the per-layer times, seconds. */ + totalTimeS: number +} + +export function summarizePreview(b: PreviewBuffers): PreviewSummary { + const S = b.segmentCount + const f32 = new Float32Array(b.raw, b.segmentsOffset, (S * SXPV_SEGMENT_BYTES) / 4) + const u8 = new Uint8Array(b.raw, b.segmentsOffset, S * SXPV_SEGMENT_BYTES) + const u16 = new Uint16Array(b.raw, b.segmentsOffset, (S * SXPV_SEGMENT_BYTES) / 2) + const featureMm = new Array(16).fill(0) + const featureTimeS = new Array(16).fill(0) + const toolMm: number[] = [] + let smin = Infinity, smax = 0, fmin = Infinity, fmax = 0, wmin = Infinity, wmax = 0, hmin = Infinity, hmax = 0 + for (let i = 0; i < S; i++) { + const o = i * 8 + const len = Math.hypot((f32[o + 2] ?? 0) - (f32[o] ?? 0), (f32[o + 3] ?? 0) - (f32[o + 1] ?? 0)) + const feat = u8[i * 32 + 24] ?? 0 + const tool = u8[i * 32 + 25] ?? 0 + featureMm[feat] = (featureMm[feat] ?? 0) + len + while (toolMm.length <= tool) toolMm.push(0) + toolMm[tool] = (toolMm[tool] ?? 0) + len + const sp = (u16[i * 16 + 13] ?? 0) * 0.1 + if (sp > 0) featureTimeS[feat] = (featureTimeS[feat] ?? 0) + len / sp + const w = (u16[i * 16 + 10] ?? 0) * 0.001 + const h = (u16[i * 16 + 11] ?? 0) * 0.001 + if (w > 0) { wmin = Math.min(wmin, w); wmax = Math.max(wmax, w) } + if (h > 0) { hmin = Math.min(hmin, h); hmax = Math.max(hmax, h) } + const fl = f32[o + 7] ?? 0 + if (sp > 0) { smin = Math.min(smin, sp); smax = Math.max(smax, sp) } + if (fl > 0) { fmin = Math.min(fmin, fl); fmax = Math.max(fmax, fl) } + } + let tmin = Infinity, tmax = 0, total = 0 + for (let k = 0; k < b.layerCount; k++) { + const t = b.layerTimeS[k] ?? 0 + tmin = Math.min(tmin, t) + tmax = Math.max(tmax, t) + total += t + } + const fin = (v: number): number => (Number.isFinite(v) ? v : 0) + return { featureMm, featureTimeS, toolMm, speedRange: [fin(smin), smax], flowRange: [fin(fmin), fmax], layerTimeRange: [fin(tmin), tmax], widthRange: [fin(wmin), wmax], heightRange: [fin(hmin), hmax], totalTimeS: total } +} diff --git a/desktop/src/vendor/slicerx/viewport/toolchanger.ts b/desktop/src/vendor/slicerx/viewport/toolchanger.ts new file mode 100644 index 00000000..779b34f9 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/toolchanger.ts @@ -0,0 +1,803 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// How a printer changes tools, as a sequence Preview can play: where the toolhead goes, what it parks +// and picks, and how long each step takes. Three mechanisms are modeled, each from the machine's own +// profile, firmware configuration or documentation (docs/toolchanger-sim.md lists what is measured and +// what is estimated): +// +// - dual-nozzle (Bambu Lab H2D): two hotends on one toolhead; the switch happens at the purge chute at +// the back, where the idle nozzle lifts and the other comes down. +// - hotend-rack (Bambu Lab H2C): the right hotend is swapped from a rack on the right side of the +// chamber, two rows of three positions; the filament is cut and flushed at the chute before and after. +// - tool-rack (Snapmaker U1): four toolheads park in a dock across the back; the carriage pushes the one +// it carries into its slot, releases it, and pulls the next one out. +// - lift-switch (UltiMaker S series): two print cores in one head; the left one is fixed, the right one +// rides on the lift switch. The head stops at the switching position the slicer writes, the firmware +// runs the switch's lever into the switch bay on the right wall and along it, which lowers or lifts the +// right core, and the head comes back out. +// - filament-swap (Bambu Lab A1, A1 mini, X1, P1, H2S): one nozzle; the AMS swaps the filament. The head goes to +// the cutter, then to the purge chute, flushes, and leaves over the wiper. +// +// Moves are timed with trapezoidal velocity profiles from the printer's speed and acceleration limits, +// so the head never jumps. The firmware's own work (cutting, loading, flushing, latching) is a dwell of +// the seconds the slicer counts for the change (`fixedSeconds`, from `ChangeClock`), spent where the +// machine spends it. Positions are bed coordinates in mm, origin at the front left corner, z up. +// --------------------------------------------------------------------------------------------------------------- +// MODIFIED BY SNAPMAKER STUDIO (DVOpenLabs/snapmaker-studio): the only change in this file is the import path of the +// contracts module ('@slicerx/contracts' -> '../contracts/index'). Upstream: slicerx-oss/slicerx @ +// edb521fe41306dd60d01bda8a0f6bf8aa54fcb29 (Apache-2.0). See ../UPDATING.md. +// --------------------------------------------------------------------------------------------------------------- +import type { Bed, PreviewBuffers } from '../contracts/index' + +export type V3 = [number, number, number] + +export type ToolChangerKind = 'dual-nozzle' | 'hotend-rack' | 'tool-rack' | 'xl-dock' | 'lift-switch' | 'filament-swap' + +export interface MotionLimits { + /** mm/s */ + speed: number + /** mm/s2 */ + accel: number +} + +export interface ToolChangerSpec { + kind: ToolChangerKind + bed: Bed + /** Filament slots the print uses (tool bytes 0 to tools - 1). */ + tools: number + /** 0-based extruder of each tool (`filament_map`); a tool-rack has one extruder per tool. */ + extruderOf: number[] + travel: MotionLimits + z: MotionLimits + /** Slow moves at a dock or rack. */ + dock: MotionLimits + /** Height the head lifts above the top layer for the change, mm. */ + liftMm: number + /** + * The change G-code lifts over the highest layer printed so far (`max_layer_z`), as the makers' own do, so a change + * printed by object clears the finished objects (the engine's collision check reads the same). + */ + liftOverPrint?: boolean + /** Fixed seconds the profile gives the firmware's work: the switch, a load and an unload. */ + seconds: { switch: number; load: number; unload: number } + /** Bambu: the purge chute and nozzle wiper, where the nozzle flushes over it, and the Y stops of the exit moves written after the change. */ + chute?: { + x: number + y: number + exitY: number[] + /** Which way the head leaves over the wiper: toward the front (the H2 family) or to the right (X1, P1, A1). */ + exit?: 'front' | 'right' + /** The wipe and exit stops after the flush where they are not straight to the front; the first one takes the purge past the wiper. */ + exits?: [number, number][] + /** The cutter, the head's first stop (null y keeps the head's y); none where the firmware cuts at the chute. */ + cut?: [number, number | null] + /** + * A1, A1 mini: the chute stands on the frame, which neither the bed (moving in y) nor the gantry (moving in z) + * carries. Preview holds the bed still, so the chute stays at its flush spot at bed level: the change moves the + * bed to that y before it flushes, so the head meets it there. + */ + frame?: boolean + /** The mouth around the nozzle's spot, x across and y back from the wiper side, where it differs from the H2 family's (`CHUTE`). */ + mouth?: { x: [number, number]; y: [number, number] } + } + /** H2D: distance between the two nozzles and how far the idle one lifts. */ + nozzles?: { spacing: number; liftMm: number } + /** H2C: the rack on the right wall. Slot k sits at row floor(k / 3), ys[k % 3]. */ + rack?: { x: number; ys: number[]; rowRise: number; approachX: number; latchY: number; slots: number } + /** U1: dock slots along the back, from the printer's Klipper configuration. */ + docks?: { x: number[]; y: number; idleY: number; strokeX: number; retractX: number; bufferMm: number; grab: MotionLimits; slow: MotionLimits } + /** + * Prusa XL: the dock along the back frame and the firmware's park and pick moves (Prusa-Firmware-Buddy, + * toolchanger_utils.h and toolchanger_xl.cpp). Offsets are from a dock's x and y. + */ + xl?: { + x: number[] + y: number + /** Y in front of the docks with a tool on the head, and without one. */ + safeWith: number + safeWithout: number + park: { approachX: number; unlockX: number; seatX: number } + pick: { preY: number; lockX: number; lockedX: number; clearX: number } + /** Moves into and out of a dock (SLOW_MOVE_MM_S, SLOW_ACCELERATION_MM_S2); the approach (PARKING_FINAL_MAX_SPEED). */ + slow: MotionLimits + approach: MotionLimits + /** The firmware's wait for the parked or picked sensor (WAIT_TIME_TOOL_PARKED_PICKED), s. */ + sense: number + } + /** + * UltiMaker S series. Positions are the head's, which the G-code writes as the left nozzle's (the firmware + * applies no offset): the right core prints `offsets[1]` to the right of it. + */ + lift?: { + /** Each core's nozzle offset from the left one (`extruder_offset`), mm. */ + offsets: [number, number][] + /** Where the head waits before and after each core's switch (`toolchange_park_position`, Cura's `machine_extruder_start_pos` and `_end_pos`). */ + park: [number, number][] + /** The lowered right nozzle's tip under the left one, and its stroke on the lift switch, mm. */ + lowered: number + stroke: number + /** How far the firmware runs the lever into the switch bay past the switching position, mm. */ + bayIn: number + /** Lever moves in the bay. */ + lever: MotionLimits + /** Seconds of retraction before the head leaves for the switch (the usual one, then the switch length). */ + retract: number + /** Where the firmware runs each core's switch from, at the bay: the switching positions, or on the S3 an estimate (see `toolChangerSpec`). */ + bayAt: [number, number][] + } +} + +/** A plain settings record (Orca keys) as the app resolves it. */ +type Settings = Record + +const num = (v: unknown, fallback: number): number => { + if (Array.isArray(v)) return num(v[0], fallback) + if (typeof v === 'number') return Number.isFinite(v) ? v : fallback + if (typeof v === 'string') { + const n = Number.parseFloat(v) + return Number.isFinite(n) ? n : fallback + } + return fallback +} + +/** Points as the settings hold them: `[[x, y], ...]` or Orca's `["22x0", ...]`. */ +const points = (v: unknown): [number, number][] => { + if (!Array.isArray(v)) return [] + return v.map((p): [number, number] => { + if (Array.isArray(p)) return [num(p[0], 0), num(p[1], 0)] + const [x, y] = String(p).split(/x/i) + return [num(x, 0), num(y, 0)] + }) +} + +const list = (v: unknown): number[] => { + if (Array.isArray(v)) return v.map((x) => num(x, 0)) + if (typeof v === 'string' && v.includes(',')) return v.split(',').map((x) => num(x, 0)) + return v === undefined ? [] : [num(v, 0)] +} + +function kindOf(printerId: string | undefined, cfg: Settings): ToolChangerKind | null { + const id = printerId ?? '' + if (id.startsWith('bambu-h2d')) return 'dual-nozzle' + if (id.startsWith('bambu-h2c')) return 'hotend-rack' + if (id === 'snapmaker-u1') return 'tool-rack' + if (id.startsWith('prusa-xl') && list(cfg['nozzle_diameter']).length > 1) return 'xl-dock' + if (id.startsWith('ultimaker-s')) return 'lift-switch' + const nozzles = list(cfg['nozzle_diameter']).length + if (nozzles < 2) return swapChute(id, { widthMm: 0, depthMm: 0, heightMm: 0 }) ? 'filament-swap' : null + if (list(cfg['extruder_max_nozzle_count']).some((n) => n > 1)) return 'hotend-rack' + return nozzles === 2 ? 'dual-nozzle' : 'tool-rack' +} + +/** + * The purge chute of a Bambu Lab printer with one nozzle, from its machine G-code (Bambu Studio 2.8.4 templates): + * - A1, A1 mini: the change cuts at the right end of X (`G1 X267`, `X180`), flushes at the left end + * (`G1 X-48.2`, `X-13.5` in the start G-code, with `G1 Y128`, `Y90` in the change), and wipes by running right + * over the wiper and back (`G1 X-38.2`, `X-3.5`). The chute is on the frame and the bed moves in y. + * - X1, X1E, P1P, P1S: the cutter is at the back (`G1 X70`, `Y265`), the flush at X 54, Y 265 (the start G-code's + * `G1 X54`, `G1 Y265` before its flush), the wipe runs right along the back (`G1 X70` to `X165`). + * - H2S: the H2 family's chute (`M620.14 X95.5 Y336` in the H2C template) and the same exit moves as the H2D. + * The P2S's change hands everything to the firmware (`G150` macros) and writes no position, so it has none here. + */ +function swapChute(id: string, bed: Bed): NonNullable | null { + if (id.startsWith('bambu-a1-mini')) return { x: -13.5, y: 90, exitY: [], exit: 'right', frame: true, cut: [180, null], exits: [[-3.5, 90], [-13.5, 90], [-3.5, 90]], mouth: { x: [-17, 17], y: [-8, 18] } } + if (id.startsWith('bambu-a1')) return { x: -48.2, y: 128, exitY: [], exit: 'right', frame: true, cut: [267, null], exits: [[-38.2, 128], [-48.2, 128], [-38.2, 128]], mouth: { x: [-12, 12], y: [-8, 14] } } + if (/^bambu-(x1|p1p|p1s)/.test(id)) return { x: 54, y: 265, exitY: [], exit: 'right', cut: [70, 265], exits: [[70, 265], [100, 265], [165, 265], [165, 256]], mouth: { x: [-5.7, 26], y: [-12, 18] } } + if (id.startsWith('bambu-h2s')) return { x: 95.5, y: bed.depthMm + 16, exitY: [bed.depthMm, bed.depthMm - 25, bed.depthMm - 55] } + return null +} + +/** The stops after a flush: the first takes the purge past the wiper. */ +export function chuteExits(ch: NonNullable): [number, number][] { + return ch.exits ?? ch.exitY.map((y): [number, number] => [ch.x, y]) +} + +/** + * The tool changer of a printer, or null when it has one nozzle (an AMS swap stays where the head is). + * `printerId` is the profile id (for example `bambu-h2c`); the settings carry the speeds and times. + */ +export function toolChangerSpec(printerId: string | undefined, cfg: Settings, bed: Bed, tools: number): ToolChangerSpec | null { + const kind = kindOf(printerId, cfg) + if (!kind) return null + const travelSpeed = num(cfg['travel_speed'], 500) + const travelAccel = num(cfg['machine_max_acceleration_travel'], 0) || num(cfg['travel_acceleration'], 0) || num(cfg['machine_max_acceleration_x'], 5000) + const map = list(cfg['filament_map']).map((v) => Math.max(0, Math.round(v) - 1)) + const nozzles = Math.max(1, list(cfg['nozzle_diameter']).length) + // A hotend rack whose settings map nothing to the rack's extruder (the profile default puts every + // filament on the first) is taken to print everything from the rack: that is what the machine is for. + const rackDefault = kind === 'hotend-rack' && !map.some((e) => e > 0) ? nozzles - 1 : 0 + const extruderOf = Array.from({ length: Math.max(1, tools) }, (_, t) => Math.min(nozzles - 1, map[t] ?? (kind === 'tool-rack' || kind === 'xl-dock' || kind === 'lift-switch' ? t : rackDefault))) + const sw = cfg['machine_tool_change_time'] !== undefined ? num(cfg['machine_tool_change_time'], 0) : num(cfg['machine_switch_extruder_time'], 0) + const base: ToolChangerSpec = { + kind, + bed, + tools: Math.max(1, tools), + extruderOf, + travel: { speed: Math.max(50, travelSpeed), accel: Math.max(500, travelAccel) }, + z: { speed: Math.max(5, num(cfg['machine_max_speed_z'], 20)), accel: Math.max(50, num(cfg['machine_max_acceleration_z'], 500)) }, + dock: { speed: 60, accel: 2000 }, + liftMm: 3, + ...(String(Array.isArray(cfg['change_filament_gcode']) ? cfg['change_filament_gcode'][0] : (cfg['change_filament_gcode'] ?? '')).includes('max_layer_z') ? { liftOverPrint: true } : {}), + seconds: { switch: Math.max(0, sw), load: Math.max(0, num(cfg['machine_load_filament_time'], 0)), unload: Math.max(0, num(cfg['machine_unload_filament_time'], 0)) }, + } + if (kind === 'dual-nozzle' || kind === 'hotend-rack') { + // The chute's position is the profile's fallback purge position (`M620.14 X95.5 Y336`); the exit + // stops are the `G1 Y320`, `Y295`, `Y265` moves of the change G-code (measured). + base.chute = { x: 95.5, y: bed.depthMm + 16, exitY: [bed.depthMm, bed.depthMm - 25, bed.depthMm - 55] } + base.nozzles = { spacing: 24, liftMm: 2.5 } + } + if (kind === 'filament-swap') base.chute = swapChute(printerId ?? '', bed)! + if (kind === 'hotend-rack') { + // Rack geometry is estimated: the strip right of the right nozzle's reach (X 330 of 350), three + // positions in the rear half, the upper row 96 mm up. The rack stands 22 mm past the bed so a hotend + // printing at the right edge clears the parked ones, the upper row clears the toolhead's cover, and the + // head waits 28 mm from a position (approachX) so the rows can move past it while it waits. + base.rack = { x: bed.widthMm + 22, ys: [150, 210, 270].map((y) => Math.min(y, bed.depthMm - 20)), rowRise: 96, approachX: 28, latchY: 6, slots: 6 } + } + if (kind === 'xl-dock') { + // Prusa-Firmware-Buddy (toolchanger_utils.h): DOCK_DEFAULT_FIRST_X_MM 25, DOCK_OFFSET_X_MM 82, + // DOCK_DEFAULT_Y_MM 455, SAFE_Y_WITH_TOOL 360, SAFE_Y_WITHOUT_TOOL 425, PARK_X_OFFSET_1..3 -10, -9, +0.5, + // PICK_Y_OFFSET -5, PICK_X_OFFSET_1..3 -11.8, -12.8, -9.9, SLOW_MOVE_MM_S 50, SLOW_ACCELERATION_MM_S2 400, + // PARKING_FINAL_MAX_SPEED 300, TRAVEL_MOVE_MM_S 400, WAIT_TIME_TOOL_PARKED_PICKED 200 ms. The change + // G-code lifts Z by 2 mm (`position[2] + 2.0`, `M217 Z2`) and moves at 350 mm/s at most. + const n = Math.max(2, nozzles) + base.xl = { + x: Array.from({ length: n }, (_, i) => 25 + 82 * i), + y: 455, + safeWith: 360, + safeWithout: 425, + park: { approachX: -10, unlockX: -9, seatX: 0.5 }, + pick: { preY: -5, lockX: -11.8, lockedX: -12.8, clearX: -9.9 }, + slow: { speed: 50, accel: 400 }, + approach: { speed: 300, accel: base.travel.accel }, + sense: 0.2, + } + base.travel = { speed: Math.min(base.travel.speed, 350), accel: base.travel.accel } + base.liftMm = 2 + } + if (kind === 'lift-switch') { + // UltiMaker S series, from the profile (Cura's definitions): the nozzle offsets, the switching positions, + // the switch retraction and the lift after it. The lowered right nozzle sits 1.5 mm under the left one + // (`machine_nozzle_head_distance` 4.2 and 2.7). Estimated: the 3 mm stroke of the lift switch, the 10 mm + // the firmware runs into the bay and its lever speed. + const pts = points(cfg['extruder_offset']) + const park = points(cfg['toolchange_park_position']) + const n = Math.max(2, nozzles) + const offsets = Array.from({ length: n }, (_, i): [number, number] => pts[i] ?? (i === 1 ? [22, 0] : [0, 0])) + const parks = Array.from({ length: n }, (_, i): [number, number] => park[i] ?? park[0] ?? [bed.widthMm, bed.depthMm - 3]) + // Where the two cores' positions differ (S5, S7, S6, S8) they are the ends of the lever's run along the bay. The + // S3 gets one position for both (X 180, Y 180), so its bay is put where the S5's is on its frame: on the right + // wall at the bed's right edge, 3 and 21 mm in from the back (estimated; the UltiMaker 3, the S3's + // predecessor, has its two positions at the right edge as well, X 213, Y 207 and 189). + const apart = parks.some((p) => Math.abs(p[1] - (parks[0]?.[1] ?? 0)) > 1) + const bayAt = apart ? parks : parks.map((_, i): [number, number] => [bed.widthMm, bed.depthMm - (i > 0 ? 21 : 3)]) + const at = (k: string, i: number, fallback: number) => list(cfg[k])[i] ?? list(cfg[k])[0] ?? fallback + const length = at('retraction_length', 0, 6.5) + const speed = at('retraction_speed', 0, 45) + const extra = Math.max(0, at('retract_length_toolchange', 0, length) - length) + const extraSpeed = at('retract_speed_toolchange', 0, 20) || 20 + base.lift = { + offsets, + park: parks, + lowered: 1.5, + stroke: 3, + bayIn: 10, + lever: { speed: 50, accel: 1000 }, + retract: length / Math.max(1, speed) + extra / Math.max(1, extraSpeed), + bayAt, + } + base.liftMm = at('retract_lift_toolchange', 0, at('z_hop', 0, 2)) + const zSpeed = num(cfg['travel_speed_z'], 0) + if (zSpeed > 0) base.z = { speed: zSpeed, accel: base.z.accel } + } + if (kind === 'tool-rack') { + // Snapmaker U1 printer.cfg: xy_park_position per extruder, y_idle_position, horizontal_move_x, + // retract_x_dist, insertion_buffer_dist, fast_move_speed, slow_move_speed, grab_speed, switch_accel. + const n = Math.max(2, nozzles) + const xs = n === 4 ? [35.0, 102.7, 170.2, 237.7] : Array.from({ length: n }, (_, i) => ((i + 0.5) * bed.widthMm) / n) + base.docks = { x: xs, y: bed.depthMm + 61.2, idleY: Math.min(250, bed.depthMm - 20), strokeX: 10, retractX: 1.5, bufferMm: 5, grab: { speed: 10, accel: 2000 }, slow: { speed: 60, accel: 5000 } } + base.travel = { speed: Math.min(base.travel.speed, 400), accel: Math.min(base.travel.accel, 5000) } + base.liftMm = 3.5 + base.z = { speed: 10, accel: base.z.accel } + } + return base +} + +/** + * The seconds a printer spends on each change beyond its moves, kept across the print as the engine + * keeps them (`packages/core/src/gcode.rs`, `ChangeClock`): a change to another filament on the same + * extruder costs an unload and a load; a change to another extruder costs the switch plus a load when + * that extruder is empty, or an unload and a load when it last held a different filament. The first + * unload of the print is free. + */ +export class ChangeClock { + private extruder: number | null = null + private readonly held: (number | null)[] + private unloaded = true + + constructor(private readonly spec: Pick, extruders: number) { + this.held = Array.from({ length: Math.max(1, extruders) }, () => null) + } + + private extruderOf(tool: number): number { + return Math.min(this.held.length - 1, this.spec.extruderOf[tool] ?? 0) + } + + change(next: number): number { + const e = this.extruderOf(next) + const prev = this.extruder + if (prev !== null && this.held[prev] === next) return 0 + let t = 0 + const load = (unloadFirst: boolean) => { + if (unloadFirst && !this.unloaded) t += this.spec.seconds.unload + this.unloaded = false + t += this.spec.seconds.load + this.held[e] = next + } + if (prev === e) load(true) + else if (prev === null) { + this.extruder = e + load(false) + } else { + this.extruder = e + const f = this.held[e] + if (f === null) load(false) + else if (f !== next) load(true) + t += this.spec.seconds.switch + } + return t + } +} + +// ---------- motion ---------- + +export interface Phase { + name: string + from: V3 + to: V3 + /** Seconds the move takes (0 for a dwell). */ + move: number + /** Seconds the head stays at `to` after the move. */ + dwell: number + limits: MotionLimits + /** Start time within the change. */ + t0: number + /** The tool in the head during this phase, or null when the bay is empty. */ + carried: number | null + /** Where the head holds the carried tool: 0 the left nozzle down, 1 the right (dual-nozzle, hotend-rack); the slot it is at (tool-rack). */ + state: number + /** H2C: the rack row at the head's height once this phase ends. */ + row: number +} + +export interface ChangeSequence { + from: number + to: number + duration: number + phases: Phase[] + /** For racks: which tool each slot holds before the change (-1 empty, `SPARE` a hotend the print does not use). */ + slotsBefore: number[] + slotsAfter: number[] + /** The rack row at the head's height before and after (H2C). */ + rowBefore: number + rowAfter: number +} + +export interface Pose { + x: number + y: number + z: number + carried: number | null + /** 0 to 1: the left nozzle down to the right nozzle down (dual-nozzle); unused elsewhere. */ + lift: number + /** 0 to 1: the latch or lock engaged (shown while a rack holds or releases a tool). */ + latch: number + /** Rack row at head height, interpolated (H2C). */ + row: number + /** Which tool each rack slot holds right now (-1 empty, `SPARE` a hotend the print does not use). */ + slots: number[] + phase: string +} + +/** Seconds a move of `d` mm takes with a trapezoidal profile from rest to rest. */ +export function moveTime(d: number, l: MotionLimits): number { + if (d <= 1e-9) return 0 + const dAccel = (l.speed * l.speed) / l.accel + return d >= dAccel ? d / l.speed + l.speed / l.accel : 2 * Math.sqrt(d / l.accel) +} + +/** Distance covered after `t` seconds of a trapezoidal move of `d` mm. */ +export function moveDistance(d: number, l: MotionLimits, t: number): number { + if (d <= 1e-9 || t <= 0) return 0 + const dAccel = (l.speed * l.speed) / l.accel + if (d >= dAccel) { + const ta = l.speed / l.accel + const tc = d / l.speed - ta + if (t < ta) return 0.5 * l.accel * t * t + if (t < ta + tc) return 0.5 * l.speed * ta + l.speed * (t - ta) + const te = Math.min(ta, t - ta - tc) + return d - 0.5 * l.accel * (ta - te) * (ta - te) + } + const half = Math.sqrt(d / l.accel) + if (t < half) return 0.5 * l.accel * t * t + const te = Math.min(half, t - half) + return d - 0.5 * l.accel * (half - te) * (half - te) +} + +const dist = (a: V3, b: V3) => Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]) + +class Builder { + phases: Phase[] = [] + t = 0 + private rowNow = 0 + constructor(public pos: V3, private carried: number | null, private state: number) {} + + moveTo(name: string, to: V3, limits: MotionLimits, dwell = 0): this { + const d = dist(this.pos, to) + const move = moveTime(d, limits) + this.phases.push({ name, from: this.pos, to, move, dwell, limits, t0: this.t, carried: this.carried, state: this.state, row: this.rowNow }) + this.t += move + dwell + this.pos = to + return this + } + + dwell(name: string, seconds: number): this { + if (seconds <= 0) return this + this.phases.push({ name, from: this.pos, to: this.pos, move: 0, dwell: seconds, limits: { speed: 1, accel: 1 }, t0: this.t, carried: this.carried, state: this.state, row: this.rowNow }) + this.t += seconds + return this + } + + carry(tool: number | null): this { + this.carried = tool + return this + } + + at(state: number): this { + this.state = state + return this + } + + /** The rack row at the head's height from the next phase on (H2C). */ + row(r: number): this { + this.rowNow = r + return this + } +} + +/** A rack position holding a hotend the print does not use. */ +export const SPARE = -2 + +/** + * The rack at the start of the print (hotend-rack): tools on the rack extruder take positions in tool order and + * the first of them starts in the head. The machine has a hotend for every position but one (wiki: six hotends, + * five on the rack while one is on the toolhead), so the position after the print's own is the empty one and + * the rest hold spare hotends. + */ +function rackSlots(spec: ToolChangerSpec): { slots: number[]; inHead: number | null } { + const n = spec.rack?.slots ?? 6 + const slots = Array.from({ length: n }, () => SPARE) + const rackExtruder = Math.max(...spec.extruderOf, 0) + const onRack = Array.from({ length: spec.tools }, (_, t) => t).filter((t) => spec.extruderOf[t] === rackExtruder) + const [inHead, ...rest] = onRack + rest.forEach((t, i) => { + if (i < n) slots[i] = t + }) + if (rest.length < n) slots[rest.length] = -1 + return { slots, inHead: inHead ?? null } +} + +/** The rack slot a tool sits in before a change. Preceding changes moved tools around; `history` replays them. */ +export function rackStateBefore(spec: ToolChangerSpec, history: readonly [number, number][]): { slots: number[]; inHead: number | null; row: number } { + const s = rackSlots(spec) + let row = 0 + let inHead = s.inHead + for (const [from, to] of history) { + const seq = hotendPlan(spec, from, to, s.slots, inHead, row) + if (!seq) continue + s.slots.splice(0, s.slots.length, ...seq.slotsAfter) + inHead = seq.inHeadAfter + row = seq.rowAfter + } + return { slots: s.slots, inHead, row } +} + +interface HotendPlan { + parkSlot: number + pickSlot: number + slotsAfter: number[] + inHeadAfter: number | null + rowAfter: number +} + +function hotendPlan(spec: ToolChangerSpec, from: number, to: number, slots: number[], inHead: number | null, row: number): HotendPlan | null { + const rackExtruder = Math.max(...spec.extruderOf, 0) + if (spec.extruderOf[to] !== rackExtruder || inHead === to) return null + const pickSlot = slots.indexOf(to) + if (pickSlot < 0) return null + // The firmware parks in the lowest numbered empty position (wiki: the one closest to the toolhead). + const parkSlot = inHead === null ? -1 : slots.indexOf(-1) + const after = slots.slice() + if (parkSlot >= 0 && inHead !== null) after[parkSlot] = inHead + after[pickSlot] = -1 + void from + return { parkSlot, pickSlot, slotsAfter: after, inHeadAfter: to, rowAfter: Math.floor(pickSlot / 3) } +} + +const printedTops = new WeakMap() + +/** The highest layer top printed up to the layer of `segment` (the G-code's `max_layer_z` there), mm. */ +export function printedTop(b: PreviewBuffers, segment: number): number { + let tops = printedTops.get(b) + if (!tops) { + tops = new Float32Array(b.layerCount) + let m = 0 + for (let l = 0; l < b.layerCount; l++) tops[l] = m = Math.max(m, b.layerZ[l] ?? 0) + printedTops.set(b, tops) + } + let lo = 0 + let hi = b.layerCount - 1 + while (lo < hi) { + const mid = (lo + hi + 1) >> 1 + if ((b.layerStart[mid] ?? 0) <= segment) lo = mid + else hi = mid - 1 + } + return tops[lo] ?? 0 +} + +/** + * The sequence of one change from tool `from` to tool `to`, starting with the nozzle at `at` (the end + * of the last move before the change) and ending at `resume` (the start of the first move after it). + * `fixed` is the firmware's seconds for this change (`ChangeClock.change`). `history` lists the + * changes before this one (racks keep state across changes). `printed` is the highest layer printed so far, which a + * change G-code that lifts over `max_layer_z` clears. + */ +export function changeSequence(spec: ToolChangerSpec, from: number, to: number, at: V3, resume: V3, fixed: number, history: readonly [number, number][] = [], printed = 0): ChangeSequence { + const top = Math.max(at[2], resume[2], spec.liftOverPrint ? printed : 0) + const up = top + spec.liftMm + const lifted: V3 = [at[0], at[1], up] + const back: V3 = [resume[0], resume[1], up] + const empty: number[] = [] + const firm = Math.max(fixed, 0.8) + if (spec.kind === 'dual-nozzle') { + const ch = spec.chute! + const side = (t: number) => (spec.extruderOf[t] ?? 0) > 0 ? 1 : 0 + const b = new Builder(at, from, side(from)) + b.moveTo('lift', lifted, spec.z) + b.moveTo('to chute', [ch.x, ch.y, up], spec.travel) + // Cut and retract, then the nozzles trade places, then load and flush, in the profile's time. + b.dwell('cut', firm * 0.25) + b.at(side(to)).carry(to).dwell('switch', firm * 0.2) + b.dwell('load', firm * 0.55) + const speeds = [spec.travel, spec.travel, { speed: Math.min(300, spec.travel.speed), accel: spec.travel.accel }] + ch.exitY.forEach((y, i) => b.moveTo(i === 0 ? 'wipe' : 'exit', [ch.x, y, up], speeds[i] ?? spec.travel)) + b.moveTo('return', back, spec.travel) + b.moveTo('lower', resume, { speed: Math.min(50, spec.z.speed * 2.5), accel: spec.z.accel }) + return { from, to, duration: b.t, phases: b.phases, slotsBefore: empty, slotsAfter: empty, rowBefore: 0, rowAfter: 0 } + } + if (spec.kind === 'hotend-rack') { + const ch = spec.chute! + const rack = spec.rack! + const st = rackStateBefore(spec, history) + const plan = hotendPlan(spec, from, to, st.slots, st.inHead, st.row) + const side = (t: number) => (spec.extruderOf[t] ?? 0) > 0 ? 1 : 0 + const b = new Builder(at, st.inHead, side(from)).row(st.row) + b.moveTo('lift', lifted, spec.z) + b.moveTo('to chute', [ch.x, ch.y, up], spec.travel) + const swapShare = plan ? 0.3 : 0.45 + b.dwell('cut', firm * swapShare) + if (plan) { + const slotPos = (k: number): V3 => [rack.x, rack.ys[k % 3] ?? rack.ys[0]!, up] + // Park the hotend in the bay: slide into the rack from the left, unlatch, leave forward. + if (plan.parkSlot >= 0 && st.inHead !== null) { + const p = slotPos(plan.parkSlot) + const row = Math.floor(plan.parkSlot / 3) + b.moveTo('to rack', [p[0] - rack.approachX, p[1], up], spec.travel) + if (row !== st.row) b.row(row).dwell('rack lifts', 0.9) + b.moveTo('dock', p, spec.dock, 0.25) + b.carry(null).moveTo('unlatch', [p[0], p[1] - rack.latchY, up], spec.dock, 0.15) + b.moveTo('leave', [p[0] - rack.approachX, p[1] - rack.latchY, up], spec.dock) + } + // Pick the next one: back off along the front of the rack, in front of its slot, push in from the + // front, latch, pull out to the left. The detour keeps the head off the hotend it just parked. + const q = slotPos(plan.pickSlot) + const row = Math.floor(plan.pickSlot / 3) + b.moveTo('along', [q[0] - rack.approachX, q[1] - rack.approachX, up], spec.travel) + b.moveTo('to slot', [q[0], q[1] - rack.approachX, up], spec.dock) + const current = plan.parkSlot >= 0 && st.inHead !== null ? Math.floor(plan.parkSlot / 3) : st.row + if (row !== current) b.row(row).dwell('rack lifts', 0.9) + b.moveTo('engage', q, spec.dock, 0.15) + b.carry(to).dwell('latch', 0.25) + b.moveTo('pull out', [q[0] - rack.approachX, q[1], up], spec.dock) + b.moveTo('to chute', [ch.x, ch.y, up], spec.travel) + } else { + b.at(side(to)).carry(st.inHead).dwell('switch', firm * 0.1) + } + b.dwell('load', firm * (plan ? 0.7 : 0.45)) + const speeds = [spec.travel, spec.travel, { speed: Math.min(300, spec.travel.speed), accel: spec.travel.accel }] + ch.exitY.forEach((y, i) => b.moveTo(i === 0 ? 'wipe' : 'exit', [ch.x, y, up], speeds[i] ?? spec.travel)) + b.moveTo('return', back, spec.travel) + b.moveTo('lower', resume, { speed: Math.min(50, spec.z.speed * 2.5), accel: spec.z.accel }) + return { + from, + to, + duration: b.t, + phases: b.phases, + slotsBefore: st.slots, + slotsAfter: plan ? plan.slotsAfter : st.slots, + rowBefore: st.row, + rowAfter: plan ? plan.rowAfter : st.row, + } + } + if (spec.kind === 'xl-dock') { + // Prusa-Firmware-Buddy toolchanger_xl.cpp, park() then pickup(): to the front of the dock, in, sideways into + // the dock's pins, back out without the tool; to the next dock, in, sideways out of its pins with the tool, + // back out, return. The firmware waits for the dock's sensor after each seat. + const k = spec.xl! + const xOf = (t: number) => k.x[t] ?? k.x[k.x.length - 1] ?? 0 + const slots = Array.from({ length: k.x.length }, (_, i) => (i === from ? -1 : i)) + const a = xOf(from) + const c = xOf(to) + const b = new Builder(at, from, from) + b.moveTo('lift', lifted, spec.z) + b.moveTo('to dock', [a + k.park.approachX, k.safeWith, up], spec.travel) + b.moveTo('approach', [a + k.park.approachX, k.y, up], k.approach) + b.moveTo('unlock', [a + k.park.unlockX, k.y, up], k.slow) + b.moveTo('seat', [a + k.park.seatX, k.y, up], k.slow) + b.moveTo('park', [a, k.y, up], k.slow, k.sense) + b.carry(null).at(-1).moveTo('pull back', [a, k.safeWithout, up], spec.travel) + b.moveTo('to next', [c, k.safeWithout, up], spec.travel) + b.moveTo('insert', [c, k.y + k.pick.preY, up], spec.travel) + b.moveTo('seat', [c, k.y, up], k.slow, k.sense) + b.carry(to).at(to).moveTo('lock', [c + k.pick.lockX, k.y, up], k.slow) + b.moveTo('lock', [c + k.pick.lockedX, k.y, up], k.slow) + b.moveTo('clear', [c + k.pick.clearX, k.y, up], k.slow) + b.moveTo('extract', [c + k.pick.clearX, k.safeWith, up], spec.travel) + b.dwell('heat', firm) + b.moveTo('return', back, spec.travel) + b.moveTo('lower', resume, spec.z) + const after = slots.slice() + after[from] = from + after[to] = -1 + return { from, to, duration: b.t, phases: b.phases, slotsBefore: slots, slotsAfter: after, rowBefore: 0, rowAfter: 0 } + } + if (spec.kind === 'lift-switch') return liftSwitch(spec, from, to, at, resume, firm) + if (spec.kind === 'filament-swap') { + // To the cutter (or cut at the chute), then the chute: the firmware unloads, the AMS feeds the next filament, + // the nozzle flushes; then over the wiper and out. + const ch = spec.chute! + const b = new Builder(at, from, 0) + b.moveTo('lift', lifted, spec.z) + if (ch.cut) b.moveTo('to cutter', [ch.cut[0], ch.cut[1] ?? at[1], up], spec.travel) + else b.moveTo('to chute', [ch.x, ch.y, up], spec.travel) + b.dwell('cut', firm * 0.15) + if (ch.cut) b.moveTo('to chute', [ch.x, ch.y, up], spec.travel) + b.carry(to).dwell('load', firm * 0.85) + const speeds = [spec.travel, spec.travel, { speed: Math.min(300, spec.travel.speed), accel: spec.travel.accel }] + chuteExits(ch).forEach(([x, y], i) => b.moveTo(i === 0 ? 'wipe' : 'exit', [x, y, up], speeds[i] ?? spec.travel)) + b.moveTo('return', back, spec.travel) + b.moveTo('lower', resume, { speed: Math.min(50, spec.z.speed * 2.5), accel: spec.z.accel }) + return { from, to, duration: b.t, phases: b.phases, slotsBefore: empty, slotsAfter: empty, rowBefore: 0, rowAfter: 0 } + } + // tool-rack + const d = spec.docks! + const xOf = (t: number) => d.x[t] ?? d.x[d.x.length - 1] ?? 0 + const slots = Array.from({ length: d.x.length }, (_, i) => (i === from ? -1 : i)) + const b = new Builder(at, from, from) + b.moveTo('lift', lifted, spec.z) + // Park: in front of the slot, push in fast then slow for the last millimeters, release sideways, back out. + b.moveTo('to dock', [xOf(from), d.idleY, up], spec.travel) + b.moveTo('push in', [xOf(from), d.y - d.bufferMm, up], d.slow.speed > spec.travel.speed ? spec.travel : { speed: spec.travel.speed, accel: d.slow.accel }) + b.moveTo('seat', [xOf(from), d.y, up], d.slow, 0.1) + b.moveTo('release', [xOf(from) + d.strokeX, d.y, up], d.grab) + b.carry(null).at(-1).dwell('released', Math.min(1, firm * 0.2)) + b.moveTo('back out', [xOf(from) + d.strokeX, d.y - d.bufferMm, up], d.slow) + // Pick: beside the next slot, in, grab sideways, settle, out. + b.moveTo('to next', [xOf(to) + d.strokeX, d.idleY, up], spec.travel) + b.moveTo('push in', [xOf(to) + d.strokeX, d.y - d.bufferMm, up], { speed: spec.travel.speed, accel: d.slow.accel }) + b.moveTo('seat', [xOf(to) + d.strokeX, d.y, up], d.slow) + b.moveTo('grab', [xOf(to), d.y, up], d.grab) + b.carry(to).at(to).moveTo('settle', [xOf(to) + d.retractX, d.y, up], d.slow, Math.max(0.2, firm * 0.8)) + b.moveTo('pull out', [xOf(to) + d.retractX, d.idleY, up], d.slow.speed < spec.travel.speed ? { speed: spec.travel.speed, accel: d.slow.accel } : spec.travel) + b.moveTo('return', back, spec.travel) + b.moveTo('lower', resume, spec.z) + const after = slots.slice() + after[from] = from + after[to] = -1 + return { from, to, duration: b.t, phases: b.phases, slotsBefore: slots, slotsAfter: after, rowBefore: 0, rowAfter: 0 } +} + +/** + * UltiMaker S: the head (the left nozzle's position, as the G-code writes it) retracts, goes to the leaving core's + * switching position and lifts (the moves the slicer writes), the firmware runs the lever into the switch bay, + * along it to the other core's switching position, which lowers or lifts the right core, and back out, waits + * for the new core's temperature, and the head returns to the next move and comes down. Pose state 1 is the + * right core lowered. + */ +function liftSwitch(spec: ToolChangerSpec, from: number, to: number, at: V3, resume: V3, firm: number): ChangeSequence { + const k = spec.lift! + const side = (t: number) => ((spec.extruderOf[t] ?? 0) > 0 ? 1 : 0) + const off = (t: number) => k.offsets[spec.extruderOf[t] ?? 0] ?? [0, 0] + const park = (t: number) => k.park[spec.extruderOf[t] ?? 0] ?? k.park[0] ?? [0, 0] + // The left nozzle stands the lowered right one's depth higher while the right core prints. + const head = (p: V3, t: number): V3 => [p[0] - off(t)[0], p[1] - off(t)[1], p[2] + side(t) * k.lowered] + const start = head(at, from) + const end = head(resume, to) + // The lift is written in G-code Z (the layer plus the hop); the firmware applies each core's Z offset, so the + // head stands the lowered core's depth higher once the right core prints. + const gz = Math.max(at[2], resume[2]) + spec.liftMm + const upFrom = gz + side(from) * k.lowered + const upTo = gz + side(to) * k.lowered + const [ax, ay] = park(from) + const bayAt = (t: number) => k.bayAt[spec.extruderOf[t] ?? 0] ?? k.bayAt[0] ?? park(t) + const [cx, cy] = bayAt(from) + const [bx, by] = bayAt(to) + const b = new Builder(start, from, side(from)) + b.dwell('retract', k.retract) + b.moveTo('to switch', [ax, ay, start[2]], spec.travel) + b.moveTo('lift', [ax, ay, upFrom], spec.z) + if (side(from) !== side(to)) { + // The S3's switching position is not at its bay: the firmware takes the head there first. + if (Math.hypot(cx - ax, cy - ay) > 1e-6) b.moveTo('to bay', [cx, cy, upFrom], spec.travel) + b.moveTo('into bay', [cx + k.bayIn, cy, upFrom], k.lever) + b.at(side(to)).carry(to).moveTo('switch', [bx + k.bayIn, by, upTo], k.lever) + b.moveTo('out of bay', [bx, by, upTo], k.lever) + } else { + b.at(side(to)).carry(to).dwell('switch', moveTime(k.stroke, k.lever) + 0.3) + if (upTo !== upFrom) b.moveTo('offset', [ax, ay, upTo], spec.z) + } + b.dwell('heat', firm) + b.moveTo('return', [end[0], end[1], upTo], spec.travel) + b.moveTo('lower', end, spec.z) + return { from, to, duration: b.t, phases: b.phases, slotsBefore: [], slotsAfter: [], rowBefore: 0, rowAfter: 0 } +} + +const smooth = (u: number) => (u <= 0 ? 0 : u >= 1 ? 1 : u * u * (3 - 2 * u)) + +/** The head's pose `t` seconds into a change. Before 0 it is the start pose, past the end the final one. */ +export function poseAt(seq: ChangeSequence, t: number): Pose { + const phases = seq.phases + const first = phases[0] + const last = phases[phases.length - 1] + const slots = (phase: Phase | undefined): number[] => { + if (!seq.slotsBefore.length) return seq.slotsBefore + const idx = phase ? phases.indexOf(phase) : phases.length + const released = phases.findIndex((p) => p.carried === null) + const picked = phases.findIndex((p, i) => i > released && p.carried !== null) + if (released < 0) return seq.slotsAfter + if (idx < released) return seq.slotsBefore + if (picked >= 0 && idx >= picked) return seq.slotsAfter + // Between release and pick: the parked tool is in its slot and the next one still in its own. + const mid = seq.slotsAfter.slice() + const next = seq.to + const was = seq.slotsBefore.indexOf(next) + if (was >= 0) mid[was] = next + return mid + } + if (!first || !last) return { x: 0, y: 0, z: 0, carried: null, lift: 0, latch: 1, row: 0, slots: seq.slotsBefore, phase: '' } + if (t <= 0) return { x: first.from[0], y: first.from[1], z: first.from[2], carried: first.carried, lift: first.state, latch: 1, row: seq.rowBefore, slots: seq.slotsBefore, phase: first.name } + if (t >= seq.duration) return { x: last.to[0], y: last.to[1], z: last.to[2], carried: last.carried, lift: last.state, latch: 1, row: seq.rowAfter, slots: seq.slotsAfter, phase: last.name } + let lo = 0 + let hi = phases.length - 1 + while (lo < hi) { + const mid = (lo + hi + 1) >> 1 + if ((phases[mid]?.t0 ?? 0) <= t) lo = mid + else hi = mid - 1 + } + const p = phases[lo]! + const local = t - p.t0 + const d = dist(p.from, p.to) + const s = p.move > 0 ? Math.min(1, moveDistance(d, p.limits, Math.min(local, p.move)) / Math.max(d, 1e-9)) : 1 + const x = p.from[0] + (p.to[0] - p.from[0]) * s + const y = p.from[1] + (p.to[1] - p.from[1]) * s + const z = p.from[2] + (p.to[2] - p.from[2]) * s + // The lift (dual nozzle) and the rack row glide to the new state over the dwell that changes them. + const prev = phases[lo - 1] + // A state change on a move (the lift switch run along the bay) follows the move itself. + const u = p.dwell > 0 ? smooth((local - p.move) / p.dwell) : p.move > 0 ? s : 1 + // The rack row is its own state, so a row change never moves the nozzle the head prints with. + const lift = prev && prev.state !== p.state ? prev.state + (p.state - prev.state) * u : p.state + const row = prev && prev.row !== p.row ? prev.row + (p.row - prev.row) * u : p.row + const latch = p.name === 'unlatch' ? 1 - u : p.name === 'latch' ? u : p.name === 'release' ? 1 - s : p.name === 'grab' ? s : p.carried === null ? 0 : 1 + return { x, y, z, carried: p.carried, lift, latch, row, slots: slots(p), phase: p.name } +} diff --git a/desktop/src/vendor/slicerx/viewport/toolhead.ts b/desktop/src/vendor/slicerx/viewport/toolhead.ts new file mode 100644 index 00000000..3c4f4293 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/toolhead.ts @@ -0,0 +1,719 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// The toolhead Preview draws at the current move, and the printer's tool changer around it, after the real +// machines (product photos and the Bambu wiki; see docs/toolchanger-sim.md): +// - H2D and H2C: a brushed silver upper cover over a black lower body; the left hotend sits behind a +// black front with the nozzle display and the "hot" plate, side housings hold the cooling fans. On the +// H2C the right side is an open bay a Vortek hotend plugs into from below. +// - Vortek hotend: a slim black shaft with a rounded nozzle end, a collar the rack holds it by, and a +// head block in the filament's color. +// - H2C rack: a black frame on the right wall, two rows of three holders with a white light each. +// - U1: black toolheads with an orange lever and the extruder motor at the back, hung by their coupling face +// on the back of a white carriage and parked in a dock along the back of the frame. +// - UltiMaker S series: the white head with the front fan bracket and its grille, the side fan brackets and +// their vents, two print cores in a cavity between them (the right one on the lift switch), the Bowden +// tubes and the head cable on top, the lift switch lever on the right side, and the switch bay on the +// right wall it runs into. +// Poses come from `toolchanger.ts`. +// +// Every part is a separate solid in millimeters, nozzle tip at the origin, z up, +y toward the back of the +// printer. Parts that meet only touch, so nothing flickers where two faces would share a plane, and the +// clearances keep the head out of the rack and dock through a whole change (test/toolhead.test.ts): +// - a Vortek hotend is 58 mm tall; its collar (z 30 to 32.5, r 5.5) rests on its holder's fork; +// - the head's bay is open at the back, the right and below, so a hotend leaves it by any of the moves +// the sequence makes; the rest of the head stays 17 mm either side of the nozzles in y, 10 mm right of +// the right nozzle in x, under 92 mm, so the other row (96 mm away) and the neighbors pass it by; +// - a U1 toolhead's coupling face is 1.5 mm behind the carriage, and the dock starts 1.5 mm behind the +// toolhead's motor. +import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js' +import { + BoxGeometry, + CanvasTexture, + CircleGeometry, + Color, + ConeGeometry, + CylinderGeometry, + Group, + Mesh, + MeshBasicMaterial, + MeshStandardMaterial, + SphereGeometry, + TorusGeometry, + type BufferGeometry, + type Material, +} from 'three' +import { displayHex } from './palette' +import { amber, black, block, brass, dark, deep, graphite, hotPlate, lightMat, part, post, prusaOrange, ring, silver, slab, sock, steel, white } from './headparts' +import { buildHead, type HeadModel } from './heads' +import { rackStateBefore, type Pose, type ToolChangerSpec } from './toolchanger' + +/** Dimensions, mm. */ +export const HOTEND = { collarZ: 30, collarR: 5.5, shaftR: 3.2, top: 58 } as const +export const HEAD = { bayTop: 58.5, front: -17, back: 17, top: 92, right: 10 } as const +export const RACK = { tineZ: [27.5, 30] as const, tineX: [-10, 8] as const, tineY: 5, holderX: [8, 18] as const } as const + +/** A Vortek hotend, tip at the origin: silver tip, rounded nozzle end, slim shaft, the collar a holder grips, a head block in the filament color. */ +function buildVortek(withRing: boolean): { group: Group; sleeve: Mesh } { + const g = new Group() + g.name = 'hotend' + const head = slab(steel, -6, 6, -5, 5, 40, 50, 'label', 1) + g.add( + part(new ConeGeometry(1.3, 2.2, 24).rotateX(-Math.PI / 2), steel, 0, 0, 1.1, 'tip'), + part(new CylinderGeometry(4.2, 3.0, 5, 28).rotateX(Math.PI / 2), black, 0, 0, 4.7, 'bulb'), + part(post(HOTEND.shaftR, 22.8), black, 0, 0, 18.6, 'shaft'), + part(post(HOTEND.collarR, 2.5, 40), steel, 0, 0, 31.25, 'collar'), + part(post(HOTEND.shaftR, 7.5), black, 0, 0, 36.25, 'neck'), + head, + slab(black, -6, 6, -5, 5, 50, 55, 'cap', 1), + part(post(1.8, 3, 16), steel, 0, 0, 56.5, 'inlet'), + ) + if (withRing) ring(g) + return { group: g, sleeve: head } +} + +/** A fixed hotend as the head shows it: the nozzle under its silicone sock; the rest is inside the body. */ +function buildFixedHotend(): Group { + const g = new Group() + g.name = 'hotend' + g.add(part(new ConeGeometry(1.6, 3, 24).rotateX(-Math.PI / 2), brass, 0, 0, 1.5, 'nozzle'), slab(sock, -5, 5, -5, 5, 3, 7.8, 'sock', 1.2)) + ring(g) + return g +} + +/** The soft shadow the head throws on the path it just laid. */ +function buildShadow(radius: number): Mesh { + const sc = typeof document !== 'undefined' ? document.createElement('canvas') : null + if (sc) sc.width = sc.height = 64 + const sx = sc?.getContext('2d') + if (sx) { + const g = sx.createRadialGradient(32, 32, 2, 32, 32, 32) + g.addColorStop(0, 'rgba(0,0,0,.5)') + g.addColorStop(1, 'rgba(0,0,0,0)') + sx.fillStyle = g + sx.fillRect(0, 0, 64, 64) + } + const shadow = new Mesh(new CircleGeometry(radius, 32), new MeshBasicMaterial({ map: sc ? new CanvasTexture(sc) : null, transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2 })) + shadow.name = 'shadow' + shadow.position.z = -0.02 + return shadow +} + + +/** + * The H2D and H2C head around nozzles `spacing` apart. `bay` leaves the right side open for a Vortek hotend + * (H2C); without it the right side mirrors the left (H2D). The display chip shows the printing filament. + */ +function buildBambuHead(spacing: number, bay: boolean): { group: Group; left: Group; right: Group; rightSleeve: Mesh | null; chip: Mesh } { + const g = new Group() + const s = spacing / 2 + const { front: f, back: b, top, bayTop } = HEAD + const xl = -s - 13 + const xr = s + HEAD.right + const left = buildFixedHotend() + left.position.x = -s + let right: Group + let rightSleeve: Mesh | null = null + if (bay) { + const v = buildVortek(true) + right = v.group + rightSleeve = v.sleeve + } else right = buildFixedHotend() + right.position.x = s + const chip = slab(steel, -8.2, -5, f - 1.3, f - 1, 49.5, 52, 'chip') + g.add( + left, + right, + // Lower body: the left hotend's housing with the display and the hot plate on its front, a fan housing at the side. + slab(black, xl, -s + 13, f, b, 8, bayTop, 'body', 2), + slab(black, xl - 6, xl, f + 5, b - 3, 14, bayTop, 'fan', 2), + slab(deep, -s - 9, -s + 5, f - 1, f, 48, 53.5, 'display'), + chip, + hotPlate(-s, f, 28), + ) + if (bay) { + // The bay: a front wall over the hotend's head block; open at the back, the right and below. + g.add(slab(black, -s + 13, xr, f, -7, 34, bayTop, 'bay front', 2)) + } else { + g.add(slab(black, -s + 13, -xl, f, b, 8, bayTop, 'body', 2), slab(black, -xl, -xl + 6, f + 5, b - 3, 14, bayTop, 'fan', 2), hotPlate(s, f, 28)) + } + const xr2 = bay ? xr : -xl + 6 + g.add( + // A recessed seam between the body and the cover. + slab(deep, xl - 4, xr2 - 2, f + 2, b - 2, bayTop, 62, 'band'), + // The brushed cover with its light strip along the top and the logo plate. + slab(silver, xl - 6, xr2, f, b, 62, top, 'cover', 5), + slab(lightMat, xl + 4, xr2 - 10, f - 0.5, f, top - 6, top - 4.6, 'light'), + slab(steel, -10, 10, f - 0.4, f, 70, 72.5, 'logo'), + ) + return { group: g, left, right, rightSleeve, chip } +} + +/** + * Prusa XL toolhead (a Nextruder on its own board), tip at the origin: the black body with the hotend fan on + * its front, the side blower, the extruder on top with the filament inlet, a band in the filament color and the + * orange label. It couples to the carriage at its front face. + */ +export const XL = { tool: { front: -8, back: 42, half: 27, top: 84 }, carriage: [-22, -9] as const } as const +function buildXlTool(): { group: Group; band: Mesh } { + const g = new Group() + g.name = 'toolhead' + const band = slab(steel, -27.4, -27, 0, 30, 30, 70, 'band') + g.add( + part(new ConeGeometry(1.6, 3, 24).rotateX(-Math.PI / 2), brass, 0, 0, 1.5, 'nozzle'), + slab(sock, -6, 6, -6, 6, 3, 10, 'sock', 1.5), + slab(black, -XL.tool.half, XL.tool.half, XL.tool.front, XL.tool.back, 10, 58, 'body', 3), + slab(black, -22, 22, -4, 38, 58, XL.tool.top, 'extruder', 3), + slab(deep, -14, 14, -8.4, -8, 20, 48, 'fan'), + slab(prusaOrange, -12, 12, -4.4, -4, 66, 72, 'label'), + slab(black, 27, 34, -2, 30, 14, 46, 'blower', 2), + band, + part(post(2.2, 6, 16), steel, 0, 18, XL.tool.top + 3, 'inlet'), + ) + return { group: g, band } +} + +/** A U1 toolhead, tip at the origin: black body, nozzle under its sock, the orange lever, the extruder motor at the back, the coupling face at the front. */ +function buildU1Toolhead(): { group: Group; mark: Mesh } { + const g = new Group() + g.name = 'toolhead' + const mark = slab(steel, -14, 14, -6.6, -6, 66.5, 69, 'mark') + g.add( + part(new ConeGeometry(1.6, 3, 24).rotateX(-Math.PI / 2), brass, 0, 0, 1.5, 'nozzle'), + slab(sock, -6, 6, -6, 6, 3, 9, 'sock', 1.5), + slab(black, -20, 20, -6, 40, 10, 72, 'body', 3), + // The coupling face: the fan opening low down, the label, the yellow line, the steel balls. + slab(deep, -9, 9, -6.5, -6, 12, 23, 'fan'), + slab(amber, -3, 3, -6.5, -6, 40, 46, 'label'), + mark, + part(new CylinderGeometry(2, 2, 0.6, 20), steel, -12, -6.3, 58, 'ball'), + part(new CylinderGeometry(2, 2, 0.6, 20), steel, 12, -6.3, 58, 'ball'), + slab(amber, 20, 23, 2, 14, 40, 56, 'lever', 1), + part(new CylinderGeometry(16, 16, 12, 36), black, 0, 46, 50, 'motor'), + part(new CylinderGeometry(11, 11, 1.5, 36), graphite, 0, 52.75, 50, 'motor cap'), + part(post(3, 6, 16), black, 0, 14, 75, 'inlet'), + ) + return { group: g, mark } +} + +/** UltiMaker S head, mm, the left nozzle's tip at the origin (Cura's head polygon, gantry height and nozzle head distance). */ +export const UM = { + /** The cavity the print cores stand in; the head's walls are around it. */ + cavity: { x0: -8, y0: -11, y1: 23, top: 62 }, + /** Bottom of the head over the left tip (`machine_nozzle_head_distance` 2.7). */ + bottom: 2.7, + /** Lift switch lever: pivot on the right wall, arm height, pin top, swing either side of square to the wall. */ + lever: { x: 39.6, y: 8, z0: 57, z1: 59.5, pinTop: 66, pinR: 1.5, swing: (40 * Math.PI) / 180 }, +} as const + +const clear = new MeshStandardMaterial({ color: new Color('#dce6ee'), metalness: 0.05, roughness: 0.2, transparent: true, opacity: 0.6 }) + +/** + * An UltiMaker print core, nozzle tip at the origin, after the maker's product photos: brass nozzle and heater + * block, the black lower housing with the core's name, the finned heat sink in the black frame with the chip's + * contacts on its back, the clear top plate and the steel feed tube. 14 mm wide, 32 mm deep, 60 mm tall. + */ +function buildPrintCore(): Group { + const g = new Group() + g.name = 'print core' + g.add( + part(new ConeGeometry(1.6, 3, 24).rotateX(-Math.PI / 2), brass, 0, 0, 1.5, 'nozzle'), + slab(brass, -6, 6, -5, 9, 3, 11, 'heater', 0.5), + slab(black, -7, 7, -10, 22, 11, 24, 'housing', 1), + slab(white, -5, 5, -10.4, -10, 16, 21, 'label'), + part(post(5.5, 20, 28), silver, 0, 4, 34, 'fins'), + slab(black, -7, 7, 16, 22, 24, 44, 'spine', 0.8), + slab(brass, -4, 4, 22, 22.4, 28, 40, 'contacts'), + slab(clear, -7, 7, -10, 22, 44, 47, 'plate', 0.6), + part(post(2.4, 13, 20), steel, 0, 4, 53.5, 'pin'), + ) + ring(g) + return g +} + +/** + * The UltiMaker S head around cores `spacing` apart, the left tip at the origin, after the maker's photos (the + * S5 repair manuals, the UltiMaker 3 print head assembly manual) and inside Cura's head polygon (x -41.4 to + * 63.3, y -45.8 to 36 from the left nozzle). The cores stand in a cavity open below; the walls, the front fan + * bracket, the side fan brackets and the bearing housing close it. The two Bowden tubes show the filament. + */ +function buildUltimakerHead(spacing: number, L: number): { group: Group; left: Group; right: Group; lever: Group; tubes: [Mesh, Mesh] } { + const g = new Group() + const cx = spacing / 2 + const { x0, y0, y1, top } = UM.cavity + const x1 = spacing + 8 + const w0 = cx - 27 + const w1 = cx + 27 + const b = UM.bottom + const left = buildPrintCore() + const right = buildPrintCore() + right.position.x = spacing + const tube = (x: number) => part(post(3, 42, 20), white, x, 8, 104, 'tube') + const tubes: [Mesh, Mesh] = [tube(0), tube(spacing)] + g.add( + left, + right, + // The bottom plate around the opening the cores reach through, and the walls of the cavity. + slab(white, w0, w1, -22, y0, b, 6, 'bottom'), + slab(white, w0, w1, y1, 30, b, 6, 'bottom'), + slab(white, w0, x0, y0, y1, b, 6, 'bottom'), + slab(white, x1, w1, y0, y1, b, 6, 'bottom'), + slab(white, w0, x0, y0, y1, 6, top, 'body', 1), + slab(white, x1, w1, y0, y1, 6, top, 'body', 1), + slab(white, w0, w1, -14, y0, 6, top, 'body', 1), + slab(white, w0, w1, y1, 30, 6, top, 'body', 1), + // The front fan bracket over the cores, its grille with the slats in front of the fan. + slab(white, cx - 24, cx + 24, -45.8, -14, 8, 50, 'front bracket', 3), + slab(deep, cx - 14, cx + 14, -46.2, -45.8, 16, 44, 'grille'), + // The side fan brackets with their vents, and the ducts under them that blow at the nozzles. + slab(white, -41.4, w0, -30, 26, 14, 56, 'side bracket', 3), + slab(white, w1, 63.3, -30, 26, 14, 56, 'side bracket', 3), + slab(white, -36, w0, -24, 18, 6, 14, 'duct', 2), + slab(white, w1, 58, -24, 18, 6, 14, 'duct', 2), + // The bearing housing on top with the Bowden clamps, the cable cover at the back and the head cable. + slab(white, cx - 24, cx + 24, -12, 28, top, 80, 'housing top', 2), + slab(white, cx - 12, cx + 12, 30, 36, 24, 74, 'cable cover', 1.5), + part(post(3.5, 46, 20), white, cx, 33, 97, 'cable'), + part(post(5, 3, 24), white, 0, 8, 81.5, 'clip'), + part(post(5, 3, 24), white, spacing, 8, 81.5, 'clip'), + ...tubes, + ) + for (let i = 0; i < 5; i++) g.add(slab(white, cx - 11 + i * 5, cx - 9 + i * 5, -46.8, -46.2, 16, 44, 'slat')) + for (let i = 0; i < 4; i++) { + const y = -22 + i * 11 + g.add(slab(deep, -41.8, -41.4, y, y + 5, 22, 48, 'vent'), slab(deep, 63.3, 63.7, y, y + 5, 22, 48, 'vent')) + } + // The lift switch: its arm swings about a pivot on the right wall; the pin at its end runs in the switch bay. + const lever = new Group() + lever.name = 'lever' + lever.add(slab(graphite, 0, L, -1.25, 1.25, UM.lever.z0, UM.lever.z1, 'lever', 0.5), part(post(UM.lever.pinR, UM.lever.pinTop - UM.lever.z0, 16), graphite, L, 0, (UM.lever.z0 + UM.lever.pinTop) / 2, 'lever pin')) + lever.position.set(UM.lever.x, UM.lever.y, 0) + g.add(lever) + return { group: g, left, right, lever, tubes } +} + +/** The lever's length: its pin stays in the bay while the head runs between the two switching positions (18 mm apart on the S5, S7, S6 and S8). */ +function leverLength(stroke: number): number { + return stroke / 2 / Math.sin(UM.lever.swing) +} + +export class ToolheadRig { + readonly root = new Group() + /** Moves with the pose; the active nozzle's tip is at the pose when the head carries a tool. */ + private readonly head = new Group() + /** The rack or dock: fixed in x and y, at the gantry's height (the head's z). */ + private readonly fixed = new Group() + private spec: ToolChangerSpec | null = null + private colors: readonly string[] = [] + private readonly materials = new Map() + private readonly disposables: { dispose(): void }[] = [] + private sleeves: { mesh: Mesh; tool: () => number }[] = [] + private left: Group | null = null + private right: Group | null = null + private carried: Group | null = null + private rackSlots: { group: Group }[] = [] + private lever: Group | null = null + private leverL = 14 + private headShadow: Mesh | null = null + private rackGroup: Group | null = null + private rowRise = 0 + private lastTool = -1 + private lastKey = '' + private model: HeadModel = 'generic' + + constructor() { + this.root.name = 'toolhead' + this.head.name = 'nozzle' + this.fixed.name = 'changer' + this.root.add(this.head, this.fixed) + this.root.visible = false + this.build() + } + + get visible(): boolean { + return this.root.visible + } + + set visible(on: boolean) { + this.root.visible = on + } + + /** The moving head with its carriage and shadow; the rack or dock stays as `visible` sets it. */ + get headVisible(): boolean { + return this.head.visible + } + + set headVisible(on: boolean) { + this.head.visible = on + } + + /** The printer family's head, drawn when the printer has one nozzle (see heads.ts). */ + setModel(model: HeadModel): void { + if (model === this.model) return + this.model = model + if (!this.spec || this.spec.kind === 'filament-swap') this.build() + } + + setSpec(spec: ToolChangerSpec | null): void { + const key = spec ? `${spec.kind}:${spec.tools}:${spec.extruderOf.join(',')}:${spec.bed.widthMm}x${spec.bed.depthMm}` : '' + if (key === this.lastKey) return + this.lastKey = key + this.spec = spec + this.build() + } + + setColors(colors: readonly string[]): void { + this.colors = colors + this.paint() + } + + private material(tool: number): MeshStandardMaterial { + const hex = displayHex(this.colors[tool] ?? this.colors[this.colors.length - 1] ?? '#9aa4c1') + let m = this.materials.get(hex) + if (!m) { + m = new MeshStandardMaterial({ color: new Color(hex), metalness: 0.1, roughness: 0.45 }) + this.materials.set(hex, m) + } + return m + } + + private paint(): void { + for (const s of this.sleeves) { + const t = s.tool() + s.mesh.material = t >= 0 ? this.material(t) : steel + } + } + + private clear(): void { + this.head.clear() + this.fixed.clear() + this.fixed.position.set(0, 0, 0) + for (const d of this.disposables) d.dispose() + this.disposables.length = 0 + this.sleeves = [] + this.left = this.right = this.carried = this.rackGroup = this.lever = this.headShadow = null + this.bay = null + this.rackSlots = [] + } + + private track(g: Group): void { + g.traverse((o) => { + if ((o as Mesh).isMesh) this.disposables.push((o as Mesh).geometry) + }) + } + + private build(): void { + this.clear() + const spec = this.spec + // A printer that only swaps filament keeps its own single head; the chute is the purge rig's. + const single = !spec || spec.kind === 'filament-swap' ? buildHead(this.model) : null + const shadow = buildShadow(single ? single.shadow : 18) + this.disposables.push(shadow.geometry, shadow.material as Material) + if (single || !spec) { + const h = single ?? buildHead(this.model) + this.head.add(shadow, h.group) + this.sleeves.push({ mesh: h.sleeve, tool: () => this.lastTool }) + } else if (spec.kind === 'dual-nozzle' || spec.kind === 'hotend-rack') { + const h = buildBambuHead(spec.nozzles?.spacing ?? 24, spec.kind === 'hotend-rack') + this.left = h.left + this.right = h.right + this.carried = h.right + this.head.add(shadow, h.group) + this.sleeves.push({ mesh: h.chip, tool: () => this.lastTool }) + if (h.rightSleeve) this.sleeves.push({ mesh: h.rightSleeve, tool: () => this.rightTool }) + if (spec.kind === 'hotend-rack' && spec.rack) this.buildRack(spec.rack) + } else if (spec.kind === 'lift-switch') { + const k = spec.lift + const spacing = k?.offsets[1]?.[0] ?? 22 + const park = k?.bayAt ?? [] + const stroke = Math.abs((park[0]?.[1] ?? 0) - (park[1]?.[1] ?? 0)) + this.leverL = leverLength(stroke > 1 ? stroke : 18) + const h = buildUltimakerHead(spacing, this.leverL) + this.left = h.left + this.right = h.right + this.lever = h.lever + this.headShadow = shadow + this.head.add(shadow, h.group) + this.sleeves.push({ mesh: h.tubes[0], tool: () => this.toolOnSide(0) }, { mesh: h.tubes[1], tool: () => this.toolOnSide(1) }) + if (k) this.buildSwitchBay(k) + } else if (spec.kind === 'xl-dock') { + // Prusa XL: the toolhead hangs behind the carriage's coupling plate. + const t = buildXlTool() + this.carried = t.group + const carriage = new Group() + carriage.name = 'carriage' + carriage.add(slab(black, -30, 30, XL.carriage[0], XL.carriage[1], 18, 88, 'carriage', 3), slab(prusaOrange, -24, -19, XL.carriage[0] - 0.4, XL.carriage[0], 26, 80, 'accent')) + this.head.add(shadow, t.group, carriage) + this.sleeves.push({ mesh: t.band, tool: () => this.carriedTool }) + if (spec.xl) this.buildXlDock(spec.xl) + } else { + // tool-rack: the toolhead hangs on the back of a white carriage by its coupling face. + const t = buildU1Toolhead() + this.carried = t.group + const carriage = new Group() + carriage.name = 'carriage' + carriage.add(slab(white, -21, 21, -34, -7.5, 24, 80, 'carriage', 6), part(new CylinderGeometry(6.5, 6.5, 0.8, 40), amber, 0, -34.4, 66, 'badge')) + this.head.add(shadow, t.group, carriage) + this.sleeves.push({ mesh: t.mark, tool: () => this.carriedTool }) + if (spec.docks) this.buildDock(spec.docks) + } + this.head.traverse((o) => void ((o as Mesh).isMesh && (((o as Mesh).castShadow = true), ((o as Mesh).receiveShadow = false)))) + shadow.castShadow = false + this.track(this.head) + this.track(this.fixed) + this.slots = [] + this.restState = null + this.paint() + } + + /** + * The H2C rack: a black frame with two rows of three holders, each a block with a white light and a fork + * that grips a hotend's collar; two posts carry the rows, which move up and down together. + */ + private buildRack(r: NonNullable): void { + const rack = new Group() + rack.name = 'rack' + this.rowRise = r.rowRise + const y0 = (r.ys[0] ?? 0) - 30 + const y1 = (r.ys[r.ys.length - 1] ?? 0) + 30 + const [tz0, tz1] = RACK.tineZ + const [tx0, tx1] = RACK.tineX + const [hx0, hx1] = RACK.holderX + const top = r.rowRise + 64 + for (const y of [y0 - 5, y1 + 5]) rack.add(part(post(3, top + 10, 20), steel, hx1 + 4, y, (top - 10) / 2, 'post')) + rack.add(slab(black, hx1, hx1 + 8, y0 - 8, y1 + 8, top, top + 6, 'top bar', 1.5)) + for (let row = 0; row < 2; row++) { + const z = row * r.rowRise + rack.add(slab(black, hx1, hx1 + 6, y0, y1, z + 22, z + 33, 'rail', 1.5)) + for (let k = 0; k < 3; k++) { + const y = r.ys[k] ?? 0 + rack.add(slab(black, hx0, hx1, y - 9, y + 9, z + 22, z + 33, 'holder', 1.5), slab(lightMat, hx0 - 0.4, hx0, y - 1.5, y + 1.5, z + 29, z + 31, 'light')) + for (const side of [-1, 1]) rack.add(slab(deep, tx0, tx1, y + side * RACK.tineY - 1.5, y + side * RACK.tineY + 1.5, z + tz0, z + tz1, 'tine')) + const h = buildVortek(false) + h.group.position.set(0, y, z) + const idx = row * 3 + k + h.group.userData.slot = idx + rack.add(h.group) + this.rackSlots.push({ group: h.group }) + this.sleeves.push({ mesh: h.sleeve, tool: () => this.slotTool(idx) }) + } + } + rack.position.set(r.x, 0, 0) + this.rackGroup = rack + this.fixed.add(rack) + } + + /** The Prusa XL dock along the back frame: a perforated black panel with a pin block behind each parked toolhead. */ + private buildXlDock(k: NonNullable): void { + const dock = new Group() + dock.name = 'dock' + const pitch = (k.x[1] ?? 82) - (k.x[0] ?? 0) + const x0 = (k.x[0] ?? 0) - pitch / 2 + const x1 = (k.x[k.x.length - 1] ?? 0) + pitch / 2 + const b0 = k.y + XL.tool.back + 1 + dock.add(slab(black, x0, x1, b0 + 8, b0 + 12, 10, 100, 'panel', 1.5)) + for (let i = 0; i < 9; i++) dock.add(slab(deep, x0 + 6, x1 - 6, b0 + 7.6, b0 + 8, 20 + i * 8, 24 + i * 8, 'vent')) + k.x.forEach((x, i) => { + const t = buildXlTool() + t.group.position.set(x, k.y, 0) + t.group.userData.slot = i + dock.add(t.group, slab(graphite, x - 14, x + 14, b0, b0 + 7.6, 34, 82, 'pins', 1), part(post(2.2, 14, 16), steel, x + 20, b0 + 4, 58, 'pin')) + this.rackSlots.push({ group: t.group }) + this.sleeves.push({ mesh: t.band, tool: () => this.slotTool(i) }) + }) + this.fixed.add(dock) + } + + /** + * The UltiMaker switch bay on the right wall: a white block with a slot the lever's pin runs in. It stands where + * the pin arrives when the head runs into the bay from either switching position. + */ + private bay: { x: number; y: number } | null = null + private buildSwitchBay(k: NonNullable): void { + const [ax, ay] = k.bayAt[0] ?? [0, 0] + const by = k.bayAt[1]?.[1] ?? ay + const L = this.leverL + const x = ax + k.bayIn + UM.lever.x + L * Math.cos(UM.lever.swing) + const y = (ay + by) / 2 + UM.lever.y + this.bay = { x, y } + // The slot is a little wider than the pin, so the pin turns in it as the lever swings. + const r = UM.lever.pinR * Math.SQRT2 + 0.05 + const bay = new Group() + bay.name = 'switch bay' + bay.add( + slab(white, x - 8, x + 6, y + r, y + r + 3, UM.lever.z1, UM.lever.pinTop, 'prong', 0.6), + slab(white, x - 8, x + 6, y - r - 3, y - r, UM.lever.z1, UM.lever.pinTop, 'prong', 0.6), + slab(white, x + 6, x + 16, y - 12, y + 12, UM.lever.z1, 72, 'bay', 1.5), + ) + this.fixed.add(bay) + } + + /** The U1 dock: a black beam along the back with a bracket behind each parked toolhead. */ + private buildDock(d: NonNullable): void { + const dock = new Group() + dock.name = 'dock' + const pitch = (d.x[1] ?? 60) - (d.x[0] ?? 0) + const x0 = (d.x[0] ?? 0) - pitch / 2 + const x1 = (d.x[d.x.length - 1] ?? 0) + pitch / 2 + dock.add(slab(black, x0, x1, d.y + 58, d.y + 66, 60, 76, 'beam', 1.5)) + d.x.forEach((x, i) => { + const t = buildU1Toolhead() + t.group.position.set(x, d.y, 0) + t.group.userData.slot = i + dock.add(t.group, slab(graphite, x - 16, x + 16, d.y + 55, d.y + 58, 20, 75, 'bracket', 1)) + this.rackSlots.push({ group: t.group }) + this.sleeves.push({ mesh: t.mark, tool: () => this.slotTool(i) }) + }) + this.fixed.add(dock) + } + + // ---- state read by the sleeves + private slots: number[] = [] + private rightTool = -1 + private carriedTool = -1 + private toolOnSide(side: number): number { + const spec = this.spec + if (!spec) return this.lastTool + if ((spec.extruderOf[this.lastTool] ?? 0) === side) return this.lastTool + return spec.extruderOf.findIndex((e) => e === side) + } + private slotTool(i: number): number { + return this.slots[i] ?? -1 + } + + /** + * Rack and dock contents when no change is playing: what the last change left (`rest`), or before the first + * change the rack as the print starts (every tool but the one in the head). + */ + private restSlots(tool: number): number[] { + const spec = this.spec + if (!spec) return [] + if (this.restState) return this.restState + if (spec.kind === 'tool-rack') return (spec.docks?.x ?? []).map((_, i) => (i === tool ? -1 : i)) + if (spec.kind === 'xl-dock') return (spec.xl?.x ?? []).map((_, i) => (i === tool ? -1 : i)) + if (spec.kind === 'hotend-rack') return rackStateBefore(spec, []).slots + return [] + } + + /** + * Places the head with its active nozzle tip at (x, y, z) printing `tool`, or, with `pose`, mid change: + * the pose says where the head is, what it carries, how far the idle nozzle is lifted and what the rack holds. + */ + place(x: number, y: number, z: number, tool: number, pose: Pose | null, slots: number[] | null): void { + const spec = this.spec + this.lastTool = tool + const px = pose ? pose.x : x + const py = pose ? pose.y : y + const pz = (pose ? pose.z : z) + 0.05 + if (!spec || spec.kind === 'filament-swap') { + // Through a filament change the inlet shows the old filament until the new one loads. + if (pose) this.lastTool = pose.carried ?? tool + this.head.position.set(px, py, pz) + this.paint() + return + } + if (spec.kind === 'tool-rack' || spec.kind === 'xl-dock') { + this.carriedTool = pose ? (pose.carried ?? -1) : tool + this.slots = slots ?? (pose ? pose.slots : this.restSlots(tool)) + if (this.carried) { + this.carried.visible = this.carriedTool >= 0 + // The release stroke slides the carriage off a toolhead that is already seated: the toolhead stays in its slot. + this.carried.position.x = spec.kind === 'tool-rack' && pose?.phase === 'release' ? -(1 - pose.latch) * (spec.docks?.strokeX ?? 0) : 0 + } + for (const [i, s] of this.rackSlots.entries()) s.group.visible = (this.slots[i] ?? -1) >= 0 + this.head.position.set(px, py, pz) + // The dock keeps the head's height (the frame carries both). + this.fixed.position.z = pz + this.paint() + return + } + if (spec.kind === 'lift-switch') { + this.placeUltimaker(spec, x, y, z, tool, pose) + return + } + const s = spec.nozzles?.spacing ?? 24 + const liftMm = spec.nozzles?.liftMm ?? 2.5 + const side = pose ? pose.lift : (spec.extruderOf[tool] ?? 0) > 0 ? 1 : 0 + // The active nozzle sits at the point; the idle one is lifted. Between, both move as the lift rail does. + const u = Math.min(1, Math.max(0, side)) + this.head.position.set(px + (0.5 - u) * s, py, pz) + if (this.left) this.left.position.z = u * liftMm + if (this.right) this.right.position.z = (1 - u) * liftMm + if (spec.kind === 'hotend-rack') { + const rackExtruder = Math.max(...spec.extruderOf, 0) + this.slots = slots ?? (pose ? pose.slots : this.restSlots(tool)) + const held = pose ? pose.carried : spec.extruderOf[tool] === rackExtruder ? tool : this.rightToolAtRest() + this.rightTool = held ?? -1 + if (this.carried) this.carried.visible = this.rightTool >= 0 + // A spare hotend (SPARE) is drawn too; only an empty position shows nothing. + for (const [i, sl] of this.rackSlots.entries()) sl.group.visible = (this.slots[i] ?? -1) !== -1 + if (this.rackGroup) { + const row = pose ? pose.row : this.row + this.rackGroup.position.z = pz - row * this.rowRise + } + } else { + this.rightTool = this.toolOnSide(1) + } + this.paint() + } + + /** + * UltiMaker S: the head stands with the printing core's tip at the move (the left tip higher by the lowered right + * core's depth while the right one prints), or where the change's pose puts the left tip. The right core rides the + * lift switch: lifted over the left tip, or lowered under it. While the firmware runs the lever along the bay, the + * lever's pin stays in the bay's slot and the lever's angle sets the right core's height. + */ + private placeUltimaker(spec: ToolChangerSpec, x: number, y: number, z: number, tool: number, pose: Pose | null): void { + const k = spec.lift + const side = (spec.extruderOf[tool] ?? 0) > 0 ? 1 : 0 + const off = k?.offsets[spec.extruderOf[tool] ?? 0] ?? [0, 0] + const lowered = k?.lowered ?? 1.5 + const stroke = k?.stroke ?? 3 + let u = pose ? pose.lift : side + const hx = pose ? pose.x : x - off[0] + const hy = pose ? pose.y : y - off[1] + const hz = (pose ? pose.z : z + side * lowered) + 0.05 + let angle = -UM.lever.swing + 2 * UM.lever.swing * Math.min(1, Math.max(0, u)) + if (pose?.phase === 'switch' && this.bay) { + // The pin is held in the slot: the head's y decides the angle, and the angle the core's height. + const s = Math.min(1, Math.max(-1, (this.bay.y - (hy + UM.lever.y)) / this.leverL)) + angle = Math.asin(s) + u = (angle + UM.lever.swing) / (2 * UM.lever.swing) + } + this.head.position.set(hx, hy, hz) + if (this.right) this.right.position.z = stroke - lowered - stroke * Math.min(1, Math.max(0, u)) + if (this.lever) this.lever.rotation.z = angle + if (this.headShadow) this.headShadow.position.z = -0.02 - Math.min(1, Math.max(0, u)) * lowered + this.fixed.position.z = hz + this.paint() + } + + private row = 0 + private restState: number[] | null = null + /** The rack row and contents the last change left behind (null before the first), for the frames after it. */ + rest(slots: number[] | null, row: number): void { + this.restState = slots + this.row = row + } + + private rightToolAtRest(): number { + const spec = this.spec + if (!spec) return -1 + const rackExtruder = Math.max(...spec.extruderOf, 0) + const onRack = Array.from({ length: spec.tools }, (_, t) => t).filter((t) => spec.extruderOf[t] === rackExtruder) + return onRack.find((t) => !this.slots.includes(t)) ?? onRack[0] ?? -1 + } + + /** Draws far below the bed so the shaders exist before the first scrub (see Toolpaths.warmNozzle). */ + warm(on: boolean): void { + this.root.visible = on + this.head.visible = on + this.root.traverse((o) => void (o.frustumCulled = !on)) + if (on) this.head.position.set(0, 0, -400) + } + + dispose(): void { + this.clear() + for (const m of this.materials.values()) m.dispose() + this.materials.clear() + } +} diff --git a/desktop/src/vendor/slicerx/viewport/toolpaths.ts b/desktop/src/vendor/slicerx/viewport/toolpaths.ts new file mode 100644 index 00000000..799f2954 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/toolpaths.ts @@ -0,0 +1,1373 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Preview renderer for SXPV toolpath buffers. The raw segment records go to +// the GPU as they are (32 bytes each, read as two uvec4 instance attributes), +// and the vertex shader expands every record into a bead with a diamond +// cross-section (8 vertices, 8 triangles). The CPU never +// builds triangles. Layer and move scrubbing only rebind the instance range, +// and color modes only change a uniform. +// --------------------------------------------------------------------------------------------------------------- +// MODIFIED BY SNAPMAKER STUDIO (DVOpenLabs/snapmaker-studio): the only change in this file is the import path of the +// contracts module ('@slicerx/contracts' -> '../contracts/index'). Upstream: slicerx-oss/slicerx @ +// edb521fe41306dd60d01bda8a0f6bf8aa54fcb29 (Apache-2.0). See ../UPDATING.md. +// --------------------------------------------------------------------------------------------------------------- +import { + BufferAttribute, + BufferGeometry, + Color, + DataTexture, + FloatType, + Group, + InstancedBufferGeometry, + InstancedInterleavedBuffer, + InterleavedBufferAttribute, + LinearFilter, + LineBasicMaterial, + LineSegments, + Mesh, + MeshDepthMaterial, + MeshPhongMaterial, + MeshPhysicalMaterial, + NearestFilter, + Points, + RedFormat, + RGBADepthPacking, + RGBAFormat, + ShaderMaterial, + Vector3, + Vector4, + type WebGLProgramParametersWithUniforms, +} from 'three' +import { SXPV_EXTRA_BYTES, SXPV_EXTRA_FLAG, SXPV_SEGMENT, SXPV_SEGMENT_BYTES, SXPV_TRAVEL_BYTES, objectOfSegment, type PreviewBuffers } from '../contracts/index' +import type { MarkerKind, PreviewExtras, PreviewRanges } from './types' +import { DEFAULT_TOOL_COLORS, FEATURE_COLORS, HEAT_RAMP, SCENE, displayHex, hexToRgb, srgbToLinear, type ResolvedTheme, type SceneColors } from './palette' +import type { ColorMode, FilamentFinish, ToolpathFinish } from './types' +import { ToolheadRig } from './toolhead' +import { PurgeRig, type PurgePlan } from './purge' +import { GantryRig, type GantryHit, type GantrySpec } from './gantry' +import type { HeadModel } from './heads' +import { headAt, type HeadSeg } from './headpath' +import { changeSequence, poseAt, printedTop, type ChangeSequence, type ToolChangerSpec, type V3 } from './toolchanger' + +/** Instances per draw call. Keeps each GPU buffer well under driver limits. */ +const CHUNK = 1 << 20 +const LAYER_LUT_W = 1024 +const COLOR_MODE: Record = { feature: 0, tool: 1, speed: 2, flow: 3, layerTime: 4, width: 5, height: 6, fan: 7, temperature: 8 } + +export const MARKER_KINDS: readonly MarkerKind[] = ['retractions', 'seams', 'lifts', 'wipes', 'toolChanges', 'pauses'] +/** Point shape per kind: 0 disc, 1 square, 2 diamond. */ +const MARKER_SHAPE: Record = { retractions: 0, seams: 0, lifts: 0, wipes: 2, toolChanges: 1, pauses: 1 } + +function markerColorsOf(scene: Pick): Record { + return { retractions: scene.retraction, seams: scene.seam, lifts: scene.lift, wipes: scene.wipe, toolChanges: scene.toolChange, pauses: scene.pause } +} + +/** + * Base bead: a 4-point diamond profile at both ends, 8 vertices and 8 triangles. + * position = (across, up, along), normal = (across, up, along). There are no caps: the far + * end is pushed half a line width past the segment end (see sxBead), so each bead overlaps + * the start of the next one and corners close. Caps cost far more than their few pixels: + * on Apple GPUs a capped bead took about 2.4 times as long per frame. + */ +function beadGeometry(): InstancedBufferGeometry { + const prof: [number, number][] = [[1, 0], [0, 1], [-1, 0], [0, -1]] + const pos: number[] = [] + const nrm: number[] = [] + for (let t = 0; t < 2; t++) { + for (const [u, v] of prof) { + pos.push(u, v, t) + nrm.push(u, v, 0) + } + } + const idx: number[] = [] + for (let i = 0; i < 4; i++) { + const j = (i + 1) % 4 + idx.push(i, 4 + i, 4 + j, i, 4 + j, j) + } + const g = new InstancedBufferGeometry() + g.setAttribute('position', new BufferAttribute(new Float32Array(pos), 3)) + g.setAttribute('normal', new BufferAttribute(new Float32Array(nrm), 3)) + g.setIndex(idx) + return g +} + +const BEAD_DECL = /* glsl */ ` +in uvec4 aSegA; +in uvec4 aSegB; +in float aLayer; +in vec2 aExtra; +uniform uint uFeatureMask; +uniform vec2 uWidthRange; +uniform vec2 uHeightRange; +uniform vec2 uFanRange; +uniform vec2 uTempRange; +uniform float uHasExtras; +uniform float uCurLayer; +uniform int uColorMode; +uniform sampler2D uFeatureLut; +uniform sampler2D uToolLut; +uniform sampler2D uFinishLut; +uniform sampler2D uRamp; +uniform sampler2D uLayerLut; +uniform vec2 uSpeedRange; +uniform vec2 uFlowRange; +uniform vec3 uCamObj; +uniform float uViewH; +uniform vec4 uPartSeg; +uniform float uPartZ; +uniform float uPartFrac; +varying vec3 vSegColor; +varying float vLive; +varying vec4 vFinish; +varying float vSurf; +// Across and along the bead in plate space, and how far the normals keep their round shape (1) or turn to face the camera +// (level of detail): sxBead sets them for the per-pixel shading. +vec2 sxSide; +vec2 sxDir; +float sxK = 1.0; +float sxPx = 8.0; +void sxBead(out vec3 p, out vec3 n) { + vec2 a = vec2(uintBitsToFloat(aSegA.x), uintBitsToFloat(aSegA.y)); + vec2 b = vec2(uintBitsToFloat(aSegA.z), uintBitsToFloat(aSegA.w)); + float zTop = uintBitsToFloat(aSegB.x); + // Playback: the move under the nozzle is drawn only as far as the head has gone along it. + if (uPartFrac < 1.0 && a == uPartSeg.xy && b == uPartSeg.zw && zTop == uPartZ) b = mix(a, b, uPartFrac); + float hw = float(aSegB.y & 0xffffu) * 0.0005; + float hh = float(aSegB.y >> 16u) * 0.0005; + vec2 d = b - a; + float len = length(d); + vec2 dir = len > 1e-6 ? d / len : vec2(1.0, 0.0); + vec2 side = vec2(dir.y, -dir.x); + sxSide = side; + sxDir = dir; + vec2 base = mix(a, b, position.z) + side * (position.x * hw) + dir * (position.z * hw); + p = vec3(base, zTop - hh + position.y * hh); + // Hidden feature types collapse to a point far outside the view, so they draw nothing and cast no shadow. + if (((uFeatureMask >> min(aSegB.z & 0xffu, 31u)) & 1u) == 0u) { p = vec3(0.0, 0.0, -1.0e6); n = vec3(0.0, 0.0, 1.0); return; } + n = normalize(vec3(side * normal.x + dir * normal.z, normal.y)); + // Level of detail: when a bead is only a few pixels tall its ridge normals alias into + // moire, so they blend toward the normal of a round bead facing the camera. + float depth = max(1e-3, -(modelViewMatrix * vec4(p, 1.0)).z); + float px = 2.0 * hh * projectionMatrix[1][1] * 0.5 * uViewH / depth; + sxPx = px; + float k = mix(0.3, 1.0, smoothstep(0.7, 2.2, px)); + sxK = abs(aLayer - uCurLayer) > 0.5 ? k : 1.0; + if (k < 1.0 && abs(aLayer - uCurLayer) > 0.5) { + vec3 d3 = vec3(dir, 0.0); + vec3 v = normalize(uCamObj - p); + vec3 f = v - d3 * dot(v, d3); + float fl = length(f); + if (fl > 1e-4) n = normalize(mix(f / fl, n, k)); + } +} +` + +const BEAD_COLOR = /* glsl */ ` +{ + uint feat = aSegB.z & 0xffu; + uint tool = (aSegB.z >> 8u) & 0xffu; + vec3 c; + if (uColorMode == 0) c = texelFetch(uFeatureLut, ivec2(int(min(feat, 15u)), 0), 0).rgb; + else if (uColorMode == 1) c = texelFetch(uToolLut, ivec2(int(min(tool, 15u)), 0), 0).rgb; + else if (uColorMode == 2) { + float s = float(aSegB.z >> 16u) * 0.1; + c = texture(uRamp, vec2(clamp((s - uSpeedRange.x) / max(1e-3, uSpeedRange.y - uSpeedRange.x), 0.0, 1.0), 0.5)).rgb; + } else if (uColorMode == 3) { + float f = uintBitsToFloat(aSegB.w); + c = texture(uRamp, vec2(clamp((f - uFlowRange.x) / max(1e-4, uFlowRange.y - uFlowRange.x), 0.0, 1.0), 0.5)).rgb; + } else if (uColorMode == 5) { + float w = float(aSegB.y & 0xffffu) * 0.001; + c = texture(uRamp, vec2(clamp((w - uWidthRange.x) / max(1e-4, uWidthRange.y - uWidthRange.x), 0.0, 1.0), 0.5)).rgb; + } else if (uColorMode == 6) { + float h = float(aSegB.y >> 16u) * 0.001; + c = texture(uRamp, vec2(clamp((h - uHeightRange.x) / max(1e-4, uHeightRange.y - uHeightRange.x), 0.0, 1.0), 0.5)).rgb; + } else if (uColorMode == 7) { + c = uHasExtras > 0.5 ? texture(uRamp, vec2(clamp((aExtra.x - uFanRange.x) / max(1e-4, uFanRange.y - uFanRange.x), 0.0, 1.0), 0.5)).rgb : vec3(0.3); + } else if (uColorMode == 8) { + c = uHasExtras > 0.5 ? texture(uRamp, vec2(clamp((aExtra.y - uTempRange.x) / max(1e-4, uTempRange.y - uTempRange.x), 0.0, 1.0), 0.5)).rgb : vec3(0.3); + } else { + int li = int(aLayer); + float t = texelFetch(uLayerLut, ivec2(li % ${LAYER_LUT_W}, li / ${LAYER_LUT_W}), 0).r; + c = texture(uRamp, vec2(t, 0.5)).rgb; + } + vSegColor = c; + vFinish = texelFetch(uFinishLut, ivec2(int(min(tool, 15u)), 0), 0); + // What surface the bead belongs to from afar: a wall (1), a flat top, bottom or solid layer (2), anything else (0). + vSurf = feat <= 2u || feat == 13u ? 1.0 : feat == 3u || feat == 4u || feat == 5u || feat == 7u || feat == 11u ? 2.0 : 0.0; + // Only the walls of the live layer glow, so it reads as a lit ring at the nozzle height rather than a plane. + vLive = abs(aLayer - uCurLayer) < 0.5 && feat <= 2u ? 1.0 : 0.0; +} +` + +/** Declarations for per-vertex bead lighting; three.js supplies the light and shadow uniforms. */ +const BEAD_LIGHT_DECL = /* glsl */ ` +#include +#include +#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 +uniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; +#endif +uniform vec3 uEnvSH[ 9 ]; +uniform float uEnvDiffuse; +uniform float uEnvSpec; +uniform vec3 uLiveColor; +uniform float uGlow; +varying vec3 vLit; +` + +/** Runs after three.js computed transformedNormal, mvPosition and the shadow coordinates. */ +const BEAD_LIGHT = /* glsl */ ` +{ + vec3 n = normalize( transformedNormal ); + vec3 v = normalize( - mvPosition.xyz ); + vec3 albedo = vSegColor; + vec3 c = getLightProbeIrradiance( uEnvSH, n ) * uEnvDiffuse * BRDF_Lambert( albedo ); + #if NUM_DIR_LIGHTS > 0 + IncidentLight L; + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + getDirectionalLightInfo( directionalLights[ i ], L ); + float shadow = 1.0; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + if ( i == 0 && receiveShadow ) { + // three.js orders shadow-casting lights first, so light 0 is the key light and owns shadow map 0. + vec4 sc = vDirectionalShadowCoord[ 0 ]; + sc.xyz /= sc.w; + sc.z += directionalLightShadows[ 0 ].shadowBias; + if ( sc.x >= 0.0 && sc.x <= 1.0 && sc.y >= 0.0 && sc.y <= 1.0 && sc.z <= 1.0 ) { + shadow = mix( 1.0, texture( directionalShadowMap[ 0 ], sc.xyz ), directionalLightShadows[ 0 ].shadowIntensity ); + } + } + #endif + vec3 irr = saturate( dot( n, L.direction ) ) * L.color * shadow; + c += irr * ( BRDF_Lambert( albedo ) + BRDF_BlinnPhong( L.direction, v, n, vec3( 0.04 ), 36.0 ) ); + } + #endif + vec3 fr = F_Schlick( vec3( 0.04 ), 1.0, saturate( dot( n, v ) ) ); + // The glossy environment term uses the room's mean radiance (the SH constant band): at this + // roughness the reflection is a soft wash, and one lookup less per vertex is measurable. + c += uEnvSH[ 0 ] * 0.886227 * RECIPROCAL_PI * fr * uEnvSpec; + if ( vLive > 0.5 ) { + float rim = pow( 1.0 - saturate( abs( dot( n, v ) ) ), 1.5 ); + c += mix( albedo, uLiveColor, 0.9 ) * ( 0.7 + rim * uGlow ); + } + vLit = c; +} +` + +/** + * Per-pixel bead shading. The vertex shader hands over the bead's frame in view space and where on its cross-section the + * vertex sits; across a face the profile point runs along the diamond's edge, so normalizing it per pixel gives the + * normal of a round bead. The beads are then lit by three.js's physical material, the one the model view uses, with the + * same room, lights, finish and tone, so a sliced plate reads like the model. + */ +const BEAD_PIXEL_DECL = /* glsl */ ` +varying vec3 vSideV; +varying vec3 vUpV; +varying vec3 vAlongV; +varying vec2 vProf; +varying float vK; +varying float vLayer; +varying float vBeadPx; +` + +const BEAD_PIXEL = /* glsl */ ` +{ + vSideV = normalize( normalMatrix * vec3( sxSide, 0.0 ) ); + vUpV = normalize( normalMatrix * vec3( 0.0, 0.0, 1.0 ) ); + vAlongV = normalize( normalMatrix * vec3( sxDir, 0.0 ) ); + vProf = position.xy; + vK = sxK; + vLayer = aLayer; + vBeadPx = sxPx; +} +` + +/** Declarations the bead fragment code below reads, on top of the physical material's own. */ +const BEAD_FRAG_DECL = /* glsl */ ` +uniform vec3 uLiveColor; +uniform float uGlow; +uniform float uCrease; +uniform float uStale; +varying vec3 vSegColor; +varying float vLive; +varying vec4 vFinish; +varying float vSurf; +${BEAD_PIXEL_DECL} +` + +/** + * The bead's normal per pixel. Where the cross-section turns more than about half its width within one pixel its detail + * cannot be drawn, so the round normal fades out there and a bead a pixel or two tall shades evenly instead of in moire. + * From afar a bead stands for the surface it is part of: stacked walls face out, solid layers face up, and a lone bead + * (infill, support) shows its round side to the camera. `sxOcc` is the groove where a bead sits on the one below; it + * lasts a little longer than the round shape, so layer lines still read at a middle distance. + */ +const BEAD_NORMAL = /* glsl */ ` +float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +float sxPl = length( vProf ); +vec2 sxQ = sxPl > 1e-4 ? vProf / sxPl : vec2( 0.0, 1.0 ); +// The part of a bead that shows: in a wall the beads above and below hide most of its top and bottom, in a solid layer +// its neighbors hide its sides. The hidden part's normals are squashed out, so a wall keeps its face's light. +vec2 sxShow = vSurf > 1.5 ? vec2( 0.6, 1.0 ) : vSurf > 0.5 ? vec2( 1.0, 0.6 ) : vec2( 1.0 ); +vec3 sxRound = normalize( vSideV * sxQ.x * sxShow.x + vUpV * sxQ.y * sxShow.y ); +float sxFw = fwidth( vProf.x ) + fwidth( vProf.y ); +float sxKeep = vK * saturate( 1.6 - 1.4 * sxFw ); +vec3 sxV = normalize( vViewPosition ); +vec3 sxAcross = sxV - vAlongV * dot( sxV, vAlongV ); +vec3 sxFacing = length( sxAcross ) > 1e-4 ? normalize( sxAcross ) : vUpV; +// The side of the bead this face is on (from the profile, not the view, so a face seen edge-on never flips). +vec3 sxOut = sxQ.x >= 0.0 ? vSideV : - vSideV; +vec3 sxMacro = vSurf > 1.5 ? vUpV : vSurf > 0.5 ? normalize( sxOut + vUpV * 0.15 ) : sxFacing; +vec3 normal = sxKeep >= 0.999 ? sxRound : normalize( mix( sxMacro, sxRound, sxKeep ) ); +vec3 nonPerturbedNormal = normal; +// The groove under a wall bead or beside a solid-layer bead, while the bead's cross-section is drawn. +float sxEdge = vSurf > 1.5 ? abs( sxQ.x ) : - sxQ.y; +float sxOcc = 1.0 - uCrease * smoothstep( 0.3, 0.97, sxEdge ) * sxKeep; +// Farther out a wall's layers read as even lines, the way the model view draws them: a darker band under every layer +// while a layer is a few pixels tall, then under every 2nd, 4th, 8th layer as they shrink, so the lines stay about +// three pixels apart and never turn to moire. +if ( vSurf > 0.5 && vSurf < 1.5 ) { + // The bead's height on screen comes from the vertex shader, smooth across the wall, so neighbors pick the same lines. + float sxEvery = exp2( max( 0.0, ceil( log2( 3.0 / max( vBeadPx, 0.05 ) ) ) ) ); + float sxFirst = mod( vLayer + 0.5, sxEvery ) < 1.0 ? 1.0 : 0.0; + // The whole bead darkens, not just its lower edge: a band a pixel or two tall that sampling cannot break into dots. + float sxStripe = sxFirst * ( 1.0 - smoothstep( 8.0, 32.0, sxEvery ) ) * min( 1.0, 2.0 / sxEvery + 0.5 ); + sxOcc = mix( 1.0 - 0.22 * sxStripe, sxOcc, smoothstep( 3.0, 6.0, vBeadPx ) ); +} +` + +/** The finish's gloss on top of the physical material's (one value per tool): clearcoat and sheen, as the model view sets them. */ +const BEAD_FINISH = /* glsl */ ` +#ifdef USE_CLEARCOAT +material.clearcoat = vFinish.y; +#endif +#ifdef USE_SHEEN +material.sheenColor = mix( diffuseColor.rgb, vec3( 1.0 ), 0.45 ) * vFinish.z; +#endif +` + +/** Stale paths (the plate changed, a new slice is coming) are drawn darker and less saturated, never hidden. */ +const BEAD_STALE = /* glsl */ ` +outgoingLight = mix( outgoingLight, vec3( dot( outgoingLight, vec3( 0.299, 0.587, 0.114 ) ) ), 0.5 * uStale ) * ( 1.0 - 0.35 * uStale ); +` + +/** The groove's occlusion, the silk streak along the bead, and the live layer's glow. */ +const BEAD_AFTER_LIGHTS = /* glsl */ ` +reflectedLight.indirectDiffuse *= sxOcc; +reflectedLight.directDiffuse *= sxOcc; +reflectedLight.directSpecular *= mix( 1.0, sxOcc, 0.5 ); +reflectedLight.indirectSpecular *= mix( 1.0, sxOcc, 0.5 ); +#if NUM_DIR_LIGHTS > 0 +if ( vFinish.w > 0.0 ) { + // Silk: a bright streak across the bead, along its length (Kajiya-Kay), tinted by the filament. + vec3 sxL = directionalLights[ 0 ].direction; + float sxTh = dot( vAlongV, normalize( sxL + sxV ) ); + float sxStreak = pow( sqrt( max( 0.0, 1.0 - sxTh * sxTh ) ), 90.0 ) * vFinish.w * 0.5 * saturate( dot( normal, sxL ) ); + reflectedLight.directSpecular += sxStreak * directionalLights[ 0 ].color * mix( vec3( 1.0 ), diffuseColor.rgb, 0.55 ); +} +#endif +if ( vLive > 0.5 ) { + float sxRim = pow( 1.0 - saturate( abs( dot( normal, sxV ) ) ), 1.5 ); + totalEmissiveRadiance += mix( diffuseColor.rgb, uLiveColor, 0.9 ) * ( 0.7 + sxRim * uGlow ); +} +` + +/** + * Fan, nozzle temperature, retraction and seam markers read from the per-segment extras of an SXPV + * buffer, or null when it has none. Retractions and seams are placed at the start of the segment + * that carries the flag. + */ +export function extrasFromBuffers(b: PreviewBuffers): PreviewExtras | null { + if (b.extrasOffset < 0) return null + const S = b.segmentCount + const ex = new Uint8Array(b.raw, b.extrasOffset, S * SXPV_EXTRA_BYTES) + const exView = new DataView(b.raw, b.extrasOffset, S * SXPV_EXTRA_BYTES) + const seg = new Float32Array(b.raw, b.segmentsOffset, S * (SXPV_SEGMENT_BYTES / 4)) + const fan = new Uint8Array(S) + const temp = new Uint16Array(S) + const retr: number[] = [] + const seams: number[] = [] + const lifts: number[] = [] + for (let i = 0; i < S; i++) { + const o = i * SXPV_EXTRA_BYTES + fan[i] = Math.round(((ex[o] ?? 0) * 100) / 255) + temp[i] = exView.getUint16(o + 2, true) + const flags = ex[o + 1] ?? 0 + if (flags & (SXPV_EXTRA_FLAG.retract | SXPV_EXTRA_FLAG.seam | SXPV_EXTRA_FLAG.lift)) { + const q = i * (SXPV_SEGMENT_BYTES / 4) + const x = seg[q] ?? 0 + const y = seg[q + 1] ?? 0 + const z = seg[q + 4] ?? 0 + if (flags & SXPV_EXTRA_FLAG.retract) retr.push(x, y, z) + if (flags & SXPV_EXTRA_FLAG.seam) seams.push(x, y, z) + if (flags & SXPV_EXTRA_FLAG.lift) lifts.push(x, y, z) + } + } + return { fanPct: fan, nozzleC: temp, retractions: new Float32Array(retr), seams: new Float32Array(seams), lifts: new Float32Array(lifts) } +} + +function layerOfSegment(b: PreviewBuffers, segment: number): number { + let lo = 0 + let hi = b.layerCount - 1 + while (lo < hi) { + const mid = (lo + hi + 1) >> 1 + if ((b.layerStart[mid] ?? 0) <= segment) lo = mid + else hi = mid - 1 + } + return lo +} + +/** G-code line (1-based) of a segment, or 0 when unknown. */ +export function gcodeLineOf(b: PreviewBuffers, segment: number): number { + if (b.extrasOffset < 0 || segment < 0 || segment >= b.segmentCount) return 0 + return new DataView(b.raw).getUint32(b.extrasOffset + segment * SXPV_EXTRA_BYTES + 4, true) +} + +/** Layer index whose top is at or just above `z` (markers sit on the layer they were printed in). */ +export function layerOfZ(layerZ: ArrayLike, z: number): number { + let lo = 0 + let hi = layerZ.length - 1 + while (lo < hi) { + const mid = (lo + hi) >> 1 + if ((layerZ[mid] ?? 0) + 1e-3 < z) lo = mid + 1 + else hi = mid + } + return lo +} + +/** + * How each finish lights, as the bead shader reads it: roughness, clearcoat, sheen and the silk streak. They are the + * model view's values for the same finish (studioMaterial), so a matte or silk print looks the same sliced or not. + */ +export const BEAD_FINISHES: Record = { + matte: [0.82, 0, 0.35, 0], + satin: [0.52, 0.16, 0.3, 0], + glossy: [0.3, 0.6, 0.2, 0], + silk: [0.26, 1, 0.9, 1], +} + +/** The finish a model part's look draws its toolpaths with. */ +export function beadFinish(f: FilamentFinish | ToolpathFinish | undefined): ToolpathFinish { + return f === 'matte' || f === 'silk' || f === 'glossy' ? f : f === 'petg' || f === 'translucent' ? 'glossy' : 'satin' +} + +/** One finish per tool (16 at most), satin for tools without one. */ +function finishTexture(finishes: readonly (ToolpathFinish | undefined)[], size = 16): DataTexture { + const data = new Float32Array(size * 4) + for (let i = 0; i < size; i++) data.set(BEAD_FINISHES[finishes[i] ?? finishes[0] ?? 'satin'], i * 4) + const t = new DataTexture(data, size, 1, RGBAFormat, FloatType) + t.minFilter = NearestFilter + t.magFilter = NearestFilter + t.needsUpdate = true + return t +} + +function lutTexture(colors: readonly string[], size = 16): DataTexture { + const data = new Float32Array(size * 4) + for (let i = 0; i < size; i++) { + const hex = colors[i] ?? colors[colors.length - 1] ?? '#ffffff' + const [r, g, b] = hexToRgb(displayHex(hex)) + data[4 * i] = srgbToLinear(r) + data[4 * i + 1] = srgbToLinear(g) + data[4 * i + 2] = srgbToLinear(b) + data[4 * i + 3] = 1 + } + const t = new DataTexture(data, size, 1, RGBAFormat, FloatType) + t.minFilter = t.magFilter = NearestFilter + t.needsUpdate = true + return t +} + +function rampTexture(stops: readonly string[], size = 256): DataTexture { + const data = new Float32Array(size * 4) + const lin = stops.map((h) => hexToRgb(h).map(srgbToLinear)) + for (let i = 0; i < size; i++) { + const t = (i / (size - 1)) * (lin.length - 1) + const k = Math.min(lin.length - 2, Math.floor(t)) + const f = t - k + const a = lin[k] ?? [0, 0, 0] + const b = lin[k + 1] ?? a + for (let j = 0; j < 3; j++) data[4 * i + j] = (a[j] ?? 0) + ((b[j] ?? 0) - (a[j] ?? 0)) * f + data[4 * i + 3] = 1 + } + const t = new DataTexture(data, size, 1, RGBAFormat, FloatType) + t.minFilter = t.magFilter = LinearFilter + t.needsUpdate = true + return t +} + +/** One segment far below the bed, used to compile the bead shaders before the first real preview arrives. */ +export function warmupBuffers(): PreviewBuffers { + const N = 1 + const raw = new ArrayBuffer(32 + (N + 1) * 4 + N * 8 + SXPV_SEGMENT_BYTES) + const layerStart = new Uint32Array(raw, 32, N + 1) + layerStart.set([0, 1]) + const layerZ = new Float32Array(raw, 32 + (N + 1) * 4, N) + const layerTimeS = new Float32Array(raw, 32 + (N + 1) * 4 + N * 4, N) + const segmentsOffset = 32 + (N + 1) * 4 + N * 8 + const f = new Float32Array(raw, segmentsOffset, 8) + const u = new Uint32Array(raw, segmentsOffset, 8) + f.set([0, 0, 1, 0, -500]) + u[5] = 420 | (200 << 16) + return { raw, version: 1, segmentCount: 1, layerCount: N, travelCount: 0, toolCount: 1, layerHeight: 0.2, layerStart, layerZ, layerTimeS, travelStart: null, segmentsOffset, travelsOffset: -1, extrasOffset: -1, travelFlagsOffset: -1, objectsOffset: -1 } +} + +interface Chunk { + start: number + end: number + mesh: Mesh + geo: InstancedBufferGeometry + seg: InstancedInterleavedBuffer + layer: InstancedInterleavedBuffer + drawn: [number, number] + extra?: InstancedInterleavedBuffer | undefined +} + +export class Toolpaths { + readonly root = new Group() + private readonly base = beadGeometry() + private readonly material: MeshPhongMaterial | MeshPhysicalMaterial + private readonly depthMaterial: MeshDepthMaterial + private readonly uniforms = { + uCurLayer: { value: -1 }, + uColorMode: { value: 0 }, + uFeatureLut: { value: lutTexture(FEATURE_COLORS.map((f) => f.color)) }, + uToolLut: { value: lutTexture(DEFAULT_TOOL_COLORS) }, + uFinishLut: { value: finishTexture([]) }, + uCrease: { value: 0.55 }, + uRamp: { value: rampTexture(HEAT_RAMP) }, + uLayerLut: { value: new DataTexture(new Float32Array(1), 1, 1, RedFormat, FloatType) }, + uSpeedRange: { value: [0, 300] as [number, number] }, + uFlowRange: { value: [0, 30] as [number, number] }, + uWidthRange: { value: [0.2, 0.8] as [number, number] }, + uHeightRange: { value: [0.1, 0.4] as [number, number] }, + uFanRange: { value: [0, 100] as [number, number] }, + uTempRange: { value: [180, 260] as [number, number] }, + uHasExtras: { value: 0 }, + uStale: { value: 0 }, + uFeatureMask: { value: 0x7fff }, + uLiveColor: { value: new Color(SCENE.liveLayer) }, + uGlow: { value: 3 }, + uCamObj: { value: new Vector3() }, + uEnvSH: { value: Array.from({ length: 9 }, (_, i) => (i === 0 ? new Vector3(0.9, 0.9, 0.95) : new Vector3())) }, + uEnvDiffuse: { value: 0.9 }, + uEnvSpec: { value: 0.9 }, + uViewH: { value: 800 }, + // The partly drawn move during playback: its ends and height pick it out, the share says how far it goes. + uPartSeg: { value: new Vector4() }, + uPartZ: { value: 0 }, + uPartFrac: { value: 1 }, + } + private chunks: Chunk[] = [] + private travelColor: string = SCENE.travel + private themeToolColors: readonly string[] = DEFAULT_TOOL_COLORS + private userToolColors: readonly string[] | null = null + private extras: PreviewExtras | null = null + private readonly markers: Record = { retractions: null, seams: null, lifts: null, wipes: null, toolChanges: null, pauses: null } + private readonly markerShown: Record = { retractions: false, seams: false, lifts: false, wipes: false, toolChanges: false, pauses: false } + private markerColors: Record = markerColorsOf(SCENE) + /** Wipes, tool changes and pauses come from the G-code, which the app reads; they stay apart from the buffer's own extras. */ + private gcodeMarkers: Partial> = {} + private readonly markerRange = { value: [0, 0] as [number, number] } + private buf: PreviewBuffers | null = null + private rangesReady = false + private travels: LineSegments | null = null + private travelsOn = false + private readonly head = new ToolheadRig() + /** The purge chute and the blob a change flushes into it (Bambu printers), by the change's first segment. */ + private readonly purge = new PurgeRig() + private purges: Map | null = null + /** heimdall's gantry beam over the moving head, red where it runs through a part it strikes. */ + private readonly gantry = new GantryRig() + private changer: ToolChangerSpec | null = null + /** Preview's "Show toolhead": off hides the moving head; the rack, dock, chute and wiper stay. */ + private headOn = true + private change: { segment: number; seconds: number; fixed: number } | null = null + private changeSeq: { key: string; seq: ChangeSequence } | null = null + /** Segments where the tool differs from the one before, in order, with the tools either side. */ + private changes: { segment: number; from: number; to: number }[] = [] + lo = 0 + hi = 0 + /** Moves drawn on the top layer; a fraction draws the next move part of the way (playback). */ + moveCut: number | null = null + /** Playback's partly drawn move and the head's point on it, or null at a whole move. */ + private part: { index: number; f: number } | null = null + /** Told where the moving head is after each change, in bed millimetres (the follow-the-nozzle camera). */ + onHead: ((x: number, y: number, z: number) => void) | null = null + colorMode: ColorMode = 'feature' + + /** `ghost` draws the paths as a faint gray layer with no shadows or toolhead: the slice before a change, for comparison. */ + constructor(private readonly ghost = false) { + this.root.name = ghost ? 'toolpaths-ghost' : 'toolpaths' + const u = this.uniforms + // The live paths are lit per pixel by the model view's physical material (round bead normals, the room, the lights, + // the finish's clearcoat and sheen, tone). The ghost stays lit per vertex by Phong: it is a faint gray layer. + this.material = ghost + ? new MeshPhongMaterial({ color: 0xffffff, specular: new Color(0.04, 0.04, 0.04), shininess: 36 }) + : new MeshPhysicalMaterial({ color: 0xffffff, roughness: 0.52, metalness: 0, clearcoat: 0.16, clearcoatRoughness: 0.3, sheen: 1, sheenRoughness: 0.55, envMapIntensity: 0.95 }) + this.material.onBeforeCompile = (sh: WebGLProgramParametersWithUniforms) => { + Object.assign(sh.uniforms, u) + sh.vertexShader = + BEAD_DECL + + sh.vertexShader + .replace('#include ', '#include \n' + (ghost ? BEAD_LIGHT_DECL : BEAD_PIXEL_DECL)) + .replace('#include ', 'vec3 sxP; vec3 objectNormal; sxBead(sxP, objectNormal);\n' + BEAD_COLOR) + .replace('#include ', 'vec3 transformed = sxP;') + .replace('#include ', '#include \n' + (ghost ? BEAD_LIGHT : BEAD_PIXEL)) + sh.fragmentShader = ghost + ? 'varying vec3 vLit;\nvoid main() {\n float g = dot( vLit, vec3( 0.299, 0.587, 0.114 ) );\n gl_FragColor = vec4( vec3( g * 0.6 + 0.35 ), 0.3 );\n}\n' + : BEAD_FRAG_DECL + + sh.fragmentShader + .replace('#include ', 'diffuseColor.rgb = vSegColor;') + .replace('#include ', 'float roughnessFactor = vFinish.x;') + .replace('#include ', 'float metalnessFactor = vFinish.w * 0.28;') + .replace('#include ', BEAD_NORMAL) + .replace('#include ', '#include \n' + BEAD_FINISH) + .replace('#include ', BEAD_AFTER_LIGHTS) + .replace('#include ', BEAD_STALE + '#include ') + } + if (ghost) { + this.material.transparent = true + this.material.depthWrite = false + } + this.material.customProgramCacheKey = () => (ghost ? 'sx-bead-ghost' : 'sx-bead-pixel') + this.depthMaterial = new MeshDepthMaterial({ depthPacking: RGBADepthPacking }) + this.depthMaterial.onBeforeCompile = (sh: WebGLProgramParametersWithUniforms) => { + Object.assign(sh.uniforms, u) + sh.vertexShader = BEAD_DECL + sh.vertexShader.replace('#include ', 'vec3 sxP; vec3 sxN; sxBead(sxP, sxN);\nvec3 transformed = sxP;') + sh.vertexShader = sh.vertexShader.replace('varying vec3 vSegColor;\nvarying float vLive;\nvarying vec4 vFinish;\nvarying float vSurf;\n', '') + } + this.depthMaterial.customProgramCacheKey = () => 'sx-bead-depth' + this.root.add(this.head.root, this.purge.root, this.gantry.root) + } + + /** Draws the paths dimmed while they are stale. Returns whether that changed. */ + setStale(stale: boolean): boolean { + const v = stale ? 1 : 0 + if (this.uniforms.uStale.value === v) return false + this.uniforms.uStale.value = v + return true + } + + /** Room irradiance as nine spherical-harmonic coefficients (three.js LightProbe order). */ + setEnvironment(sh: readonly Vector3[]): void { + sh.forEach((c, i) => this.uniforms.uEnvSH.value[i]?.copy(c)) + } + + /** Camera position in bed coordinates and the drawing buffer height in pixels, for bead level of detail. */ + setView(camBed: Vector3, viewHeightPx: number): void { + this.uniforms.uCamObj.value.copy(camBed) + this.uniforms.uViewH.value = viewHeightPx + } + + get buffers(): PreviewBuffers | null { + return this.buf + } + + get segmentCount(): number { + return this.buf?.segmentCount ?? 0 + } + + set(buffers: PreviewBuffers | null): void { + this.clearChunks() + this.buf = buffers + this.extras = null + this.gcodeMarkers = {} + this.uniforms.uHasExtras.value = 0 + this.buildMarkers() + this.rangesReady = false + if (!buffers || buffers.segmentCount === 0 || buffers.layerCount === 0) return + const S = buffers.segmentCount + const N = buffers.layerCount + const words = new Uint32Array(buffers.raw, buffers.segmentsOffset, S * (SXPV_SEGMENT_BYTES / 4)) + const layer = N < 65536 ? new Uint16Array(S) : new Float32Array(S) + for (let k = 0; k < N; k++) layer.fill(k, buffers.layerStart[k] ?? 0, buffers.layerStart[k + 1] ?? S) + for (let start = 0; start < S; start += CHUNK) { + const end = Math.min(S, start + CHUNK) + const seg = new InstancedInterleavedBuffer(words.subarray(start * 8, end * 8), 8, 1) + const lb = new InstancedInterleavedBuffer(layer.subarray(start, end), 1, 1) + const geo = new InstancedBufferGeometry() + geo.index = this.base.index + geo.setAttribute('position', this.base.getAttribute('position')) + geo.setAttribute('normal', this.base.getAttribute('normal')) + const mesh = new Mesh(geo, this.material) + mesh.customDepthMaterial = this.depthMaterial + mesh.frustumCulled = false + mesh.castShadow = !this.ghost + mesh.receiveShadow = !this.ghost + if (this.ghost) mesh.renderOrder = 3 + const c: Chunk = { start, end, mesh, geo, seg, layer: lb, drawn: [-1, -1] } + this.bind(c, 0, end - start) + this.chunks.push(c) + this.root.add(mesh) + } + this.updateLayerLut() + this.changes = changePoints(buffers) + this.changeSeq = null + this.lo = 0 + this.hi = N - 1 + this.moveCut = null + this.apply() + if (this.travelsOn) this.buildTravels() + const native = extrasFromBuffers(buffers) + if (native) this.setExtras(native) + } + + private bind(c: Chunk, from: number, to: number): void { + if (c.drawn[0] === from && c.drawn[1] === to) return + // New attribute objects with a shifted offset rebind the same GPU buffer at a new start; nothing is uploaded again. + c.geo.setAttribute('aSegA', new InterleavedBufferAttribute(c.seg, 4, from * 8)) + c.geo.setAttribute('aSegB', new InterleavedBufferAttribute(c.seg, 4, from * 8 + 4)) + c.geo.setAttribute('aLayer', new InterleavedBufferAttribute(c.layer, 1, from)) + if (c.extra) c.geo.setAttribute('aExtra', new InterleavedBufferAttribute(c.extra, 2, from * 2)) + c.geo.instanceCount = to - from + c.drawn = [from, to] + } + + private updateLayerLut(): void { + const b = this.buf + if (!b) return + const N = b.layerCount + const h = Math.max(1, Math.ceil(N / LAYER_LUT_W)) + const data = new Float32Array(LAYER_LUT_W * h) + let mn = Infinity + let mx = 0 + for (let k = 0; k < N; k++) { + const t = b.layerTimeS[k] ?? 0 + if (t < mn) mn = t + if (t > mx) mx = t + } + const span = Math.max(1e-3, mx - mn) + for (let k = 0; k < N; k++) data[k] = ((b.layerTimeS[k] ?? 0) - mn) / span + const old = this.uniforms.uLayerLut.value + const t = new DataTexture(data, LAYER_LUT_W, h, RedFormat, FloatType) + t.minFilter = t.magFilter = NearestFilter + t.needsUpdate = true + this.uniforms.uLayerLut.value = t + old.dispose() + } + + /** Speed and flow ranges need a pass over every segment, so they run only when a mode needs them. */ + private ensureRanges(): void { + const b = this.buf + if (!b || this.rangesReady) return + const S = b.segmentCount + const u16 = new Uint16Array(b.raw, b.segmentsOffset, S * 16) + const f32 = new Float32Array(b.raw, b.segmentsOffset, S * 8) + let smin = Infinity, smax = 0, fmin = Infinity, fmax = 0, wmin = Infinity, wmax = 0, hmin = Infinity, hmax = 0 + for (let i = 0; i < S; i++) { + const sp = (u16[i * 16 + 13] ?? 0) * 0.1 + const fl = f32[i * 8 + 7] ?? 0 + const w = (u16[i * 16 + 10] ?? 0) * 0.001 + const h = (u16[i * 16 + 11] ?? 0) * 0.001 + if (w > 0) { + if (w < wmin) wmin = w + if (w > wmax) wmax = w + } + if (h > 0) { + if (h < hmin) hmin = h + if (h > hmax) hmax = h + } + if (sp > 0) { + if (sp < smin) smin = sp + if (sp > smax) smax = sp + } + if (fl > 0) { + if (fl < fmin) fmin = fl + if (fl > fmax) fmax = fl + } + } + this.uniforms.uSpeedRange.value = [Number.isFinite(smin) ? smin : 0, smax] + this.uniforms.uFlowRange.value = [Number.isFinite(fmin) ? fmin : 0, fmax] + this.uniforms.uWidthRange.value = [Number.isFinite(wmin) ? wmin : 0, wmax] + this.uniforms.uHeightRange.value = [Number.isFinite(hmin) ? hmin : 0, hmax] + this.rangesReady = true + } + + ranges(): PreviewRanges { + this.ensureRanges() + const u = this.uniforms + return { + speed: [...u.uSpeedRange.value], + flow: [...u.uFlowRange.value], + width: [...u.uWidthRange.value], + height: [...u.uHeightRange.value], + fan: this.extras?.fanPct ? [...u.uFanRange.value] : null, + temperature: this.extras?.nozzleC ? [...u.uTempRange.value] : null, + } + } + + /** True when per-segment fan or temperature data is loaded, so those color schemes have something to show. */ + hasMarkers(): Record { + const m = this.markers + return { retractions: !!m.retractions, seams: !!m.seams, lifts: !!m.lifts, wipes: !!m.wipes, toolChanges: !!m.toolChanges, pauses: !!m.pauses } + } + + hasExtras(): { fan: boolean; temperature: boolean } { + return { fan: !!this.extras?.fanPct, temperature: !!this.extras?.nozzleC } + } + + setColorMode(mode: ColorMode): void { + this.colorMode = mode + if (mode !== 'feature' && mode !== 'tool' && mode !== 'layerTime') this.ensureRanges() + this.uniforms.uColorMode.value = COLOR_MODE[mode] + } + + /** Bit per feature id; a cleared bit hides that feature type. */ + setFeatureMask(mask: number): void { + this.uniforms.uFeatureMask.value = mask >>> 0 + } + + /** + * Per-segment fan and nozzle temperature, and marker positions. Arrays follow segment order. + * Passing null clears them. + */ + setExtras(extras: PreviewExtras | null): void { + this.extras = extras + const b = this.buf + const u = this.uniforms + u.uHasExtras.value = extras && (extras.fanPct || extras.nozzleC) ? 1 : 0 + if (b && extras && (extras.fanPct || extras.nozzleC)) { + const S = b.segmentCount + const data = new Float32Array(S * 2) + let fmin = Infinity, fmax = -Infinity, tmin = Infinity, tmax = -Infinity + for (let i = 0; i < S; i++) { + const f = extras.fanPct?.[i] ?? 0 + const t = extras.nozzleC?.[i] ?? 0 + data[2 * i] = f + data[2 * i + 1] = t + if (extras.fanPct) { + if (f < fmin) fmin = f + if (f > fmax) fmax = f + } + if (extras.nozzleC && t > 0) { + if (t < tmin) tmin = t + if (t > tmax) tmax = t + } + } + if (fmax >= fmin) u.uFanRange.value = [fmin, Math.max(fmax, fmin + 1)] + if (tmax >= tmin) u.uTempRange.value = [tmin, Math.max(tmax, tmin + 1)] + for (const c of this.chunks) c.extra = new InstancedInterleavedBuffer(data.subarray(c.start * 2, c.end * 2), 2, 1) + } else { + for (const c of this.chunks) c.extra = undefined + } + for (const c of this.chunks) { + const [from, to] = c.drawn + c.drawn = [-1, -1] + this.bind(c, Math.max(0, from), Math.max(0, to)) + if (!c.extra) c.geo.deleteAttribute('aExtra') + } + this.buildMarkers() + } + + private buildMarkers(): void { + for (const kind of MARKER_KINDS) { + const m = this.markers[kind] + if (!m) continue + m.geometry.dispose() + ;(m.material as ShaderMaterial).dispose() + m.removeFromParent() + this.markers[kind] = null + } + const b = this.buf + if (!b) return + const ex = this.extras + const make = (kind: MarkerKind, xyz: Float32Array | undefined): Points | null => { + if (!xyz || xyz.length < 3) return null + const n = Math.floor(xyz.length / 3) + const layer = new Float32Array(n) + for (let i = 0; i < n; i++) layer[i] = layerOfZ(b.layerZ, xyz[3 * i + 2] ?? 0) + const g = new BufferGeometry() + g.setAttribute('position', new BufferAttribute(xyz.subarray(0, n * 3), 3)) + g.setAttribute('aLayer', new BufferAttribute(layer, 1)) + const m = new ShaderMaterial({ + uniforms: { uCol: { value: new Color(this.markerColors[kind]) }, uRange: this.markerRange, uSize: { value: MARKER_SHAPE[kind] === 0 ? 10 : 11 }, uShape: { value: MARKER_SHAPE[kind] } }, + vertexShader: 'attribute float aLayer; uniform vec2 uRange; uniform float uSize; void main(){ vec4 mv = modelViewMatrix * vec4(position + vec3(0.0, 0.0, 0.3), 1.0); gl_Position = projectionMatrix * mv; gl_PointSize = (aLayer < uRange.x || aLayer > uRange.y) ? 0.0 : uSize; if (gl_PointSize == 0.0) gl_Position = vec4(2.0, 2.0, 2.0, 1.0); }', + // Shapes tell the kinds apart without color: discs for retractions, seams and lifts, a diamond for wipes, a square for tool changes and pauses. + fragmentShader: 'uniform vec3 uCol; uniform float uShape; void main(){ vec2 d = gl_PointCoord - 0.5; float r = uShape > 1.5 ? abs(d.x) + abs(d.y) : uShape > 0.5 ? max(abs(d.x), abs(d.y)) : length(d); if (r > 0.5) discard; float rim = smoothstep(0.5, 0.36, r); gl_FragColor = vec4(mix(vec3(0.02), uCol, rim), 1.0); }', + depthTest: true, + depthWrite: false, + }) + const pts = new Points(g, m) + pts.frustumCulled = false + pts.renderOrder = 2 + pts.raycast = () => {} + this.root.add(pts) + return pts + } + this.markers.retractions = make('retractions', ex?.retractions) + this.markers.seams = make('seams', ex?.seams) + this.markers.lifts = make('lifts', ex?.lifts) + this.markers.wipes = make('wipes', this.gcodeMarkers.wipes ?? ex?.wipes) + this.markers.toolChanges = make('toolChanges', this.gcodeMarkers.toolChanges ?? ex?.toolChanges) + this.markers.pauses = make('pauses', this.gcodeMarkers.pauses ?? ex?.pauses) + this.applyMarkers() + } + + /** + * Wipe, tool change and pause positions (x, y, z per marker, bed frame mm) read from the G-code. They keep + * until the next preview; null removes a kind. + */ + setGcodeMarkers(data: Partial>): void { + for (const [k, v] of Object.entries(data) as ['wipes' | 'toolChanges' | 'pauses', Float32Array | null][]) { + if (v) this.gcodeMarkers[k] = v + else delete this.gcodeMarkers[k] + } + this.buildMarkers() + } + + /** Show or hide each kind of marker. They follow the layer range. */ + setMarkers(opts: Partial>): void { + for (const kind of MARKER_KINDS) { + const on = opts[kind] + if (on !== undefined) this.markerShown[kind] = on + } + this.applyMarkers() + } + + private applyMarkers(): void { + for (const kind of MARKER_KINDS) { + const m = this.markers[kind] + if (m) m.visible = this.markerShown[kind] + } + this.markerRange.value = [this.lo, this.hi] + } + + /** The finish each tool's filament prints with (tool 1 first): matte, satin, glossy or silk. A tool without one is satin. */ + setToolFinishes(finishes: readonly ToolpathFinish[]): void { + const old = this.uniforms.uFinishLut.value + this.uniforms.uFinishLut.value = finishTexture(finishes) + old.dispose() + } + + /** How dark the groove between stacked layers is, 0 (none) to 1. */ + setCrease(amount: number): void { + this.uniforms.uCrease.value = Math.max(0, Math.min(1, amount)) + } + + setToolColors(colors: readonly string[]): void { + this.userToolColors = colors.length ? colors : null + this.uploadToolColors() + } + + /** Feature colors, heat ramp, default tool colors, live layer and travel colors. Tool colors from setToolColors stay. */ + setTheme(t: ResolvedTheme): void { + const u = this.uniforms + const old = [u.uFeatureLut.value, u.uRamp.value] + u.uFeatureLut.value = lutTexture(t.featureColors) + u.uRamp.value = rampTexture(t.heatRamp) + for (const o of old) o.dispose() + u.uLiveColor.value.set(t.scene.liveLayer) + this.travelColor = t.scene.travel + if (this.travels) (this.travels.material as LineBasicMaterial).color.set(t.scene.travel) + this.themeToolColors = t.toolColors + this.uploadToolColors() + this.markerColors = markerColorsOf(t.scene) + for (const kind of MARKER_KINDS) { + const m = this.markers[kind] + if (m) (m.material as ShaderMaterial).uniforms.uCol?.value.set(this.markerColors[kind]) + } + } + + private uploadToolColors(): void { + const old = this.uniforms.uToolLut.value + this.uniforms.uToolLut.value = lutTexture(this.userToolColors ?? this.themeToolColors) + old.dispose() + this.head.setColors(this.userToolColors ?? this.themeToolColors) + this.purge.setColors(this.userToolColors ?? this.themeToolColors) + } + + setRange(lo: number, hi: number, moveCut: number | null): void { + const b = this.buf + if (!b) return + const N = b.layerCount + this.hi = Math.max(0, Math.min(N - 1, Math.round(hi))) + this.lo = Math.max(0, Math.min(this.hi, Math.round(lo))) + // Whole moves stay whole; playback hands a fraction, which draws the next move part of the way. + this.moveCut = moveCut === null ? null : Math.max(0, Math.abs(moveCut - Math.round(moveCut)) < 1e-6 ? Math.round(moveCut) : moveCut) + this.apply() + } + + /** The last move drawn: its segment index, layer and G-code line (0 when the buffer has none). Null with no preview. */ + currentMove(): { segment: number; layer: number; gcodeLine: number } | null { + const b = this.buf + if (!b) return null + const [from, to] = this.visibleRange() + if (to <= from) return null + const segment = to - 1 + return { segment, layer: layerOfSegment(b, segment), gcodeLine: gcodeLineOf(b, segment) } + } + + /** + * The drawn toolpath a ray hits first, for a click in Preview. The ray is in bed coordinates; `pxAngle` is the + * angle one screen pixel covers, so thin paths far away can still be hit. Hidden features and layers are skipped. + */ + pick(origin: Vector3, dir: Vector3, pxAngle: number): { segment: number; layer: number; feature: number; tool: number; gcodeLine: number; object: number; point: [number, number, number] } | null { + const b = this.buf + if (!b) return null + const [from, to] = this.visibleRange() + const f = new Float32Array(b.raw, b.segmentsOffset, b.segmentCount * 8) + const bytes = new Uint8Array(b.raw, b.segmentsOffset, b.segmentCount * SXPV_SEGMENT_BYTES) + const u16 = new Uint16Array(b.raw, b.segmentsOffset, b.segmentCount * 16) + const mask = this.uniforms.uFeatureMask.value + const ox = origin.x, oy = origin.y, oz = origin.z + const dx = dir.x, dy = dir.y, dz = dir.z + let best = -1 + let bestT = Infinity + for (let i = from; i < to; i++) { + const k = i * 8 + const feature = bytes[i * SXPV_SEGMENT_BYTES + SXPV_SEGMENT.feature] ?? 0 + if (!((mask >> feature) & 1)) continue + const ax = f[k] as number, ay = f[k + 1] as number, bx = f[k + 2] as number, by = f[k + 3] as number, z = f[k + 4] as number + // Closest approach of the ray (o + t d) and the segment (a + s e), e flat in z. + const ex = bx - ax, ey = by - ay + const wx = ox - ax, wy = oy - ay, wz = oz - z + const ee = ex * ex + ey * ey + const de = dx * ex + dy * ey + const dw = dx * wx + dy * wy + dz * wz + const ew = ex * wx + ey * wy + const den = ee - de * de + let sSeg = den > 1e-9 ? (ew - de * dw) / den : 0 + sSeg = sSeg < 0 ? 0 : sSeg > 1 ? 1 : sSeg + const t = de * sSeg - dw + if (t <= 0 || t >= bestT) continue + const px = ox + dx * t - (ax + ex * sSeg), py = oy + dy * t - (ay + ey * sSeg), pz = oz + dz * t - z + const r = ((u16[i * 16 + SXPV_SEGMENT.widthUm / 2] ?? 400) / 2000) + 2.5 * t * pxAngle + if (px * px + py * py + pz * pz > r * r) continue + best = i + bestT = t + } + if (best < 0) return null + return { + segment: best, + layer: layerOfSegment(b, best), + feature: bytes[best * SXPV_SEGMENT_BYTES + SXPV_SEGMENT.feature] ?? 0, + tool: bytes[best * SXPV_SEGMENT_BYTES + SXPV_SEGMENT.tool] ?? 0, + gcodeLine: gcodeLineOf(b, best), + object: objectOfSegment(b, best), + point: [ox + dx * bestT, oy + dy * bestT, oz + dz * bestT], + } + } + + /** Segment index range [from, to) currently drawn. */ + visibleRange(): [number, number] { + const b = this.buf + if (!b) return [0, 0] + const from = b.layerStart[this.lo] ?? 0 + const layerA = b.layerStart[this.hi] ?? 0 + const layerB = b.layerStart[this.hi + 1] ?? b.segmentCount + if (this.moveCut === null) return [from, layerB] + const n = Math.floor(this.moveCut + 1e-6) + const p = this.partOf(layerA + n, this.moveCut - n, layerB) + return [from, Math.min(layerB, layerA + n + (p && p.reveal > 0 ? 1 : 0))] + } + + /** One move from the buffer, as the head path reads it; null outside it. */ + private seg = (i: number): HeadSeg | null => { + const b = this.buf + if (!b || i < 0 || i >= b.segmentCount) return null + const f = new Float32Array(b.raw, b.segmentsOffset + i * SXPV_SEGMENT_BYTES, 5) + return { x0: f[0] ?? 0, y0: f[1] ?? 0, x1: f[2] ?? 0, y1: f[3] ?? 0, z: f[4] ?? 0 } + } + + /** The move `index` drawn `f` of the way (0 < f < 1) on the top layer, or null when the cut is at a whole move. */ + private partOf(index: number, f: number, layerB: number): { index: number; f: number; reveal: number } | null { + if (f <= 1e-6 || f >= 1 - 1e-6 || index >= layerB) return null + return { index, f, reveal: headAt(this.seg, index, f).reveal } + } + + private apply(): void { + const b = this.buf + if (!b) return + const [from, to] = this.visibleRange() + this.updatePart() + for (const c of this.chunks) { + const s = Math.max(from, c.start) + const e = Math.min(to, c.end) + c.mesh.visible = e > s + if (e > s) this.bind(c, s - c.start, e - c.start) + } + const scrubbing = this.moveCut !== null || this.hi < b.layerCount - 1 + this.uniforms.uCurLayer.value = scrubbing ? this.hi : -1 + this.placeNozzle(from, to) + this.applyTravels() + this.applyMarkers() + } + + /** Points the shader at playback's partly drawn move, or turns that off at a whole move. */ + private updatePart(): void { + const b = this.buf + const u = this.uniforms + this.part = null + u.uPartFrac.value = 1 + if (!b || this.moveCut === null) return + const layerA = b.layerStart[this.hi] ?? 0 + const layerB = b.layerStart[this.hi + 1] ?? b.segmentCount + const n = Math.floor(this.moveCut + 1e-6) + const p = this.partOf(layerA + n, this.moveCut - n, layerB) + if (!p) return + this.part = { index: p.index, f: p.f } + const s = this.seg(p.index)! + u.uPartSeg.value.set(s.x0, s.y0, s.x1, s.y1) + u.uPartZ.value = s.z + u.uPartFrac.value = p.reveal + } + + /** + * Draws the toolhead once, far below the bed, so its shaders, shadow program and buffers exist before the first + * layer scrub shows it. Without this the first scrubbed frame compiled them (a 200 ms frame). `false` hides it + * again; the next range change places it as usual. + */ + warmNozzle(on: boolean): void { + this.head.warm(on) + } + + /** The printer family's head for a printer with one nozzle (`headFor` in heads.ts). */ + setHeadModel(model: HeadModel): void { + this.head.setModel(model) + this.apply() + } + + /** The printer's tool changer, so the head and its rack or dock match the machine; null draws the printer's own single head. */ + setToolChanger(spec: ToolChangerSpec | null): void { + this.changer = spec + this.changeSeq = null + this.head.setSpec(spec) + this.purge.setSpec(spec) + this.apply() + } + + /** The printer's gantry, for the beam drawn over the moving head; null draws none. */ + setGantry(spec: GantrySpec | null): void { + this.gantry.setSpec(spec) + this.apply() + } + + /** heimdall's gantry strikes: the beam shows on their layers even with the head hidden, red through the part. */ + setGantryHits(hits: readonly GantryHit[] | null): void { + this.gantry.setHits(hits) + this.apply() + } + + setGantryColor(hit: string): void { + this.gantry.setColor(hit) + } + + /** Shows or hides the moving head and its carriage. The machine's fixed parts stay and still follow the print. */ + setShowToolhead(on: boolean): void { + if (on === this.headOn) return + this.headOn = on + this.apply() + } + + /** Each change's purge, read from the G-code; null when there is none to show. */ + setPurges(plans: readonly PurgePlan[] | null): void { + this.purges = plans?.length ? new Map(plans.map((p) => [p.segment, p])) : null + this.apply() + } + + /** + * Plays the tool change before `segment` at `seconds` into it (`fixed` is the firmware's own seconds for it, + * from the playback timeline); null returns the head to the current move. + */ + setToolChange(c: { segment: number; seconds: number; fixed: number } | null): void { + this.change = c + this.apply() + } + + /** Segments where the tool differs from the one before (the first move of each new tool), in print order. */ + changePoints(): readonly { segment: number; from: number; to: number }[] { + return this.changes + } + + /** The change sequence that ends at `segment`, built once per change and reused while it plays. */ + private sequenceFor(segment: number, fixed: number): ChangeSequence | null { + const b = this.buf + const spec = this.changer + if (!b || !spec) return null + const key = `${segment}:${fixed}` + if (this.changeSeq && this.changeSeq.key === key) return this.changeSeq.seq + const idx = this.changes.findIndex((c) => c.segment === segment) + if (idx < 0) return null + const c = this.changes[idx]! + const seq = changeSequence(spec, c.from, c.to, segmentEnd(b, segment - 1), segmentStart(b, segment), fixed, this.changes.slice(0, idx).map((h) => [h.from, h.to]), printedTop(b, segment)) + this.changeSeq = { key, seq } + return seq + } + + private placeNozzle(from: number, to: number): void { + const b = this.buf + // The rack, dock, chute and wiper show whenever a preview is up; the moving head only while scrubbing. + const fixtures = !this.ghost && !!b && b.segmentCount > 0 + const moving = fixtures && (this.moveCut !== null || this.hi < b.layerCount - 1) && to > from + this.head.visible = fixtures + this.head.headVisible = moving && this.headOn + this.purge.visible = fixtures + if (!b || !fixtures) { + this.gantry.place(false, 0, 0, 0) + return + } + const beam = moving && (this.headOn || this.gantry.striking(this.hi)) + // With nothing drawn yet the machine stands as the print starts. + to = Math.max(1, Math.min(to, b.segmentCount)) + const bytes = new Uint8Array(b.raw, b.segmentsOffset, b.segmentCount * SXPV_SEGMENT_BYTES) + const change = this.change && this.change.segment === to ? this.change : null + const seq = change ? this.sequenceFor(change.segment, change.fixed) : null + if (seq && change) { + // The change precedes segment `to`: the head is somewhere on its way; the paths drawn stop before it. + const pose = poseAt(seq, change.seconds) + const tool = bytes[to * SXPV_SEGMENT_BYTES + SXPV_SEGMENT.tool] ?? 0 + this.head.place(pose.x, pose.y, pose.z, tool, pose, pose.slots) + this.placePurge(pose.x, pose.y, pose.z + 0.05, seq, change) + this.gantry.place(beam, pose.y, pose.z, this.hi) + return + } + const cur = this.part ? this.part.index : to - 1 + const tool = bytes[cur * SXPV_SEGMENT_BYTES + SXPV_SEGMENT.tool] ?? 0 + // Racks keep what the changes so far left in them. + if (this.changer && this.changer.kind !== 'dual-nozzle' && this.changer.kind !== 'filament-swap') { + const k = this.changes.filter((c) => c.segment <= to - 1).length + const last = k > 0 ? this.changes[k - 1]! : null + // The rack's contents after a change do not depend on the change's seconds, so 0 serves here. + const seq = last ? this.sequenceFor(last.segment, 0) : null + this.head.rest(seq ? seq.slotsAfter : null, seq ? seq.rowAfter : 0) + } + // Along the move at the head's own pace (playback), else at the last drawn move's end, corners eased. + const at = this.part ? headAt(this.seg, this.part.index, this.part.f) : headAt(this.seg, to - 1, 1) + this.head.place(at.x, at.y, at.z, tool, null, null) + if (this.headOn && this.head.headVisible) this.onHead?.(at.x, at.y, at.z) + this.placePurge(at.x, at.y, at.z + 0.05, null, null) + this.gantry.place(beam, at.y, at.z, this.hi) + } + + /** The chute at the head's height and, inside a change with a purge, the blob; the head's shadow only over the bed. */ + private placePurge(x: number, y: number, z: number, seq: ChangeSequence | null, change: { segment: number; seconds: number } | null): void { + const plan = change ? this.purges?.get(change.segment) : undefined + this.purge.place(z, seq && change && plan ? { seq, plan, seconds: change.seconds } : null) + const bed = this.changer?.bed + const shadow = this.head.root.getObjectByName('shadow') + if (shadow) shadow.visible = !bed || (x >= -5 && y >= -5 && x <= bed.widthMm + 5 && y <= bed.depthMm + 5) + } + + setTravels(on: boolean): void { + this.travelsOn = on + if (on && !this.travels) this.buildTravels() + this.applyTravels() + } + + private buildTravels(): void { + const b = this.buf + if (!b || b.travelsOffset < 0 || !b.travelStart || b.travelCount === 0) return + const T = b.travelCount + const src = new Float32Array(b.raw, b.travelsOffset, T * (SXPV_TRAVEL_BYTES / 4)) + const pos = new Float32Array(T * 6) + for (let k = 0; k < b.layerCount; k++) { + const z = (b.layerZ[k] ?? 0) + 0.1 + const e = b.travelStart[k + 1] ?? T + for (let i = b.travelStart[k] ?? 0; i < e; i++) { + pos[6 * i] = src[4 * i] ?? 0 + pos[6 * i + 1] = src[4 * i + 1] ?? 0 + pos[6 * i + 2] = z + pos[6 * i + 3] = src[4 * i + 2] ?? 0 + pos[6 * i + 4] = src[4 * i + 3] ?? 0 + pos[6 * i + 5] = z + } + } + const g = new BufferGeometry() + g.setAttribute('position', new BufferAttribute(pos, 3)) + const m = new LineBasicMaterial({ color: new Color(this.travelColor), transparent: true, opacity: 0.45, depthWrite: false }) + this.travels = new LineSegments(g, m) + this.travels.frustumCulled = false + this.root.add(this.travels) + } + + private applyTravels(): void { + const t = this.travels + const b = this.buf + if (!t) return + t.visible = this.travelsOn && !!b + if (!b || !b.travelStart) return + const from = b.travelStart[this.lo] ?? 0 + const to = b.travelStart[this.hi + 1] ?? b.travelCount + t.geometry.setDrawRange(from * 2, Math.max(0, to - from) * 2) + } + + /** Bed-frame xy bounds from a strided sample of segment starts, and the top z. */ + bounds(): { min: [number, number, number]; max: [number, number, number] } | null { + const b = this.buf + if (!b || b.segmentCount === 0) return null + const S = b.segmentCount + const f = new Float32Array(b.raw, b.segmentsOffset, S * 8) + const step = Math.max(1, Math.floor(S / 20000)) + let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity + for (let i = 0; i < S; i += step) { + const x = f[i * 8] ?? 0 + const y = f[i * 8 + 1] ?? 0 + if (x < x0) x0 = x + if (x > x1) x1 = x + if (y < y0) y0 = y + if (y > y1) y1 = y + } + return { min: [x0, y0, 0], max: [x1, y1, b.layerZ[b.layerCount - 1] ?? 0] } + } + + private clearChunks(): void { + for (const c of this.chunks) { + c.geo.dispose() + c.mesh.removeFromParent() + } + this.chunks = [] + if (this.travels) { + this.travels.geometry.dispose() + ;(this.travels.material as LineBasicMaterial).dispose() + this.travels.removeFromParent() + this.travels = null + } + this.head.visible = false + this.purge.visible = false + this.gantry.place(false, 0, 0, 0) + this.changes = [] + this.changeSeq = null + } + + dispose(): void { + this.clearChunks() + this.extras = null + this.buildMarkers() + this.base.dispose() + this.material.dispose() + this.depthMaterial.dispose() + this.uniforms.uFeatureLut.value.dispose() + this.uniforms.uToolLut.value.dispose() + this.uniforms.uRamp.value.dispose() + this.uniforms.uLayerLut.value.dispose() + this.head.dispose() + this.purge.dispose() + this.gantry.dispose() + } +} + +/** Where segment `i` starts and ends (x, y, z), mm. */ +function segmentStart(b: PreviewBuffers, i: number): V3 { + const f = new Float32Array(b.raw, b.segmentsOffset + Math.max(0, Math.min(b.segmentCount - 1, i)) * SXPV_SEGMENT_BYTES, 5) + return [f[0] ?? 0, f[1] ?? 0, f[4] ?? 0] +} +function segmentEnd(b: PreviewBuffers, i: number): V3 { + const f = new Float32Array(b.raw, b.segmentsOffset + Math.max(0, Math.min(b.segmentCount - 1, i)) * SXPV_SEGMENT_BYTES, 5) + return [f[2] ?? 0, f[3] ?? 0, f[4] ?? 0] +} + +/** Segments where the tool byte differs from the segment before, in order. */ +export function changePoints(b: PreviewBuffers): { segment: number; from: number; to: number }[] { + const out: { segment: number; from: number; to: number }[] = [] + if (b.toolCount < 2) return out + const bytes = new Uint8Array(b.raw, b.segmentsOffset, b.segmentCount * SXPV_SEGMENT_BYTES) + let prev = bytes[SXPV_SEGMENT.tool] ?? 0 + for (let i = 1; i < b.segmentCount; i++) { + const t = bytes[i * SXPV_SEGMENT_BYTES + SXPV_SEGMENT.tool] ?? 0 + if (t !== prev) { + out.push({ segment: i, from: prev, to: t }) + prev = t + } + } + return out +} diff --git a/desktop/src/vendor/slicerx/viewport/types.ts b/desktop/src/vendor/slicerx/viewport/types.ts new file mode 100644 index 00000000..177deb96 --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/types.ts @@ -0,0 +1,604 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// Public types of @slicerx/viewport. Coordinates in every public call are the +// slicer frame used by the Plate contract: millimeters, Z up, origin at the +// bed's front left corner. The renderer converts to three.js Y-up internally. +// --------------------------------------------------------------------------------------------------------------- +// MODIFIED BY SNAPMAKER STUDIO (DVOpenLabs/snapmaker-studio): the only change in this file is the import path of the +// contracts module ('@slicerx/contracts' -> '../contracts/index'). Upstream: slicerx-oss/slicerx @ +// edb521fe41306dd60d01bda8a0f6bf8aa54fcb29 (Apache-2.0). See ../UPDATING.md. +// --------------------------------------------------------------------------------------------------------------- +import type { ToolChangerSpec } from './toolchanger' +import type { PurgePlan } from './purge' +import type { HeadModel } from './heads' +import type { StrikeMark } from './strikes' +import type { GantryHit, GantrySpec } from './gantry' +import type { Guides } from './guides' +import type { DimensionMark, SketchCursor, SketchScene } from './cadtools' +import type { Bed, PreviewBuffers } from '../contracts/index' +import type { ControlsMap, ControlsPresetId } from './controls' +import type { ViewportTheme } from './palette' + +export type Backend = 'auto' | 'webgl2' | 'webgpu' +export type Quality = 'high' | 'balanced' | 'low' +export type ViewportMode = 'prepare' | 'preview' +/** Prepare look. */ +export type RenderMode = 'studio' | 'clay' | 'xray' | 'overhang' | 'filament' +/** Preview coloring. `tool` is the filament color of each segment's tool. */ +export type ColorMode = 'feature' | 'tool' | 'speed' | 'flow' | 'layerTime' | 'width' | 'height' | 'fan' | 'temperature' +/** `fit` frames the scene or selection from the current direction; `bed` frames the whole bed from it. */ +export type ViewPreset = 'iso' | 'top' | 'bottom' | 'front' | 'back' | 'left' | 'right' | 'fit' | 'bed' +export type Projection = 'perspective' | 'orthographic' +/** How Prepare draws models: `shaded`, `edges` (shaded with feature edges, the default) or `wireframe`. X-ray is a RenderMode. */ +export type DisplayStyle = 'shaded' | 'edges' | 'wireframe' +/** `face` is lay on face: hovering highlights the flat face under the cursor and a click emits `facepick`. */ +/** + * `face` is lay on face. `paint` paints color, seams and supports. `scale` follows OrcaSlicer's scale gizmo: x and y + * handles at the middle of the bottom edges, a z handle on top, uniform handles at the bottom corners. A drag scales about + * the bottom center of the model's box, so it stays on the bed. Hold Ctrl when the drag starts to keep the opposite + * handle fixed (a corner then scales x and y only). Shift snaps the factor to 5 percent steps. + */ +export type PlateTool = 'select' | 'move' | 'rotate' | 'face' | 'paint' | 'scale' | 'brim' | 'probe' +/** With the `probe` tool a click only reports what is under the cursor (`pick`): nothing is selected or moved. Measure and the shape tools use it. */ +export type FilamentFinish = 'basic' | 'matte' | 'silk' | 'petg' | 'translucent' + +/** How printed toolpaths shine: matte, satin (everyday PLA), glossy (PETG and the like) or silk, which streaks along each bead. */ +export type ToolpathFinish = 'matte' | 'satin' | 'glossy' | 'silk' + +/** The bed under the print: the outline and grid only, or a build plate surface under them. */ +export type PlateStyle = 'grid' | 'textured-pei' | 'smooth-pei' | 'cool' | 'engineering' + +/** Preview data beyond SXPV v1. Per-segment arrays follow the segment order of the buffer. */ +export interface PreviewExtras { + /** Fan speed, 0 to 100, per segment. */ + fanPct?: ArrayLike + /** Nozzle temperature in degrees C per segment. */ + nozzleC?: ArrayLike + /** x, y, z of each retraction, bed frame mm. */ + retractions?: Float32Array + /** x, y, z of each layer seam, bed frame mm. */ + seams?: Float32Array + /** x, y, z where the nozzle lifts (z hop), bed frame mm. */ + lifts?: Float32Array + /** x, y, z where a wipe starts, bed frame mm. */ + wipes?: Float32Array + /** x, y, z of each tool or filament change, bed frame mm. */ + toolChanges?: Float32Array + /** x, y, z of each pause, bed frame mm. */ + pauses?: Float32Array +} + +/** Kinds of point markers in Preview. */ +export type MarkerKind = 'retractions' | 'seams' | 'lifts' | 'wipes' | 'toolChanges' | 'pauses' + +/** Value ranges behind the color schemes, in the units shown in a legend. `fan` and `temperature` are null without extras. */ +export interface PreviewRanges { + /** mm/s */ + speed: [number, number] + /** mm3/s */ + flow: [number, number] + /** mm */ + width: [number, number] + /** mm */ + height: [number, number] + /** percent */ + fan: [number, number] | null + /** degrees C */ + temperature: [number, number] | null +} + +export interface LegendFeature { + id: number + label: string + /** Color as drawn, theme applied. */ + color: string + /** Extrusion time in seconds, from path length over speed. */ + timeS: number + lengthMm: number + visible: boolean +} + +export interface ViewportOptions { + /** `auto` picks WebGL2 today; see README, "Backend". */ + backend?: Backend + /** `high`: MSAA 4x, SSAO, FXAA, 2048 shadows. `balanced`: SSAO at lower cost. `low`: no SSAO, 1x pixel ratio. */ + quality?: Quality + /** Upper bound for the device pixel ratio. Default 2. */ + maxPixelRatio?: number + /** Accessible label for the canvas. */ + label?: string + /** Lower quality on its own when frames stay slow. Default true; benchmarks turn it off. */ + adaptive?: boolean + /** Colors of the 3D scene. See ViewportTheme. Same as calling setTheme after creation. */ + theme?: ViewportTheme + /** Camera and mouse controls at start. Default 'slicerx'. */ + controls?: ControlsPresetId | ControlsMap + /** + * The GL renderer the desktop shell read itself (Linux, where WebKit gives pages a made-up GPU name). It wins over + * the name WebGL reports when deciding the quality tier and the software rendering warning. + */ + gpuRenderer?: string | null +} + +export interface ViewportPart { + name: string + /** Object-local positions, mm, Z up. */ + positions: Float32Array + indices: Uint32Array | Uint16Array + /** Filament color as #rrggbb. */ + color: string + finish?: FilamentFinish +} + +export interface ViewportObject { + id: string + name: string + parts: ViewportPart[] + /** 4x4 column-major, mm, Z up, origin at the bed's front left corner (PlateObject.transform). */ + transform: number[] +} + +import type { NozzleZone } from './stage' +export type { NozzleZone } + +export interface ViewportPlate { + bed: Bed + objects: ViewportObject[] + /** Name of the bed surface, for example "Textured PEI". Not drawn: the floor is an outline. */ + surfaceLabel?: string + /** Areas only one nozzle reaches (dual nozzle printers), in bed coordinates. */ + zones?: NozzleZone[] + /** Parts of the bed nothing may print on (the printer's `bed_exclude_area`), polygons in bed coordinates, mm. Omitted keeps the current ones. */ + excluded?: (readonly [number, number])[][] +} + +export interface PartStyle { + color?: string + finish?: FilamentFinish +} + +export interface PickEvent { + objectId: string | null + partIndex: number | null + /** Hit point in bed coordinates (mm, Z up), or null for a miss. */ + point: [number, number, number] | null + /** The triangle hit, as an index into the part's index buffer, or null for a miss. */ + triangle: number | null + /** Where the click meets the bed plane (mm), hit or miss; null when the ray runs away from the bed. */ + bed: [number, number] | null + /** Shift was down: tools that pick several things add to the picks. */ + shift?: boolean +} + +/** Probe tool with hover on: the model point under the cursor, at most once a frame. */ +export interface ProbeHover { + objectId: string + partIndex: number + triangle: number + /** Bed coordinates, mm. */ + point: [number, number, number] +} + +/** What an edge op would remove (`cut`) and add (`join`), bed coordinates; either may be empty. */ +export interface EdgePreviewSpec { + cut: { positions: ArrayLike; indices: ArrayLike } | null + join: { positions: ArrayLike; indices: ArrayLike } | null +} + +/** What a paint stroke writes: filament color, seam position, support or fuzzy skin. */ +export type PaintLayer = 'color' | 'seam' | 'support' | 'fuzzy' + +export interface PaintSettings { + layer: PaintLayer + /** + * `brush` paints under the cursor, `triangle` paints the single piece under it, `fill` floods connected pieces of the + * state under the cursor (limited by `fillAngleDeg`, negative for no limit), `smart` floods whole triangles by surface + * angle (`angleDeg`), `height` paints a band of `heightMm` at the height of the cursor on every part of the model, + * `gap` merges small patches into a neighbor (`performGapFill`, Orca and Bambu Studio), `replace` turns every piece of + * the color under the cursor into the new one (PrusaSlicer). Which tools exist depends on the look. + */ + tool: 'brush' | 'triangle' | 'fill' | 'smart' | 'height' | 'gap' | 'replace' + /** Sphere paints what the ball touches; circle paints through a disc along the view. Either spreads only over connected surface that faces the viewer, as OrcaSlicer's brush does. */ + shape: 'sphere' | 'circle' + /** Brush radius in mm. OrcaSlicer allows 0.4 to 8 in steps of 0.2 (Ctrl and the wheel). */ + radiusMm: number + /** + * Color layer: 1-based filament slot. Seam and support layers: 1 enforcer, 2 blocker. On the seam and support layers + * the left button always writes an enforcer and the right button a blocker, as in OrcaSlicer. + */ + state: number + /** Erase instead of painting. Holding Shift while painting erases too. */ + erase: boolean + /** Split triangles so the brush edge follows the cursor. Off paints whole pieces by their center. */ + splitTriangles: boolean + /** Longest edge left after splitting, mm. 0 is OrcaSlicer's rule, `min(radius / 5, 0.05)`. */ + detailMm: number + /** Smart fill: largest bend between neighboring triangles, 0 to 90 degrees (default 30); negative removes the limit. */ + angleDeg: number + /** Bucket fill: the same limit for the fill tool (Orca and Bambu Studio share one value with smart fill; PrusaSlicer defaults to 90). */ + fillAngleDeg: number + /** Height tool: thickness of the band in mm. The range, step and whether the band starts at or is centered on the cursor depend on the look. */ + heightMm: number + /** `paintHeightRange` from code: an explicit bed height range in mm. */ + heightRangeMm: [number, number] + /** Gap fill: patches with less area than this (mm2) are merged. 0 to 5 in Orca. */ + gapAreaMm2: number + /** The second brush color, painted by the right button when the look says so (PrusaSlicer). */ + secondState: number + /** Paint only on overhangs steeper than this angle in degrees (Orca's paint on overhangs only). 0 is off. */ + overhangOnlyDeg: number + /** Clipping plane, 0 off to 1 (moved with the wheel). What lies in front of it is hidden and not painted. */ + clipRatio: number +} + +/** One triangle's paint before and after a stroke, as `paint_color` style text (null: unpainted). Undo applies `before`. */ +export interface PaintEdit { + triangle: number + before: string | null + after: string | null +} + +export interface PaintStroke { + objectId: string + partIndex: number + layer: PaintLayer + edits: PaintEdit[] +} + +/** A flat face of a model, in the bed frame (mm, Z up). */ +export interface FacePick { + objectId: string + partIndex: number + /** Outward unit normal after the object's transform. */ + normal: [number, number, number] + /** Center of the object's bounds in bed coordinates, to rotate about. */ + centerBed: [number, number, number] + areaMm2: number + /** Hit point on the face. */ + point: [number, number, number] +} + +export interface TransformEvent { + id: string + transform: number[] + /** True on pointer up or when an arrange animation ends. Commit to app state then. */ + final: boolean +} + +/** The cut tool's plane in bed coordinates (mm). `keep` decides which side the preview draws faint. */ +export interface CutPlaneSpec { + objectId: string + point: [number, number, number] + normal: [number, number, number] + keep?: 'both' | 'above' | 'below' + /** Connector placement: a click on the plane emits `cutconnector` with the point instead of moving the plane. */ + placeConnectors?: boolean +} + +/** Push and pull: the picked face (bed coordinates, mm) and how far it moves along its outward normal. */ +export interface PushSpec { + face: { objectId: string; point: [number, number, number]; normal: [number, number, number] } | null + distanceMm: number + /** The swept prism of a 1 mm push (bed coordinates); the view stretches it to the distance while dragging. */ + prism?: { positions: ArrayLike; indices: ArrayLike } | null +} + +/** A drag on a flat face while the push tool is on. `start` names the face pressed; `end` carries the final distance. */ +export interface PushEvent { + phase: 'start' | 'move' | 'end' | 'cancel' + objectId: string + partIndex: number + triangle: number + /** Where the face was pressed and its outward normal, bed coordinates. */ + point: [number, number, number] + normal: [number, number, number] + distanceMm: number + /** The snap key is down: the distance is in whole millimeters. */ + snapped: boolean +} + +/** The cursor on the sketch plane, in plane coordinates (mm). `mmPerPx` turns pixel tolerances into millimeters there. */ +export interface SketchEvent { + /** `hover` (at most one per frame), `click`, `context` (a right click), `drag` and `release` of a handle. */ + kind: 'hover' | 'click' | 'context' | 'drag' | 'release' + at: [number, number] + /** The handle being dragged, an index into the scene's handles. */ + handle?: number + mmPerPx: number + /** Client pixels, for a field placed at the cursor. */ + screen: [number, number] + shift: boolean + alt: boolean +} + +export interface CameraState { + /** Orbit center in bed coordinates, mm. */ + target: [number, number, number] + /** 0 looks from the front of the bed, 90 from the right side. */ + azimuthDeg: number + /** Angle above the bed plane. */ + elevationDeg: number + distanceMm: number +} + +export interface PathPick { + segment: number + /** 0-based layer index. */ + layer: number + /** SXPV feature id (outer wall, sparse infill and so on). */ + feature: number + /** 0-based tool. */ + tool: number + /** 1-based G-code line, 0 when the buffer has none. */ + gcodeLine: number + /** Index of the path's object in the slice request's `plate.objects`, -1 for none (skirt, shared brim, prime tower) or unknown. */ + object: number + /** Where the click met the path, bed coordinates in mm. */ + point: [number, number, number] + /** The click in CSS pixels from the canvas corner. */ + screen: [number, number] +} + +export interface ViewportEvents { + pick: PickEvent + select: { ids: string[] } + /** While a scale handle is dragged: the factors applied to the model's own axes since the drag began (`snapped`: Shift is down). */ + scale: { id: string; factors: [number, number, number]; uniform: boolean; snapped: boolean } + /** The wheel changed a paint setting (radius, height band or fill angle). */ + paintsettings: PaintSettings + /** A paint stroke, fill or height range ended. Edits carry before and after texts for undo. */ + paintstroke: PaintStroke + /** Face tool: the face under the cursor, or null. */ + facehover: FacePick | null + /** Probe tool with hover on: the model point under the cursor, or null off the model. */ + probehover: ProbeHover | null + /** Face tool: a click on a face. Turn it with `layOnFaceTransform(transform, normal, centerBed)`. */ + facepick: FacePick + /** Brim tool: a left click on a model (not on an ear). `point` is the hit in bed coordinates, mm. */ + brimadd: { objectId: string; point: [number, number, number] } + /** Brim tool: a right click on an ear. */ + brimremove: { objectId: string; index: number } + /** Brim tool: ears picked by a click (`set`, or `add` and `remove` with Shift and Alt), by a rectangle, or none (`set` with no indices) by a click on the model while some are selected. `indices` follow the array passed to `setBrimEars`. */ + brimselect: { objectId: string; indices: number[]; mode: 'set' | 'add' | 'remove' } + /** Brim tool: an ear dragged. `point` is the hit on the model under the cursor (bed frame, mm). One event per move with `final: false`, then one with `final: true` on release. */ + brimmove: { objectId: string; index: number; point: [number, number, number]; final: boolean } + /** Brim tool: Ctrl and the wheel (the wheel does not zoom). `delta` is 1 or -1 per notch. */ + brimwheel: { delta: 1 | -1 } + /** Preview: a click on a toolpath (the segment, its layer and feature, the G-code line and where the click landed), or null for a click on nothing. */ + pathpick: PathPick | null + transform: TransformEvent + /** While a rotate ring is dragged: the turn since the drag began, about the bed's axis or the model's own (`space`). `snapped`: the snap key is down. One event with `final: true` on release. */ + rotate: { id: string; axis: 'x' | 'y' | 'z'; space: 'world' | 'local'; angleDeg: number; snapped: boolean; final: boolean } + /** The cut plane moved or tilted in the view. One event per move with `final: false`, then one with `final: true` on release. */ + cutplane: { objectId: string; point: [number, number, number]; normal: [number, number, number]; final: boolean } + /** Connector placement on the cut plane: where a click met the plane (bed coordinates, mm). */ + cutconnector: { objectId: string; point: [number, number, number] } + /** Push and pull: a face dragged along its normal. Moves come at pointer rate; `end` comes once on release. */ + push: PushEvent + /** Sketch mode: the cursor, clicks and handle drags on the sketch plane. */ + sketch: SketchEvent + /** The camera moved (throttled to one per frame). For overlays such as dimension labels. */ + camera: { preset: ViewPreset | null } + /** WebGL context lost or the renderer failed to start. */ + error: { message: string } + /** The viewport lowered its own quality to keep frames smooth. Show `message` as a toast. */ + degrade: { message: string } +} + +export interface ViewportStats { + backend: 'webgl2' | 'webgpu' + gpu: string + quality: Quality + pixelRatio: number + width: number + height: number + frames: number + /** Intervals between rendered frames while rendering continuously, ms (last 600). */ + frameMs: number[] + /** CPU time spent rendering each frame, ms (last 600); includes the GPU wait while `setGpuTiming(true)`. */ + renderMs: number[] + /** Time from the start of each frame until the GPU finished it, ms (last 600). Filled only while `setGpuTiming(true)`. */ + costMs: number[] + /** Percentiles of costMs when GPU timing ran, otherwise of frameMs (which vsync caps). */ + p50: number + p95: number + /** ms from setPreview() to the first frame drawn with it, or null. */ + firstFrameMs: number | null + /** Milliseconds from creating the viewport to its first drawn frame (plate and bed). */ + firstDrawMs: number | null + drawCalls: number + triangles: number + segments: number + aoOn: boolean + /** Moving frames are drawn at this fraction of the still resolution. */ + motionScale: number +} + +export interface Viewport { + readonly canvas: HTMLCanvasElement + setMode(mode: ViewportMode): void + + // Prepare + setPlate(plate: ViewportPlate, opts?: { keepCamera?: boolean }): void + /** Move objects without rebuilding geometry. */ + setTransforms(transforms: Record): void + setPartStyle(objectId: string, partIndex: number, style: PartStyle): void + setRenderMode(mode: RenderMode): void + setDisplayStyle(style: DisplayStyle): void + /** Overhang heat map threshold in degrees from vertical. Amber starts 15 degrees below it. */ + setOverhangAngle(deg: number): void + /** + * sleipnir: draw the real layer heights on the models. `tops` are the top of every layer in mm, + * ascending, first entry the first layer's top (core's options.layerTopsMm). The layer grooves follow + * them, and with `band` (default true) a heat band colors thin layers blue and thick layers orange. + * Null clears. Throws on tops that do not ascend. The shaders are shared by every viewport on the page. + */ + setLayerHeights(tops: ArrayLike | null, opts?: { band?: boolean }): void + setLayerHeightBand(on: boolean): void + /** Layer-groove shading in Prepare; `layerHeightMm` defaults to 0.2. */ + setPrintLook(on: boolean, layerHeightMm?: number): void + setSelection(ids: string[]): void + setTool(tool: PlateTool): void + /** Brim ears per object, in bed coordinates (mm). `error` draws the ear in the alert color. */ + setBrimEars(ears: Record): void + /** Radius of the faint disc that follows the cursor while the brim tool is on; null hides it. */ + setBrimHoverRadius(r: number | null): void + /** + * Fit check: a line between the closest points of two parts that sit too close. `on`: the objects it was measured + * on and their transforms then; it follows one object as it moves and hides once either of two has moved. Empty clears them. + */ + setGapLines(lines: readonly { from: [number, number, number]; to: [number, number, number]; kind: 'horizontal' | 'vertical' | 'fused' | 'apart'; on?: readonly { id: string; transform: readonly number[] }[] }[]): void + /** Modeling guides in bed coordinates (mm): lines, closed outlines and end point dots. An empty object clears them. */ + setGuides(guides: Guides): void + /** Probe tool: highlight the flat face under the cursor, as lay on face does. */ + setProbeFaces(on: boolean): void + /** Probe tool: report the model point under the cursor as `probehover`, at most once a frame. Off by default. */ + setProbeHover(on: boolean): void + /** Fillet and chamfer: the pieces the op would remove (red) and add (green), drawn through the model. Null clears them. */ + setEdgePreview(preview: EdgePreviewSpec | null): void + /** Screen positions (CSS pixels from the canvas corner) of the scale handles of the selected model, or null when the scale tool is off. */ + scaleHandles(): Partial> | null + /** Rotate tool: whether the rings turn the model about the bed's axes (`world`, the default) or its own (`local`). */ + setRotateSpace(space: 'world' | 'local'): void + /** Screen positions (CSS pixels from the canvas corner) of a grab point on each rotate ring, or null when the rotate tool is off. */ + rotateHandles(): Partial> | null + /** Cut tool: shows the plane with its grabber and tilt rings on the model and clips the model there. Null ends it. */ + setCutPlane(cut: CutPlaneSpec | null): void + /** Screen positions of the cut grabber and a point on each tilt ring, or null without a cut plane. */ + cutHandles(): { grabber: [number, number]; u: [number, number]; v: [number, number] } | null + /** + * Push and pull (with the probe tool): a press on a flat face and a drag move it along its normal, a + * click picks it as usual. The view draws `prism` stretched to the distance. Null ends the tool. + */ + setPush(push: PushSpec | null): void + /** Sketch mode (with the probe tool): draws the sketch on its plane and reports the cursor there. Null ends it. */ + setSketch(scene: SketchScene | null): void + /** The line being drawn and the snapped cursor. Cheap: call it on every hover event. */ + setSketchCursor(cursor: SketchCursor | null): void + /** Turns the camera to look straight at a plane through `point` along `normal` (bed coordinates), framing `radiusMm`. */ + lookAtPlane(point: [number, number, number], normal: [number, number, number], radiusMm: number, opts?: { animate?: boolean }): void + /** Kept dimensions: a line and a value label each, drawn through the model. An empty list clears them. */ + setDimensions(marks: readonly DimensionMark[]): void + /** Paint tool options. Partial updates keep the rest. */ + setPaintSettings(settings: Partial): void + getPaintSettings(): PaintSettings + /** Filament slot colors for the color layer, slot 1 first (#rrggbb). */ + setPaintColors(colors: readonly string[]): void + /** + * Paint of one part as text per painted triangle (triangle index into the part's index buffer), the + * same encoding as `paint_color`, `paint_seam` and `paint_supports` in 3MF. + */ + getPaintData(objectId: string, partIndex: number, layer: PaintLayer): Record + /** Replaces the paint of a part. Null clears it. Malformed texts are skipped and their triangle indexes returned. */ + setPaintData(objectId: string, partIndex: number, layer: PaintLayer, texts: Record | null): number[] + /** Applies edits from a stroke (`after`) or an undo (`before`): null clears the triangle. */ + applyPaintEdits(objectId: string, partIndex: number, layer: PaintLayer, edits: readonly { triangle: number; text: string | null }[]): void + /** Paints a bed height range in mm on every part of a model, `heightRangeMm` by default (the `height` tool paints a band at the cursor instead). */ + paintHeightRange(objectId: string, range?: [number, number]): void + /** The gap fill tool's Perform button (Orca and Bambu Studio): patches smaller than `gapAreaMm2` merge into a neighbor. */ + performGapFill(objectId: string): void + /** The flat face under a client-space point, or null. Works with any tool. */ + pickFace(clientX: number, clientY: number): FacePick | null + /** Packs objects on the bed and emits `transform` events. Returns the new transforms. */ + arrange(opts?: { animate?: boolean; gapMm?: number }): Record + view(preset: ViewPreset, opts?: { animate?: boolean }): void + /** Frame the selection, or every model when nothing is selected. Animated by default. */ + zoomToSelection(opts?: { animate?: boolean }): void + zoomToBed(opts?: { animate?: boolean }): void + /** Moves the camera toward its target by `factor` (below 1 moves away), keeping the angle, within the zoom limits. */ + zoomBy(factor: number, opts?: { animate?: boolean }): void + /** Eases the camera to center a bed point (mm) at the current angle and zoom; jumps under reduced motion. */ + focusBedPoint(x: number, y: number, z: number, opts?: { animate?: boolean }): void + setProjection(projection: Projection): void + getProjection(): Projection + /** Switches and returns the new projection. */ + toggleProjection(): Projection + /** Switch camera and mouse controls at runtime: a preset id or a full map. */ + /** Change scene colors at runtime. Omit to return to the defaults. Throws on an invalid color. */ + setTheme(theme?: ViewportTheme): void + setControls(controls: ControlsPresetId | ControlsMap): void + getControls(): ControlsMap + getCamera(): CameraState + setCamera(state: Partial, opts?: { animate?: boolean }): void + + // Preview + setPreview(buffers: PreviewBuffers | null): void + /** Dims the toolpaths while they no longer match the plate (a new slice is on its way), instead of hiding them. */ + setPreviewStale?(stale: boolean): void + /** A second, faint set of toolpaths under the live one: the slice before a change. Null removes it. It follows the layer range. */ + setPreviewGhost(buffers: PreviewBuffers | null): void + /** Where the plate's front left corner sits in the toolpaths' (machine) coordinates, mm: the preview is drawn shifted back by it. */ + setPreviewOrigin(x: number, y: number): void + /** 0-based, inclusive layer indexes. */ + /** Reserves the bottom `px` of the view for an overlay (the playback bar). */ + setBottomInset(px: number): void + /** Reserves the sides of the view that overlays cover, in pixels; views frame the model in the free area. */ + setInsets(insets: { left: number; right: number; top: number; bottom: number }): void + /** Turns the bed outline orange (an object is off the bed). */ + setBedAlert(on: boolean): void + /** Hides the bed for modeling: a plain ground grid at bed level, the camera and objects unchanged. */ + setGround(on: boolean): void + /** Hatches the parts of the bed nothing may print on (polygons in bed coordinates, mm). An empty list clears them. */ + setExcludedAreas(areas: readonly (readonly [number, number])[][]): void + /** Brightens one dual nozzle zone (by id); null resets. */ + setZoneHighlight(id: string | null): void + setLayerRange(lo: number, hi: number): void + /** Number of moves shown in the top layer of the range; null shows the whole layer. */ + setMoveCut(moves: number | null): void + setColorMode(mode: ColorMode): void + /** Filament colors by tool index, #rrggbb. */ + setToolColors(colors: string[]): void + /** The finish each tool's filament prints with, tool 1 first (satin where none is given). The toolpaths shine to match. */ + setToolFinishes?(finishes: ToolpathFinish[]): void + /** The bed under the print: `grid` (the default) or a build plate surface (textured or smooth PEI, cool, engineering). */ + setPlateStyle?(style: PlateStyle): void + /** The printer family's toolhead for a printer with one nozzle (`headFor` maps a profile id to it). */ + setHeadModel(model: HeadModel): void + /** The printer's tool changer: the toolhead, rack or dock Preview draws. Null draws the printer's own single head. */ + setToolChanger(spec: ToolChangerSpec | null): void + /** Plays the tool change before `segment`, `seconds` into it (`fixed`: the firmware's seconds of it). Null returns the head to the current move. */ + setToolChange(c: { segment: number; seconds: number; fixed: number } | null): void + /** Each tool change's purge at the chute, read from the G-code; the blob grows and drops while the change plays. Null for none. */ + setPurges?(plans: readonly PurgePlan[] | null): void + /** Preview's "Show toolhead": false hides the moving head and its carriage; the rack, dock, chute and wiper stay and follow the print. */ + setShowToolhead?(on: boolean): void + /** Preview's "Follow the nozzle": the camera moves with the head during playback, keeping its angle and zoom. */ + setFollowNozzle?(on: boolean): void + setTravels(on: boolean): void + /** Preview data beyond SXPV v1: fan, temperature, retraction and seam positions. Cleared by setPreview. */ + setPreviewExtras(extras: PreviewExtras | null): void + /** Which extras are loaded, so an app can offer the fan and temperature schemes and the marker toggles. */ + previewExtras(): { fan: boolean; temperature: boolean } & Record + /** Shows or hides each kind of marker. Markers follow the layer range. */ + setMarkers(opts: Partial>): void + /** + * Wipe, tool change and pause positions read from the G-code (x, y, z per marker, bed frame mm; z on the layer + * the marker belongs to). They keep until the next setPreview; null removes a kind. + */ + setGcodeMarkers(data: Partial>): void + /** heimdall's strikes: where the machine would meet a printed part (bed frame, mm), drawn over everything. Null clears them. */ + setStrikes?(marks: readonly StrikeMark[] | null): void + /** heimdall's gantry: the beam over the moving head (null for none), and the strikes it runs through a part on. */ + setGantry?(spec: GantrySpec | null, hits: readonly GantryHit[] | null): void + /** Value ranges for legends of the speed, flow, width, height, fan and temperature schemes. */ + previewRanges(): PreviewRanges + /** One row per feature type present: color, time, length and visibility. */ + previewLegend(): LegendFeature[] + /** Show or hide a feature type in Preview. */ + setFeatureVisible(id: number, visible: boolean): void + /** Show exactly these feature ids. */ + setVisibleFeatures(ids: readonly number[]): void + /** The move at the nozzle (the last one drawn): segment, layer and G-code line, for a G-code line view. Null without a preview. */ + currentMove(): { segment: number; layer: number; gcodeLine: number } | null + /** Number of moves in a layer, the range of the horizontal move slider. */ + layerMoveCount(layer: number): number + + on(event: E, cb: (payload: ViewportEvents[E]) => void): () => void + stats(): ViewportStats + resetStats(): void + /** Benchmarks and dev overlays: wait for the GPU after each frame so costMs holds the full frame cost. */ + setGpuTiming(on: boolean): void + /** Request a frame. The viewport renders on demand and idles otherwise. */ + invalidate(): void + dispose(): void +} diff --git a/desktop/src/vendor/slicerx/viewport/viewport.ts b/desktop/src/vendor/slicerx/viewport/viewport.ts new file mode 100644 index 00000000..535663cd --- /dev/null +++ b/desktop/src/vendor/slicerx/viewport/viewport.ts @@ -0,0 +1,2900 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 The SlicerX contributors +// createViewport: owns the renderer, the scene graph and the render loop. +// Frames are rendered on demand; the GPU idles when nothing changes, and the +// loop pauses while the canvas is offscreen or the page is hidden. +// --------------------------------------------------------------------------------------------------------------- +// MODIFIED BY SNAPMAKER STUDIO (DVOpenLabs/snapmaker-studio): the only change in this file is the import path of the +// contracts module ('@slicerx/contracts' -> '../contracts/index'). Upstream: slicerx-oss/slicerx @ +// edb521fe41306dd60d01bda8a0f6bf8aa54fcb29 (Apache-2.0). See ../UPDATING.md. +// --------------------------------------------------------------------------------------------------------------- +import { FirstFrameGate } from './firstframe' +import { gpuProfile } from './gpu' +import type { ToolChangerSpec } from './toolchanger' +import type { PurgePlan } from './purge' +import type { HeadModel } from './heads' +import { + DoubleSide, + FrontSide, + BufferAttribute, + BufferGeometry, + Box3, + Color, + Matrix3, + Matrix4, + MeshBasicMaterial, + Mesh, + NoToneMapping, + PerspectiveCamera, + Plane, + Raycaster, + SRGBColorSpace, + Vector2, + Vector3, + WebGLRenderer, + type Group, + type Material, + type Object3D, +} from 'three' +import type { DragAction } from './controls' +import { facePatch } from './faces' +import { Painter, type PaintHit } from './painter' +import { ScaleGizmo } from './gizmo' +import { RingSet, angleAround, pickRing, rayPlane, ringAxes, rotateAbout, snapAngle, turnVector, unit, unwrapAngle, type RingAxis, type RotateSpace } from './rings' +import { CutGizmo, CutPreview, extentAlong, movePlane, tiltAxes, type CutKeep } from './cutplane' +import { DimensionLayer, EdgePreview, PushPreview, SketchLayer, fromPlane, rayOnPlane, type DimensionMark, type SketchCursor, type SketchScene, type V2 } from './cadtools' +import { clampScale, factorsFor, handleAxis, handleLocal, minFactorFor, nearestOnLine, pivotFor, ratioLine, ratioPivotFor, ratioPlane, ratioPoint, scaleTransform, snapScale, type HandleId, type V3 } from './scaling' +import type { ModKey } from './gizmobindings' +import { layerTopsProblems } from './layerheights' +import { FEATURE_COLORS, SCENE, resolveTheme, type ResolvedTheme, type ViewportTheme } from './palette' +import { summarizePreview, type PreviewSummary } from './summary' +import { CONTROL_PRESETS, buttonName, dragStartsOnModel, modifiersOf, orbitCodeFor, resolveDrag, resolveWheel, type ControlsMap, type ControlsPresetId } from './controls' +import { OrbitControls } from 'three/addons/controls/OrbitControls.js' +import type { PreviewBuffers } from '../contracts/index' +import { BrimEars } from './brim' +import { GapLines, type GapLine } from './gaps' +import { GuideLines, type Guides } from './guides' +import { applyInsets, CameraRig, NO_INSETS, reducedMotion, type Insets } from './camera' +import { MaterialCache, setSharedBandColors, setSharedLayerTops, setSharedSceneColors, shared, sharedMaterials } from './materials' +import { buildObject, disposeObject, type ObjectEntry } from './model' +import { Pipeline } from './post' +import { Stage } from './stage' +import { FrameProbe, probeRequested, type ProbeStats } from './probe' +import { Toolpaths, warmupBuffers } from './toolpaths' +import { Strikes, type StrikeMark } from './strikes' +import type { GantryHit, GantrySpec } from './gantry' +import type { + CameraState, + CutPlaneSpec, + PushEvent, + PushSpec, + EdgePreviewSpec, + SketchEvent, + ColorMode, + PartStyle, + FacePick, + LegendFeature, + MarkerKind, + PreviewExtras, + PreviewRanges, + PaintLayer, + PaintSettings, + PlateTool, + Quality, + RenderMode, + DisplayStyle, + Projection, + ViewPreset, + Viewport, + ViewportEvents, + ViewportMode, + ViewportOptions, + ViewportPlate, + ViewportStats, + ToolpathFinish, + PlateStyle, +} from './types' + +const RING = 600 +const SETTLE_FRAMES = 3 +/** Field of view of the orthographic stand-in, degrees. */ +const ORTHO_FOV = 1 +const DEG = Math.PI / 180 +const dot3 = (a: readonly number[], b: readonly number[]): number => (a[0] ?? 0) * (b[0] ?? 0) + (a[1] ?? 0) * (b[1] ?? 0) + (a[2] ?? 0) * (b[2] ?? 0) +/** The push distance in words, next to the cursor while dragging. */ +const pushLabel = (d: number): string => (d < 0 ? `Cuts ${(-d).toFixed(1)} mm` : `Adds ${d.toFixed(1)} mm`) + +class Ring { + private readonly data = new Float32Array(RING) + private n = 0 + private i = 0 + push(v: number): void { + this.data[this.i] = v + this.i = (this.i + 1) % RING + this.n = Math.min(RING, this.n + 1) + } + values(): number[] { + const out: number[] = [] + for (let k = 0; k < this.n; k++) out.push(this.data[(this.i - this.n + k + RING) % RING] ?? 0) + return out + } + clear(): void { + this.n = 0 + this.i = 0 + } +} + +function percentile(sorted: number[], p: number): number { + if (sorted.length === 0) return 0 + const k = Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1)) + return sorted[k] ?? 0 +} + +function gpuName(r: WebGLRenderer): string { + const gl = r.getContext() + const ext = gl.getExtension('WEBGL_debug_renderer_info') + if (!ext) return 'unknown' + const v: unknown = gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) + return typeof v === 'string' ? v : 'unknown' +} + +type Listener = (payload: never) => void + +interface Drag { + entry: ObjectEntry + kind: 'move' | 'rotate' + start: number[] + offset: [number, number] + rel: { min: [number, number]; max: [number, number] } + startX: number + center: [number, number] + startYaw: number +} + +export function createViewport(canvas: HTMLCanvasElement, opts: ViewportOptions = {}): Viewport { + return new ViewportImpl(canvas, opts) +} + +/** Side length of moving frames, as a share of the still frame, that a high density screen starts with (0.7 is half the pixels). */ +const MOTION_START_HIDPI = 0.7 + +/** A ring drag in progress (rotate tool and cut tilt): the turn so far follows the cursor around `center` on the ring's plane, or along its screen tangent when the ring was grabbed edge on. */ +interface RingDrag { + center: V3 + radius: number + dir: V3 + from: V3 + angle: number + edgeOn: boolean + x0: number + y0: number + tangent: [number, number] + rpx: number +} + +interface PickHit { + entry: ObjectEntry + part: number + point: Vector3 + face: number + dir: Vector3 +} + +class ViewportImpl implements Viewport { + readonly canvas: HTMLCanvasElement + private readonly renderer: WebGLRenderer + private readonly stage: Stage + private readonly pipeline: Pipeline + private readonly camera: PerspectiveCamera + private readonly controls: OrbitControls + private readonly rig: CameraRig + private readonly toolpaths = new Toolpaths() + private readonly strikes = new Strikes() + private readonly mats = new MaterialCache() + private readonly objects = new Map() + private readonly listeners = new Map>() + private readonly frameMs = new Ring() + private readonly renderMs = new Ring() + private readonly costMs = new Ring() + + private readonly quality: Quality + private readonly gpu: string + private readonly weak: boolean + private readonly adaptive: boolean + private readonly maxPr: number + private readonly ro: ResizeObserver | null + private readonly io: IntersectionObserver | null + private readonly cleanups: (() => void)[] = [] + private mode: ViewportMode = 'prepare' + private renderMode: RenderMode = 'studio' + private selection: string[] = [] + private controlsMap: ControlsMap = CONTROL_PRESETS.slicerx + private spaceDown = false + private projection: Projection = 'perspective' + private display: DisplayStyle = 'edges' + private pickFn: (e: { clientX: number; clientY: number }) => PickHit | null = () => null + private faceOverlay: Mesh | null = null + private faceKey = '' + private featureMask = 0x7fff + private painter!: Painter + private readonly gizmo = new ScaleGizmo() + private scaleDrag: { entry: ObjectEntry; kind: HandleId; start: number[]; box: Box3; startRay: { o: V3; d: V3 }; pinAtStart: boolean; startRatioT: number | null } | null = null + private keys = { shift: false, ctrl: false, alt: false } + private painting: { x: number; y: number; pointerId: number } | null = null + private layerTops: number[] | null = null + private layerBand = true + private summary: PreviewSummary | null = null + private summaryFor: PreviewBuffers | null = null + private theme: ResolvedTheme = resolveTheme() + private faceColor: string = SCENE.selection + private perspFov = 30 + private aoLevel = 1 + private tool: PlateTool = 'select' + private pr = 1 + private aoOn: boolean + private dirty = true + private shadowDirty = true + private raf = 0 + private lastRenderT = 0 + private frameIdx = 0 + private frames = 0 + /** Frames left in the fade-in of full-quality effects after the camera stops. */ + private settle = 0 + private slow = 0 + private scrubbed = false + private motionSeeded = false + private slowFrames = 0 + private fastFrames = 0 + private raiseAfter = 45 + private raisedAt = 0 + private onscreen = true + private gpuTiming = false + private probe: FrameProbe | null = null + private disposed = false + private previewSetAt: number | null = null + private previewGen = 0 + private readonly firstFrame = new FirstFrameGate() + private afterFrame: (() => void) | null = null + private cameraMoved = false + private firstFrameMs: number | null = null + private arrangeAnim: ((now: number) => boolean) | null = null + private drag: Drag | null = null + private width = 1 + private height = 1 + private insets: Insets = NO_INSETS + private readonly brim = new BrimEars() + private readonly gaps = new GapLines() + private readonly guides = new GuideLines() + private ghost: Toolpaths | null = null + private probeFaces = false + private brimDrag: { kind: 'ear'; objectId: string; index: number; moved: boolean } | { kind: 'rect'; x0: number; y0: number; mode: 'add' | 'remove'; ear: { objectId: string; index: number } | null; moved: boolean } | null = null + private brimRectEl: HTMLDivElement | null = null + private readonly rotRings = new RingSet(['x', 'y', 'z']) + private rotSpace: RotateSpace = 'world' + private rotDrag: (RingDrag & { entry: ObjectEntry; axis: RingAxis; start: number[]; shown: number; snapped: boolean }) | null = null + private readonly cutGizmo = new CutGizmo() + private readonly cutRings = new RingSet<'u' | 'v'>(['u', 'v'], { u: '#ff79c6', v: '#bd93f9' }) + private readonly cutPreview = new CutPreview() + private cut: { entry: ObjectEntry; point: V3; normal: V3; keep: CutKeep; place: boolean } | null = null + private cutDrag: ({ kind: 'move'; point0: V3; extent: [number, number]; t0: number | null; mmPerPx: number; x0: number; y0: number } | (RingDrag & { kind: 'tilt'; ring: 'u' | 'v'; normal0: V3 })) | null = null + private gizmoLabel: HTMLDivElement | null = null + private readonly pushView = new PushPreview() + private readonly edgeView = new EdgePreview() + private probeHover = false + private push: PushSpec | null = null + private pushDrag: { started: boolean; objectId: string; partIndex: number; triangle: number; point: V3; normal: V3; d0: number; d: number; snapped: boolean; t0: number | null; mmPerPx: number; x0: number; y0: number } | null = null + private readonly sketchLayer = new SketchLayer() + private sketchDrag: { handle: number } | null = null + private readonly dims = new DimensionLayer() + private readonly tmpRay = new Raycaster() + + constructor(canvas: HTMLCanvasElement, opts: ViewportOptions) { + this.canvas = canvas + let renderer: WebGLRenderer + try { + renderer = new WebGLRenderer({ canvas, antialias: false, alpha: false, stencil: false, powerPreference: 'high-performance' }) + } catch (e) { + throw new Error('The 3D view needs WebGL2. Turn on hardware acceleration in the browser settings, then reload.', { cause: e }) + } + this.renderer = renderer + renderer.autoClear = false + renderer.info.autoReset = false + renderer.outputColorSpace = SRGBColorSpace + renderer.toneMapping = NoToneMapping + const gpu = gpuProfile(gpuName(renderer), opts.gpuRenderer) + this.gpu = gpu.name + this.weak = gpu.weak + if (gpu.software) { + const message = gpu.fromShell + ? `This computer has no graphics driver for 3D, so it is drawn on the processor (${gpu.name}) and the 3D view will be slow.` + : 'Hardware acceleration looks off in this browser, so the 3D view will be slow. Turn it on in the browser settings and reload.' + // Listeners attach after construction, so tell them on the next turn. + setTimeout(() => this.emit('degrade', { message }), 0) + } + this.quality = opts.quality ?? (this.weak ? 'low' : 'high') + this.adaptive = opts.adaptive ?? true + this.maxPr = opts.maxPixelRatio ?? (this.weak ? 1.25 : 2) + this.aoOn = this.quality !== 'low' + canvas.tabIndex = 0 + canvas.setAttribute('aria-label', opts.label ?? '3D view of the plate. Drag to orbit, scroll to zoom.') + canvas.style.touchAction = 'none' + + this.stage = new Stage(renderer, this.weak) + if (probeRequested()) this.probe = new FrameProbe(renderer) + this.pipeline = new Pipeline(renderer, this.quality) + this.camera = new PerspectiveCamera(30, 1, 20, 1600) + this.camera.position.set(260, 230, 330) + this.controls = new OrbitControls(this.camera, canvas) + const c = this.controls + c.enableDamping = true + c.dampingFactor = 0.085 + c.screenSpacePanning = true + c.minDistance = 30 + c.maxDistance = 1500 + // Bottom view looks up at the plate, so the orbit may pass under it. + c.maxPolarAngle = Math.PI + this.applyControls() + c.target.set(0, 30, 0) + c.update() + this.rig = new CameraRig(this.camera, this.controls) + const onChange = (): void => { + // OrbitControls also updates inside its pointer handlers, so its own return value can miss motion. + this.cameraMoved = true + this.invalidate() + } + const onStart = (): void => { + this.rig.preset = null + this.rig.move = null + } + c.addEventListener('change', onChange) + c.addEventListener('start', onStart) + this.cleanups.push(() => { + c.removeEventListener('change', onChange) + c.removeEventListener('start', onStart) + }) + + this.painter = new Painter( + (id) => this.objects.get(id), + this.stage.scene, + () => this.invalidate(), + (s) => this.emit('paintstroke', s), + () => this.controlsMap.gizmo.paint, + ) + this.painter.applyPreset() + this.painter.onClip = () => this.applyClip() + this.painter.onSettings = (s) => this.emit('paintsettings', { ...s, heightRangeMm: [...s.heightRangeMm] }) + this.stage.scene.add(this.gizmo.group) + this.stage.previewRoot.add(this.toolpaths.root) + this.toolpaths.root.add(this.strikes.root) + this.stage.objectsRoot.add(this.brim.group) + this.stage.objectsRoot.add(this.gaps.group) + this.stage.objectsRoot.add(this.guides.group) + this.stage.objectsRoot.add(this.rotRings.group, this.cutGizmo.group, this.cutRings.group, this.pushView.group, this.edgeView.group, this.sketchLayer.group, this.dims.group) + this.stage.envSH.then( + (sh) => { + if (this.disposed) return + this.toolpaths.setEnvironment(sh) + this.invalidate() + }, + (e: unknown) => { + // Toolpaths keep their flat ambient light without the bake; only a real failure is worth a line in the console. + if (!this.disposed) console.warn('Environment bake failed', e) + }, + ) + this.stage.previewRoot.visible = false + if (opts.controls) this.setControls(opts.controls) + if (opts.theme) this.setTheme(opts.theme) + + this.ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => this.resize()) : null + this.ro?.observe(canvas) + this.io = + typeof IntersectionObserver !== 'undefined' + ? new IntersectionObserver((en) => { + this.onscreen = en[0]?.isIntersecting ?? true + this.kick() + }) + : null + this.io?.observe(canvas) + const onVis = (): void => this.kick() + document.addEventListener('visibilitychange', onVis) + this.cleanups.push(() => document.removeEventListener('visibilitychange', onVis)) + const onLost = (e: Event): void => { + e.preventDefault() + this.emit('error', { message: 'The graphics context was lost. Reload the view to continue.' }) + } + canvas.addEventListener('webglcontextlost', onLost) + this.cleanups.push(() => canvas.removeEventListener('webglcontextlost', onLost)) + this.bindPointer() + this.resize() + this.view('iso') + // The warm-up compiles the bead shaders and shows the bead for a frame; it waits so the plate draws first. + this.firstFrame.after(() => requestAnimationFrame(() => void this.warmPreview())) + } + + /** Compiles the bead shaders in the background so the first real preview frame does not wait for them. */ + private async warmPreview(): Promise { + const gen = this.previewGen + const root = this.stage.previewRoot + this.toolpaths.set(warmupBuffers()) + this.toolpaths.warmNozzle(true) + root.visible = true + await this.renderer.compileAsync(this.stage.scene, this.camera).catch(() => { + // Best effort: if it fails, the first real preview frame compiles the shaders instead. + }) + if (this.disposed) return + // One frame with the warm-up bead and a shadow update also builds the shadow-pass program. + this.shadowDirty = true + this.afterFrame = () => { + root.visible = this.mode === 'preview' + if (this.previewGen === gen) { + this.toolpaths.warmNozzle(false) + this.toolpaths.set(null) + } + this.shadowDirty = true + } + this.invalidate() + } + + // ---------- events ---------- + + on(event: E, cb: (payload: ViewportEvents[E]) => void): () => void { + let set = this.listeners.get(event) + if (!set) { + set = new Set() + this.listeners.set(event, set) + } + const l = cb as Listener + set.add(l) + return () => set.delete(l) + } + + private emit(event: E, payload: ViewportEvents[E]): void { + const set = this.listeners.get(event) + if (!set) return + for (const l of set) (l as (p: ViewportEvents[E]) => void)(payload) + } + + // ---------- loop ---------- + + invalidate(): void { + this.dirty = true + this.kick() + } + + private canRun(): boolean { + return !this.disposed && this.onscreen && !(typeof document !== 'undefined' && document.hidden) + } + + private kick(): void { + if (this.raf || !this.canRun()) return + this.raf = requestAnimationFrame(this.tick) + } + + private readonly tick = (now: number): void => { + this.raf = 0 + if (!this.canRun()) { + this.lastRenderT = 0 + return + } + let moving = this.rig.step(now) || this.cameraMoved + this.cameraMoved = false + if (this.controls.update()) moving = true + if (this.arrangeAnim && this.arrangeAnim(now)) moving = true + // Scrubbing layers or moves redraws like orbiting: cheap frames while it changes, full quality once it stops. + const camMoving = moving + if (this.scrubbed) { + this.scrubbed = false + moving = true + } + if (moving) { + this.dirty = true + this.settle = SETTLE_FRAMES + } else if (this.settle > 0) this.dirty = true + if (this.dirty) { + this.dirty = false + // Moving frames skip AO and MSAA; once the camera stops, full quality returns and AO fades in. + let aoMix: number + if (moving) { + // Fade AO out over a few frames instead of cutting it, so starting to orbit does not pop the plate and shadows. + this.aoLevel = Math.max(0, this.aoLevel - 0.34) + aoMix = this.aoLevel + } else { + aoMix = this.settle > 0 ? (SETTLE_FRAMES - this.settle + 1) / SETTLE_FRAMES : 1 + this.aoLevel = aoMix + } + if (!moving && this.settle > 0) this.settle-- + this.renderFrame(aoMix, moving) + if (this.lastRenderT) this.trackFrame(now - this.lastRenderT) + if (this.lastRenderT && moving) this.tuneMotionScale(now - this.lastRenderT) + this.lastRenderT = now + if (camMoving) this.emit('camera', { preset: this.rig.preset }) + } else { + this.lastRenderT = 0 + } + // Through kick, never a bare requestAnimationFrame: a listener that invalidated during this tick has already + // queued the next one, and a second request would start a second loop that renders every frame again. + if (moving || this.dirty || this.rig.move || this.arrangeAnim) this.kick() + } + + /** + * Resolution of moving frames follows the frame time: a GPU that cannot hold 60 fps at the full pixel count + * draws orbit frames smaller (the last pass upsamples them) and sharpens again once frames are cheap. + */ + private tuneMotionScale(dt: number): void { + const p = this.pipeline + if (dt > 22) { + this.fastFrames = 0 + if (++this.slowFrames >= (dt > 45 ? 2 : 4)) { + this.slowFrames = 0 + if (p.motionScale > 0.3) { + // Area scales the cost, so the side length scales with the square root of the time to win back. + p.motionScale = Math.min(p.motionScale - 0.05, p.motionScale * Math.sqrt(17 / dt)) + if (this.raisedAt && this.frames - this.raisedAt < 240) this.raiseAfter = Math.min(this.raiseAfter * 2, 960) + } + } + } else if (dt < 19 && p.motionScale < 1) { + this.slowFrames = 0 + if (++this.fastFrames >= this.raiseAfter) { + this.fastFrames = 0 + p.motionScale = p.motionScale + 0.1 + this.raisedAt = this.frames + } + } else this.slowFrames = Math.max(0, this.slowFrames - 1) + } + + private trackFrame(dt: number): void { + this.frameMs.push(dt) + if (!this.adaptive || !this.aoOn) return + if (dt > 55) { + if (++this.slow > 14) this.degrade() + } else this.slow = Math.max(0, this.slow - 1) + } + + private degrade(): void { + this.aoOn = false + this.slow = 0 + if (this.pr > 1) { + this.pr = 1 + this.resize() + } + this.emit('degrade', { message: 'Ambient occlusion paused to keep the view smooth on this GPU.' }) + } + + private renderFrame(aoMix: number, moving: boolean): void { + const t0 = performance.now() + this.probe?.begin() + this.renderer.info.reset() + const bed = this.stage.bed + this.rig.fitClip(Math.max(bed.widthMm, bed.depthMm, bed.heightMm * 0.6)) + if (this.shadowDirty) { + this.renderer.shadowMap.needsUpdate = true + this.shadowDirty = false + } + const outline: Object3D[] = [] + if (this.mode === 'prepare') { + for (const id of this.selection) { + const o = this.objects.get(id) + if (o) outline.push(o.group) + } + } + if (this.mode === 'preview') { + const camBed = this.camera.position.clone().applyMatrix4(this.stage.bedRoot.matrixWorld.clone().invert()) + this.toolpaths.setView(camBed, this.pipeline.size.height) + this.ghost?.setView(camBed, this.pipeline.size.height) + } + this.stage.updateZoneLabels(this.camera, this.pipeline.size.height / this.pipeline.size.pixelRatio) + this.painter.sync() + this.gaps.follow((id) => this.objects.get(id)?.group.matrix) + this.updateGizmo() + // Only while their tool is on: the rings follow the selection, the cut gizmo its plane. + if (this.tool === 'rotate' || this.rotRings.visible) this.updateRings() + if (this.cut || this.cutGizmo.group.visible) this.updateCutGizmo() + this.dims.fit(this.camera.fov, this.height) + const ao = this.aoOn && aoMix > 0 && this.display !== 'wireframe' && !(this.mode === 'prepare' && this.renderMode === 'xray') + const firstPreviewFrame = this.previewSetAt !== null && this.mode === 'preview' + this.stage.bakePendingContact() + this.pipeline.render(this.stage.scene, this.camera, { ao, aoMix, fast: moving, outline, frameIndex: this.frameIdx++ }) + this.probe?.end() + // Timer queries are not used for this: on ANGLE's Metal backend they span queued work and read high. + if (this.gpuTiming || firstPreviewFrame) this.pipeline.waitForGpu() + const t1 = performance.now() + this.renderMs.push(t1 - t0) + if (this.gpuTiming) this.costMs.push(t1 - t0) + this.frames++ + this.firstFrame.frame() + if (this.afterFrame) { + const f = this.afterFrame + this.afterFrame = null + f() + this.invalidate() + } + if (this.previewSetAt !== null && this.mode === 'preview') { + this.firstFrameMs = t1 - this.previewSetAt + this.previewSetAt = null + } + } + + private resize(): void { + if (this.disposed) return + const w = Math.max(1, this.canvas.clientWidth) + const h = Math.max(1, this.canvas.clientHeight) + const dpr = typeof devicePixelRatio === 'number' ? devicePixelRatio : 1 + if (this.frames === 0 || this.pr > 1 || !this.adaptive) this.pr = Math.min(dpr, this.maxPr) + this.width = w + this.height = h + this.renderer.setPixelRatio(this.pr) + this.renderer.setSize(w, h, false) + this.pipeline.setSize(w, h, this.pr) + // On a high density screen the first orbit starts at about half the pixels, so it is smooth from its first frame. + // tuneMotionScale raises it while frames stay cheap; still frames are always drawn at the full size with MSAA. + if (!this.motionSeeded) { + this.motionSeeded = true + if (this.pr >= 1.5) this.pipeline.motionScale = MOTION_START_HIDPI + } + this.camera.aspect = w / h + this.applyInset() + shared.gmin.value = this.pr >= 1.5 ? 6.5 : 4 + // Sizing the canvas clears it. The observer runs before the page paints, so drawing now keeps the old picture + // from going blank for a frame when a panel or bar beside the view changes size. + if (this.frames > 0 && this.canRun()) this.renderFrame(this.aoLevel, false) + this.invalidate() + } + + /** Reserves the bottom `px` of the view for an overlay: the picture shifts up and views frame the model above it. */ + setBottomInset(px: number): void { + this.setInsets({ ...this.insets, bottom: px }) + } + + /** + * Reserves the sides of the view that overlays cover (pixels): the picture centers in what is left and + * views frame the model inside it. A camera still on a view preset frames again for the new free area. + */ + setInsets(next: Insets): void { + const r = (n: number) => Math.max(0, Math.round(n)) + const v = { left: r(next.left), right: r(next.right), top: r(next.top), bottom: r(next.bottom) } + const old = this.insets + if (v.left === old.left && v.right === old.right && v.top === old.top && v.bottom === old.bottom) return + this.insets = v + this.applyInset() + if (this.rig.preset) this.view(this.rig.preset) + this.invalidate() + } + + private applyInset(): void { + this.rig.free = applyInsets(this.camera, this.width, this.height, this.insets) + } + + // ---------- modes ---------- + + setMode(mode: ViewportMode): void { + if (mode === this.mode) return + this.mode = mode + const pv = mode === 'preview' + this.stage.objectsRoot.visible = !pv + this.stage.previewRoot.visible = pv + this.stage.setContactVisible(!pv && this.renderMode !== 'xray') + this.shadowDirty = true + this.invalidate() + } + + setRenderMode(mode: RenderMode): void { + this.renderMode = mode + this.applyMaterials() + } + + private applyMaterials(): void { + this.cutPreview.detach() + const x = this.renderMode === 'xray' + const wire = this.display === 'wireframe' + const sh = sharedMaterials() + for (const o of this.objects.values()) { + for (const p of o.parts) { + const m = this.mats.get(this.renderMode, { color: p.color, finish: p.finish }) + // Clay and overhang materials are shared by every viewport on the page, so a page has one display style for them. + ;(m as Material & { wireframe?: boolean }).wireframe = wire + p.mesh.material = m + p.mesh.castShadow = !x && !wire + p.mesh.receiveShadow = !x && !wire + p.mesh.renderOrder = x ? 2 : 0 + p.edges.material = x ? sh.edgeXray : sh.edgeDark + p.edges.visible = x || this.display === 'edges' + } + } + this.stage.setContactVisible(!x && this.mode === 'prepare') + this.shadowDirty = true + this.applyClip() + this.syncCutPreview() + } + + /** Puts the painter's clipping plane on the models' materials (nothing when it is off). */ + private applyClip(): void { + const plane = this.painter?.clipPlane() ?? null + this.renderer.localClippingEnabled = true + const set = (m: Material | Material[]): void => { + for (const mat of Array.isArray(m) ? m : [m]) { + const had = (mat.clippingPlanes?.length ?? 0) > 0 + mat.clippingPlanes = plane ? [plane] : null + if (had !== !!plane) mat.needsUpdate = true + } + } + for (const o of this.objects.values()) { + // The model being cut carries the cut's own clipping planes. + if (o === this.cutPreview.entry) continue + for (const p of o.parts) { + set(p.mesh.material) + set(p.edges.material) + } + } + this.invalidate() + } + + setDisplayStyle(style: DisplayStyle): void { + if (style === this.display) return + this.display = style + this.applyMaterials() + } + + setOverhangAngle(deg: number): void { + shared.overhangDeg.value = Math.max(0, Math.min(89, deg)) + this.invalidate() + } + + setLayerHeights(tops: ArrayLike | null, opts: { band?: boolean } = {}): void { + if (tops) { + const problems = layerTopsProblems(tops) + if (problems.length) throw new Error(`Invalid layer heights: ${problems.join('; ')}`) + } + this.layerTops = tops ? Array.from(tops) : null + this.layerBand = opts.band ?? this.layerBand + setSharedLayerTops(this.layerTops, this.layerBand) + this.shadowDirty = true + this.invalidate() + } + + setLayerHeightBand(on: boolean): void { + this.layerBand = on + setSharedLayerTops(this.layerTops, on) + this.invalidate() + } + + setPrintLook(on: boolean, layerHeightMm = 0.2): void { + shared.lines.value = on ? 1 : 0 + shared.layerH.value = Math.max(0.02, layerHeightMm) + this.invalidate() + } + + // ---------- plate ---------- + + setPlate(plate: ViewportPlate, opts: { keepCamera?: boolean } = {}): void { + this.stage.setBed(plate.bed, plate.surfaceLabel) + this.stage.setNozzleZones(plate.zones ?? []) + if (plate.excluded) this.stage.setExcludedAreas(plate.excluded) + this.hoverFace(null) + this.cutPreview.detach() + for (const o of this.objects.values()) disposeObject(o) + this.objects.clear() + const sh = sharedMaterials() + for (const obj of plate.objects) { + const entry = buildObject(obj, (p) => this.mats.get(this.renderMode, { color: p.color, finish: p.finish ?? 'basic' }), this.renderMode === 'xray' ? sh.edgeXray : sh.edgeDark) + this.objects.set(obj.id, entry) + this.stage.objectsRoot.add(entry.group) + } + this.selection = this.selection.filter((id) => this.objects.has(id)) + // The cut follows its model into the new plate by id, or ends when the model is gone. + if (this.cut) { + const e = this.objects.get(this.cut.entry.id) + this.cut = e ? { ...this.cut, entry: e } : null + } + this.applyMaterials() + this.objectsMoved() + if (!opts.keepCamera) this.view('iso') + } + + setTransforms(transforms: Record): void { + for (const [id, m] of Object.entries(transforms)) { + const o = this.objects.get(id) + if (!o) continue + o.group.matrix.fromArray(m) + o.group.matrixWorldNeedsUpdate = true + } + this.objectsMoved() + } + + setPartStyle(objectId: string, partIndex: number, style: PartStyle): void { + const p = this.objects.get(objectId)?.parts[partIndex] + if (!p) return + if (style.color) p.color = style.color + if (style.finish) p.finish = style.finish + const cutting = this.cutPreview.entry?.id === objectId + if (cutting) this.cutPreview.detach() + p.mesh.material = this.mats.get(this.renderMode, { color: p.color, finish: p.finish }) + if (cutting) this.syncCutPreview() + this.invalidate() + } + + private objectsMoved(): void { + this.stage.scene.updateMatrixWorld(true) + this.stage.requestContact() + this.shadowDirty = true + this.invalidate() + } + + setSelection(ids: string[]): void { + this.selection = ids.filter((id) => this.objects.has(id)) + this.invalidate() + } + + setBrimEars(ears: Record): void { + this.brim.setEars(ears) + this.invalidate() + } + + setGapLines(lines: readonly GapLine[]): void { + this.gaps.set(lines) + this.invalidate() + } + + setGuides(guides: Guides): void { + if (this.guides.set(guides)) this.invalidate() + } + + setProbeHover(on: boolean): void { + if (this.probeHover && !on) this.emit('probehover', null) + this.probeHover = on + } + + setEdgePreview(preview: EdgePreviewSpec | null): void { + this.edgeView.set(preview) + this.invalidate() + } + + setProbeFaces(on: boolean): void { + this.probeFaces = on + if (!on && this.tool === 'probe') this.hoverFace(null) + } + + setBrimHoverRadius(r: number | null): void { + this.brim.setHoverRadius(r) + this.invalidate() + } + + private showBrimRect(x0: number, y0: number, x1: number, y1: number, mode: 'add' | 'remove'): void { + if (typeof document === 'undefined') return + let r = this.brimRectEl + if (!r) { + r = document.createElement('div') + r.style.cssText = 'position:fixed;pointer-events:none;z-index:20;border-radius:2px;border:1px dashed' + document.body.appendChild(r) + this.brimRectEl = r + } + const c = mode === 'remove' ? this.theme.scene.overhangRed : this.theme.scene.selection + r.style.borderColor = c + r.style.background = `${c}22` + r.style.left = `${Math.min(x0, x1)}px` + r.style.top = `${Math.min(y0, y1)}px` + r.style.width = `${Math.abs(x1 - x0)}px` + r.style.height = `${Math.abs(y1 - y0)}px` + r.style.display = 'block' + } + + private hideBrimRect(): void { + if (this.brimRectEl) this.brimRectEl.style.display = 'none' + } + + /** Emits the ears whose centers lie inside a screen rectangle, one event per object. */ + private brimRectSelect(x0: number, y0: number, x1: number, y1: number, mode: 'add' | 'remove'): void { + const rc = this.canvas.getBoundingClientRect() + const [l, r] = [Math.min(x0, x1), Math.max(x0, x1)] + const [t, b] = [Math.min(y0, y1), Math.max(y0, y1)] + this.stage.scene.updateMatrixWorld(true) + const m = this.stage.bedRoot.matrixWorld + const v = new Vector3() + const hits = new Map() + // As in Orca (get_unobscured_idxs), an ear behind the model is skipped. The ear and a point just above it are tested, + // so an ear is not hidden by every small irregularity on the model. + const meshes: Mesh[] = [] + for (const o of this.objects.values()) for (const p of o.parts) meshes.push(p.mesh) + const rc3 = new Raycaster() + const cam = this.camera.getWorldPosition(new Vector3()) + const visible = (pt: Vector3): boolean => { + const dir = pt.clone().sub(cam) + const dist = dir.length() + rc3.set(cam, dir.normalize()) + rc3.far = dist + const h = rc3.intersectObjects(meshes, false)[0] + return !h || h.distance > dist - 0.4 + } + this.brim.forEachEar((id, i, e) => { + v.set(e.x, e.y, e.z).applyMatrix4(m).project(this.camera) + if (v.z > 1) return + const sx = rc.left + (v.x * 0.5 + 0.5) * rc.width + const sy = rc.top + (-v.y * 0.5 + 0.5) * rc.height + if (sx < l || sx > r || sy < t || sy > b) return + const at = new Vector3(e.x, e.y, e.z + 0.1).applyMatrix4(m) + const above = new Vector3(e.x, e.y, e.z + 1.5).applyMatrix4(m) + if (visible(at) || visible(above)) hits.set(id, [...(hits.get(id) ?? []), i]) + }) + for (const [objectId, indices] of hits) this.emit('brimselect', { objectId, indices, mode }) + } + + setTool(tool: PlateTool): void { + this.tool = tool + if (tool !== 'brim' && this.brim.setHover(null)) this.invalidate() + if (tool !== 'face' && tool !== 'probe') this.hoverFace(null) + this.painter.setActive(tool === 'paint') + this.invalidate() + } + + /** Union of the model's part boxes in its own frame. */ + private localBox(entry: ObjectEntry): Box3 { + const b = new Box3() + // Part geometry never changes after it is built (transforms live on the group), so its box is computed once. + for (const p of entry.parts) { + const g = p.mesh.geometry + if (!g.boundingBox) g.computeBoundingBox() + if (g.boundingBox) b.union(g.boundingBox) + } + return b + } + + private scaleTarget(): ObjectEntry | null { + if (this.tool !== 'scale' || this.mode !== 'prepare') return null + const id = this.selection[0] + return (id ? this.objects.get(id) : undefined) ?? null + } + + scaleHandles(): Partial> | null { + const t = this.scaleTarget() + if (!t) return null + this.updateGizmo() + const world = this.gizmo.handleWorld(t.group, this.localBox(t)) + const r = this.canvas.getBoundingClientRect() + const out: Partial> = {} + for (const k of Object.keys(world) as HandleId[]) { + const p = world[k] + if (!p) continue + const v = new Vector3(...p).project(this.camera) + out[k] = [((v.x + 1) / 2) * r.width, ((1 - v.y) / 2) * r.height] + } + return out + } + + /** True when the key of a binding is down (null never is). */ + private modDown(key: ModKey | null, state = this.keys): boolean { + return key !== null && state[key] + } + + private updateGizmo(): void { + const t = this.scaleTarget() + const b = this.controlsMap.gizmo.scale + const pinned = this.scaleDrag ? this.pinned(this.scaleDrag.pinAtStart) : this.modDown(b.pinKey) + this.gizmo.update(t?.group ?? null, t ? this.localBox(t) : null, this.camera, this.height, this.camera.fov, { layout: b.layout, pivot: b.pivot, pinned }) + } + + /** Whether the pin key counts as held: read at the start of the drag (Orca) or live (Bambu Studio). */ + private pinned(atStart: boolean): boolean { + const b = this.controlsMap.gizmo.scale + return b.pinKey === null ? false : b.pinMode === 'at-start' ? atStart : this.modDown(b.pinKey) + } + + private scaleDown(ray: Raycaster): boolean { + const t = this.scaleTarget() + if (!t) return false + this.updateGizmo() + const kind = this.gizmo.hit(ray) + if (!kind) return false + t.group.updateMatrixWorld(true) + const b = this.controlsMap.gizmo.scale + this.scaleDrag = { + entry: t, + kind, + start: t.group.matrix.toArray(), + box: this.localBox(t), + startRay: { o: ray.ray.origin.toArray() as V3, d: ray.ray.direction.toArray() as V3 }, + pinAtStart: this.modDown(b.pinKey), + startRatioT: null, + } + this.gizmo.setDragging(kind) + this.controls.enabled = false + return true + } + + /** + * Factors of the running drag for a ray, or null when the ray cannot be turned into a ratio. The source of the ratio, the + * pivot, the pin and snap keys and the layout all come from the preset's scale bindings (gizmobindings.ts). + */ + private scaleFactors(ray: { o: V3; d: V3 }): { factors: V3; anchor: V3 } | null { + const d = this.scaleDrag + if (!d) return null + const b = this.controlsMap.gizmo.scale + const { entry, kind, box } = d + const min = box.min.toArray() as V3 + const max = box.max.toArray() as V3 + const origin = { layout: b.layout, pivot: b.pivot, cornerPinLocksZ: b.cornerPinLocksZ } + const pinned = this.pinned(d.pinAtStart) + const m = new Matrix4().fromArray(d.start) + const parent = entry.group.parent + parent?.updateMatrixWorld(true) + const toWorld = new Matrix4().multiplyMatrices(parent?.matrixWorld ?? new Matrix4(), m) + const world = (p: V3): V3 => new Vector3(...p).applyMatrix4(toWorld).toArray() as V3 + const pivotWorld = world(ratioPivotFor(kind, min, max, origin, pinned)) + const handleWorld = world(handleLocal(kind, min, max, b.layout)) + const len = Math.hypot(handleWorld[0] - pivotWorld[0], handleWorld[1] - pivotWorld[1], handleWorld[2] - pivotWorld[2]) + if (len < 1e-6) return null + let f: number + if (b.ratio === 'line') { + const dir: V3 = [(handleWorld[0] - pivotWorld[0]) / len, (handleWorld[1] - pivotWorld[1]) / len, (handleWorld[2] - pivotWorld[2]) / len] + const tNow = nearestOnLine(ray.o, ray.d, pivotWorld, dir) + const tStart = nearestOnLine(d.startRay.o, d.startRay.d, pivotWorld, dir) + if (tNow === null || tStart === null) return null + f = ratioLine(tNow, tStart, len) + } else if (b.ratio === 'point') { + f = ratioPoint(ray.o, ray.d, handleWorld, pivotWorld) + } else { + const upWorld = new Vector3(0, 0, 1).transformDirection(toWorld).toArray() as V3 + f = ratioPlane(ray.o, ray.d, handleWorld, pivotWorld, upWorld, handleAxis(kind) === 'z') + } + if (f <= 0) return null + if (this.modDown(b.snapKey)) f = snapScale(f, b.snapStep) + const scaleMm = toWorld.getMaxScaleOnAxis() + const sizes = [(max[0] - min[0]) * scaleMm, (max[1] - min[1]) * scaleMm, (max[2] - min[2]) * scaleMm] as V3 + f = Math.max(clampScale(f), minFactorFor(kind, sizes, b.minSizeMm)) + const lockZ = pinned && b.cornerPinLocksZ && handleAxis(kind) === 'uniform' + return { factors: factorsFor(kind, f, lockZ), anchor: pivotFor(kind, min, max, origin, pinned) } + } + + private scaleMove(ray: Raycaster, e: PointerEvent): void { + const d = this.scaleDrag + if (!d) return + this.keys = { shift: e.shiftKey, ctrl: e.ctrlKey || e.metaKey, alt: e.altKey } + const r = this.scaleFactors({ o: ray.ray.origin.toArray() as V3, d: ray.ray.direction.toArray() as V3 }) + if (!r) return + const m = scaleTransform(d.start, r.factors, r.anchor) + d.entry.group.matrix.fromArray(m) + d.entry.group.matrixWorldNeedsUpdate = true + this.emit('scale', { id: d.entry.id, factors: r.factors, uniform: handleAxis(d.kind) === 'uniform', snapped: this.modDown(this.controlsMap.gizmo.scale.snapKey) }) + this.emit('transform', { id: d.entry.id, transform: m, final: false }) + this.invalidate() + } + + private scaleEnd(cancel: boolean): void { + const d = this.scaleDrag + if (!d) return + this.scaleDrag = null + this.gizmo.setDragging(null) + this.controls.enabled = true + if (cancel) { + d.entry.group.matrix.fromArray(d.start) + d.entry.group.matrixWorldNeedsUpdate = true + } else this.emit('transform', { id: d.entry.id, transform: d.entry.group.matrix.toArray(), final: true }) + this.objectsMoved() + this.invalidate() + } + + // ---------- rotate rings ---------- + + private rotateTarget(): ObjectEntry | null { + if (this.tool !== 'rotate' || this.mode !== 'prepare' || this.cut) return null + const id = this.selection[0] + return (id ? this.objects.get(id) : undefined) ?? null + } + + /** Center of the model's box and a ring radius a little wider than the box, in bed coordinates. */ + private ringLayout(entry: ObjectEntry): { center: V3; radius: number } { + const b = this.localBox(entry) + if (b.isEmpty()) b.set(new Vector3(), new Vector3()) + const m = entry.group.matrix + const c = b.getCenter(new Vector3()).applyMatrix4(m) + const half = b.getSize(new Vector3()).length() / 2 + return { center: c.toArray() as V3, radius: Math.max(4, half * m.getMaxScaleOnAxis() * 1.08) } + } + + /** A ray in bed coordinates. */ + private bedRay(ray: Raycaster): { o: V3; d: V3 } { + const inv = this.stage.bedMatrix().invert() + return { o: ray.ray.origin.clone().applyMatrix4(inv).toArray() as V3, d: ray.ray.direction.clone().transformDirection(inv).toArray() as V3 } + } + + /** Millimeters per screen pixel at a bed point. */ + private mmPerPx(p: V3): number { + const w = new Vector3(...p).applyMatrix4(this.stage.bedMatrix()) + const dist = this.camera.position.distanceTo(w) + return (2 * dist * Math.tan((this.camera.fov * Math.PI) / 360)) / Math.max(1, this.height) + } + + /** A bed point on screen, in client pixels. */ + private toScreen(p: V3): [number, number] { + const v = new Vector3(...p).applyMatrix4(this.stage.bedMatrix()).project(this.camera) + const r = this.canvas.getBoundingClientRect() + return [r.left + ((v.x + 1) / 2) * r.width, r.top + ((1 - v.y) / 2) * r.height] + } + + /** Starts a ring drag: where the ring was grabbed, and the screen tangent there for a ring seen edge on. */ + private ringStart(o: V3, d: V3, center: V3, dir: V3, radius: number, e: { clientX: number; clientY: number }): RingDrag { + const ud = unit(d) + const hit = rayPlane(o, d, center, dir) + const edgeOn = !hit || Math.abs(ud[0] * dir[0] + ud[1] * dir[1] + ud[2] * dir[2]) < 0.15 + // Grabbed edge on, the ring counts as grabbed at its point nearest the camera. + const raw: V3 = hit && !edgeOn ? [hit[0] - center[0], hit[1] - center[1], hit[2] - center[2]] : [-ud[0], -ud[1], -ud[2]] + const k = raw[0] * dir[0] + raw[1] * dir[1] + raw[2] * dir[2] + const from = unit([raw[0] - dir[0] * k, raw[1] - dir[1] * k, raw[2] - dir[2] * k]) + const at: V3 = [center[0] + from[0] * radius, center[1] + from[1] * radius, center[2] + from[2] * radius] + const t = turnVector(from, dir, 0.05) + const s0 = this.toScreen(at) + const s1 = this.toScreen([center[0] + t[0] * radius, center[1] + t[1] * radius, center[2] + t[2] * radius]) + const sc = this.toScreen(center) + const tl = Math.hypot(s1[0] - s0[0], s1[1] - s0[1]) || 1 + return { center, radius, dir, from, angle: 0, edgeOn, x0: e.clientX, y0: e.clientY, tangent: [(s1[0] - s0[0]) / tl, (s1[1] - s0[1]) / tl], rpx: Math.max(20, Math.hypot(s0[0] - sc[0], s0[1] - sc[1])) } + } + + /** The turn of a ring drag for a pointer position, before snapping. */ + private ringAngle(g: RingDrag, ray: Raycaster, e: { clientX: number; clientY: number }): number { + if (g.edgeOn) return ((e.clientX - g.x0) * g.tangent[0] + (e.clientY - g.y0) * g.tangent[1]) / g.rpx + const { o, d } = this.bedRay(ray) + const p = rayPlane(o, d, g.center, g.dir) + if (!p) return g.angle + return unwrapAngle(g.angle, angleAround(g.from, [p[0] - g.center[0], p[1] - g.center[1], p[2] - g.center[2]], g.dir)) + } + + private updateRings(): void { + const t = this.rotateTarget() + if (!t) { + if (this.rotRings.visible) this.rotRings.show(false) + return + } + const l = this.rotDrag ?? this.ringLayout(t) + const axes = ringAxes(t.group.matrix.elements, this.rotSpace) + for (const id of ['x', 'y', 'z'] as const) this.rotRings.place(id, l.center, axes[id], l.radius) + this.rotRings.show(true) + } + + private ringUnder(ray: Raycaster): RingAxis | null { + const t = this.rotateTarget() + if (!t) return null + const { o, d } = this.bedRay(ray) + const l = this.ringLayout(t) + const axes = ringAxes(t.group.matrix.elements, this.rotSpace) + return pickRing(o, d, l.center, (['x', 'y', 'z'] as const).map((id) => ({ id, axis: axes[id] })), l.radius, 7 * this.mmPerPx(l.center)) + } + + private ringHover(ray: Raycaster): void { + const id = this.ringUnder(ray) + if (this.rotRings.setHover(id)) { + this.canvas.style.cursor = id ? 'pointer' : '' + this.invalidate() + } + } + + private rotDown(ray: Raycaster, e: PointerEvent): boolean { + const t = this.rotateTarget() + const axis = t ? this.ringUnder(ray) : null + if (!t || !axis) return false + const { o, d } = this.bedRay(ray) + const l = this.ringLayout(t) + const dir = ringAxes(t.group.matrix.elements, this.rotSpace)[axis] + this.rotDrag = { ...this.ringStart(o, d, l.center, dir, l.radius, e), entry: t, axis, start: t.group.matrix.toArray(), shown: 0, snapped: false } + this.rotRings.setActive(axis) + this.controls.enabled = false + this.showGizmoLabel(e.clientX, e.clientY, this.rotText(0, false)) + this.invalidate() + return true + } + + private rotText(rad: number, snapped: boolean): string { + const d = this.rotDrag + const deg = (rad * 180) / Math.PI + const axis = d ? d.axis.toUpperCase() : '' + return `${this.rotSpace === 'local' ? 'Object ' : ''}${axis} ${snapped ? Math.round(deg) : deg.toFixed(1)}°` + } + + private rotMove(ray: Raycaster, e: PointerEvent): void { + const d = this.rotDrag + if (!d) return + d.angle = this.ringAngle(d, ray, e) + const rb = this.controlsMap.gizmo.rotate + const snapped = this.modDown(rb.snapKey, { shift: e.shiftKey, ctrl: e.ctrlKey || e.metaKey, alt: e.altKey }) + const a = snapped ? snapAngle(d.angle, rb.snapStepDeg) : d.angle + d.shown = a + d.snapped = snapped + const m = rotateAbout(d.start, d.center, d.dir, a) + d.entry.group.matrix.fromArray(m) + d.entry.group.matrixWorldNeedsUpdate = true + this.rotRings.sweep(d.center, d.dir, d.from, a, d.radius) + this.setGizmoLabel(this.rotText(a, snapped)) + this.emit('rotate', { id: d.entry.id, axis: d.axis, space: this.rotSpace, angleDeg: (a * 180) / Math.PI, snapped, final: false }) + this.emit('transform', { id: d.entry.id, transform: m, final: false }) + this.invalidate() + } + + private rotEnd(cancel: boolean): void { + const d = this.rotDrag + if (!d) return + this.rotDrag = null + this.rotRings.setActive(null) + this.controls.enabled = true + this.hideGizmoLabel() + const g = d.entry.group + if (cancel) { + g.matrix.fromArray(d.start) + g.matrixWorldNeedsUpdate = true + } else { + // A turn about a tilted axis puts the model back on the bed, as Orca does after a rotation. + if (Math.abs(d.dir[2]) < 0.9999) { + g.updateMatrixWorld(true) + const b = new Box3().setFromObject(g, true).applyMatrix4(this.stage.bedMatrix().invert()) + if (!b.isEmpty()) g.matrix.elements[14] = (g.matrix.elements[14] ?? 0) - b.min.z + g.matrixWorldNeedsUpdate = true + } + this.emit('rotate', { id: d.entry.id, axis: d.axis, space: this.rotSpace, angleDeg: (d.shown * 180) / Math.PI, snapped: d.snapped, final: true }) + this.emit('transform', { id: d.entry.id, transform: g.matrix.toArray(), final: true }) + } + this.objectsMoved() + } + + setRotateSpace(space: RotateSpace): void { + if (space === this.rotSpace) return + this.rotSpace = space + this.invalidate() + } + + rotateHandles(): Partial> | null { + const t = this.rotateTarget() + if (!t) return null + const l = this.ringLayout(t) + const axes = ringAxes(t.group.matrix.elements, this.rotSpace) + const cam = this.camera.position.clone().applyMatrix4(this.stage.bedMatrix().invert()) + const toCam: V3 = [cam.x - l.center[0], cam.y - l.center[1], cam.z - l.center[2]] + const r = this.canvas.getBoundingClientRect() + const out: Partial> = {} + for (const id of ['x', 'y', 'z'] as const) { + // The point of each ring on the camera's side, where it is easiest to grab. + const n = axes[id] + const k = toCam[0] * n[0] + toCam[1] * n[1] + toCam[2] * n[2] + const f = unit([toCam[0] - n[0] * k, toCam[1] - n[1] * k, toCam[2] - n[2] * k]) + const s = this.toScreen([l.center[0] + f[0] * l.radius, l.center[1] + f[1] * l.radius, l.center[2] + f[2] * l.radius]) + out[id] = [s[0] - r.left, s[1] - r.top] + } + return out + } + + /** The value of a running drag next to the cursor. Placed once when the drag starts; a move only changes its text. */ + private showGizmoLabel(x: number, y: number, text: string): void { + if (typeof document === 'undefined') return + let el = this.gizmoLabel + if (!el) { + el = document.createElement('div') + el.className = 'vp-gizmo-label' + el.setAttribute('role', 'status') + // A small lifted surface: the host's tokens when it has them, a plain dark label when it does not. + el.style.cssText = + 'position:fixed;pointer-events:none;z-index:20;padding:2px 6px;border-radius:var(--r-sm,4px);' + + 'font:500 12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--fg,#f8f8f2);' + + 'background:color-mix(in srgb,var(--ink-3,#1e1f29) 90%,transparent);border:1px solid var(--line,transparent);' + + 'box-shadow:var(--shadow-float,none);-webkit-backdrop-filter:var(--lift-glass,none);backdrop-filter:var(--lift-glass,none)' + document.body.appendChild(el) + this.gizmoLabel = el + } + el.textContent = text + el.style.left = `${x + 16}px` + el.style.top = `${y - 30}px` + el.style.display = 'block' + } + + private setGizmoLabel(text: string): void { + if (this.gizmoLabel) this.gizmoLabel.textContent = text + } + + private hideGizmoLabel(): void { + if (this.gizmoLabel) this.gizmoLabel.style.display = 'none' + } + + // ---------- cut plane ---------- + + setCutPlane(cut: CutPlaneSpec | null): void { + const entry = cut ? this.objects.get(cut.objectId) : undefined + if (!cut || !entry) { + if (!this.cut && !this.cutPreview.entry) return + this.cutEnd(true) + this.cut = null + this.cutPreview.detach() + this.applyClip() + return + } + // A plane pushed back by the app while a drag runs would undo the drag; the release reports the result. + if (this.cutDrag) return + const keep = cut.keep ?? 'both' + const reattach = this.cut?.entry !== entry || this.cut.keep !== keep + this.cut = { entry, point: [...cut.point], normal: unit(cut.normal), keep, place: cut.placeConnectors === true } + if (reattach) this.syncCutPreview() + else this.cutPreview.setPlane(this.cut.point, this.cut.normal, this.stage.bedRoot.matrixWorld) + this.invalidate() + } + + private syncCutPreview(): void { + const c = this.cut + if (!c) return + this.cutPreview.attach(c.entry, c.keep) + this.stage.bedRoot.updateMatrixWorld(true) + this.cutPreview.setPlane(c.point, c.normal, this.stage.bedRoot.matrixWorld) + this.renderer.localClippingEnabled = true + } + + private updateCutGizmo(): void { + const c = this.mode === 'prepare' ? this.cut : null + this.cutGizmo.group.visible = !!c + this.cutRings.show(!!c) + if (!c) return + const r = this.ringLayout(c.entry).radius + this.cutGizmo.place(c.point, c.normal, r, this.mmPerPx(c.point)) + const g = this.cutDrag?.kind === 'tilt' ? this.cutDrag : null + const { u, v } = tiltAxes(g ? g.normal0 : c.normal) + this.cutRings.place('u', c.point, u, r * 0.8) + this.cutRings.place('v', c.point, v, r * 0.8) + } + + /** What of the cut gizmo a ray points at: a tilt ring, the grabber or the plane. */ + private cutUnder(ray: Raycaster): 'u' | 'v' | 'grabber' | 'plane' | null { + const c = this.mode === 'prepare' ? this.cut : null + if (!c) return null + this.updateCutGizmo() + this.cutGizmo.group.updateMatrixWorld(true) + if (ray.intersectObject(this.cutGizmo.grabber, false).length) return 'grabber' + const { o, d } = this.bedRay(ray) + const { u, v } = tiltAxes(c.normal) + const ring = pickRing(o, d, c.point, [{ id: 'u' as const, axis: u }, { id: 'v' as const, axis: v }], this.ringLayout(c.entry).radius * 0.8, 7 * this.mmPerPx(c.point)) + if (ring) return ring + return ray.intersectObject(this.cutGizmo.quad, false).length ? 'plane' : null + } + + private cutHover(ray: Raycaster): void { + const part = this.cutUnder(ray) + const a = this.cutRings.setHover(part === 'u' || part === 'v' ? part : null) + const b = this.cutGizmo.setHot(part === 'grabber' || part === 'plane' ? part : null) + if (a || b) { + this.canvas.style.cursor = part ? 'pointer' : '' + this.invalidate() + } + } + + private cutDown(ray: Raycaster, e: PointerEvent): boolean { + const c = this.cut + const part = c ? this.cutUnder(ray) : null + if (!c || !part) return false + const { o, d } = this.bedRay(ray) + // Placing connectors: a click on the plane says where, and the plane stays put. + if (c.place && part === 'plane') { + const n = c.normal + const den = n[0] * d[0] + n[1] * d[1] + n[2] * d[2] + if (Math.abs(den) < 1e-9) return true + const t = (n[0] * (c.point[0] - o[0]) + n[1] * (c.point[1] - o[1]) + n[2] * (c.point[2] - o[2])) / den + this.emit('cutconnector', { objectId: c.entry.id, point: [o[0] + d[0] * t, o[1] + d[1] * t, o[2] + d[2] * t] }) + return true + } + if (part === 'u' || part === 'v') { + const axis = tiltAxes(c.normal)[part] + this.cutDrag = { ...this.ringStart(o, d, c.point, axis, this.ringLayout(c.entry).radius * 0.8, e), kind: 'tilt', ring: part, normal0: c.normal } + this.cutRings.setActive(part) + this.showGizmoLabel(e.clientX, e.clientY, 'Tilt 0°') + } else { + const b = this.localBox(c.entry) + const extent = extentAlong(b.min.toArray() as V3, b.max.toArray() as V3, c.entry.group.matrix.elements, c.point, c.normal) + const px = this.mmPerPx(c.point) + // Along the normal by the ray's nearest point; when the normal points at the camera, by the cursor's height on screen. + const s0 = this.toScreen(c.point) + const s1 = this.toScreen([c.point[0] + c.normal[0] * 10, c.point[1] + c.normal[1] * 10, c.point[2] + c.normal[2] * 10]) + const visible = Math.hypot(s1[0] - s0[0], s1[1] - s0[1]) * px > 2.5 + const t0 = visible ? nearestOnLine(o, d, c.point, c.normal) : null + this.cutDrag = { kind: 'move', point0: c.point, extent, t0, mmPerPx: px, x0: e.clientX, y0: e.clientY } + this.cutGizmo.setHot(part) + this.showGizmoLabel(e.clientX, e.clientY, 'Moved 0.0 mm') + } + this.controls.enabled = false + this.invalidate() + return true + } + + private cutMove(ray: Raycaster, e: PointerEvent): void { + const c = this.cut + const g = this.cutDrag + if (!c || !g) return + const mods = { shift: e.shiftKey, ctrl: e.ctrlKey || e.metaKey, alt: e.altKey } + if (g.kind === 'move') { + let t: number + if (g.t0 !== null) { + const { o, d } = this.bedRay(ray) + const now = nearestOnLine(o, d, g.point0, c.normal) + if (now === null) return + t = now - g.t0 + } else t = (g.y0 - e.clientY) * g.mmPerPx + // The cut snaps with the rotate key for both moves and tilts, so one key works on every look. + const mv = this.controlsMap.gizmo.move + if (this.modDown(this.controlsMap.gizmo.rotate.snapKey, mods)) t = Math.round(t / mv.snapStepMm) * mv.snapStepMm + c.point = movePlane(g.point0, c.normal, t, g.extent) + const moved = (c.point[0] - g.point0[0]) * c.normal[0] + (c.point[1] - g.point0[1]) * c.normal[1] + (c.point[2] - g.point0[2]) * c.normal[2] + this.setGizmoLabel(`Moved ${moved.toFixed(1)} mm`) + } else { + g.angle = this.ringAngle(g, ray, e) + const rb = this.controlsMap.gizmo.rotate + const snapped = this.modDown(rb.snapKey, mods) + const a = snapped ? snapAngle(g.angle, rb.snapStepDeg) : g.angle + c.normal = unit(turnVector(g.normal0, g.dir, a)) + this.cutRings.sweep(g.center, g.dir, g.from, a, g.radius) + const deg = (a * 180) / Math.PI + this.setGizmoLabel(`Tilt ${snapped ? Math.round(deg) : deg.toFixed(1)}°`) + } + this.cutPreview.setPlane(c.point, c.normal, this.stage.bedRoot.matrixWorld) + this.emit('cutplane', { objectId: c.entry.id, point: [...c.point], normal: [...c.normal], final: false }) + this.invalidate() + } + + private cutEnd(cancel: boolean): void { + const g = this.cutDrag + const c = this.cut + if (!g) return + this.cutDrag = null + this.cutRings.setActive(null) + this.cutGizmo.setHot(null) + this.controls.enabled = true + this.hideGizmoLabel() + if (!c) return + if (cancel) { + if (g.kind === 'move') c.point = g.point0 + else c.normal = g.normal0 + this.cutPreview.setPlane(c.point, c.normal, this.stage.bedRoot.matrixWorld) + } else this.emit('cutplane', { objectId: c.entry.id, point: [...c.point], normal: [...c.normal], final: true }) + this.invalidate() + } + + cutHandles(): { grabber: [number, number]; u: [number, number]; v: [number, number] } | null { + const c = this.mode === 'prepare' ? this.cut : null + if (!c) return null + const r = this.ringLayout(c.entry).radius + const { u, v } = tiltAxes(c.normal) + const rc = this.canvas.getBoundingClientRect() + const at = (p: V3): [number, number] => { + const s = this.toScreen(p) + return [s[0] - rc.left, s[1] - rc.top] + } + const on = (a: V3, k: number): V3 => [c.point[0] + a[0] * k, c.point[1] + a[1] * k, c.point[2] + a[2] * k] + // Each ring's point a quarter turn from the other ring's axis, so the two lie apart on screen. + return { grabber: at(on(c.normal, r * 0.6)), u: at(on(v, r * 0.8)), v: at(on(u, r * 0.8)) } + } + + // ---------- push and pull ---------- + + setPush(push: PushSpec | null): void { + const before = this.push + this.push = push + if (!push) { + if (this.pushDrag) this.pushEnd(true) + this.pushView.setPrism(null, null) + this.pushView.group.visible = false + if (before) this.invalidate() + return + } + const f = push.face + if (push.prism !== before?.prism || f !== before?.face) this.pushView.setPrism(f ? (push.prism ?? null) : null, f ? { point: [...f.point], normal: [...f.normal] } : null) + // While a drag runs the view owns the distance; the app's copy may lag a frame behind. + const g = this.pushDrag + this.pushView.setDistance(g?.started && f && g.objectId === f.objectId ? g.d : push.distanceMm) + this.invalidate() + } + + /** Whether a bed point and normal lie on the picked push face. */ + private onPushFace(objectId: string, point: V3, normal: V3): boolean { + const sel = this.push?.face + if (!sel || sel.objectId !== objectId || dot3(sel.normal, normal) < 0.9999) return false + return Math.abs(dot3([point[0] - sel.point[0], point[1] - sel.point[1], point[2] - sel.point[2]], sel.normal)) < 0.01 + } + + /** A press on a flat face with the push tool: the drag starts once the cursor moves a few pixels, so a click still picks. */ + private pushDown(e: PointerEvent, p: PickHit | null): boolean { + const f = p ? this.faceFromHit(p) : null + if (!p || !f || this.mode !== 'prepare') return false + let point = f.pick.point as V3 + let normal = f.pick.normal as V3 + let d0 = 0 + const sel = this.push?.face + // The face already picked keeps its distance, so a second drag goes on from the first. + if (sel && this.onPushFace(p.entry.id, point, normal)) { + point = [...sel.point] + normal = [...sel.normal] + d0 = this.push?.distanceMm ?? 0 + } + const px = this.mmPerPx(point) + const s0 = this.toScreen(point) + const s1 = this.toScreen([point[0] + normal[0] * 10, point[1] + normal[1] * 10, point[2] + normal[2] * 10]) + // Along the normal by the ray's nearest point; when the normal points at the camera, by the cursor's height on screen. + const visible = Math.hypot(s1[0] - s0[0], s1[1] - s0[1]) * px > 2.5 + const { o, d } = this.bedRayAt(e) + const t0 = visible ? nearestOnLine(o, d, point, normal) : null + this.pushDrag = { started: false, objectId: p.entry.id, partIndex: p.part, triangle: p.face, point, normal, d0, d: d0, snapped: false, t0, mmPerPx: px, x0: e.clientX, y0: e.clientY } + this.controls.enabled = false + return true + } + + private pushMove(e: PointerEvent): void { + const g = this.pushDrag + if (!g) return + if (!g.started) { + if (Math.hypot(e.clientX - g.x0, e.clientY - g.y0) < 4) return + g.started = true + // A face other than the picked one: its prism comes from the app once it has picked that face. + if (!this.onPushFace(g.objectId, g.point, g.normal)) this.pushView.setPrism(null, null) + this.showGizmoLabel(e.clientX, e.clientY, pushLabel(g.d)) + this.emitPush('start', g) + } + let t: number + if (g.t0 !== null) { + const { o, d } = this.bedRayAt(e) + const now = nearestOnLine(o, d, g.point, g.normal) + if (now === null) return + t = now - g.t0 + } else t = (g.y0 - e.clientY) * g.mmPerPx + g.snapped = this.modDown(this.controlsMap.gizmo.rotate.snapKey, { shift: e.shiftKey, ctrl: e.ctrlKey || e.metaKey, alt: e.altKey }) + // The rotate snap key rounds to whole millimeters, as it rounds a turn to 15 degrees. + g.d = g.snapped ? Math.round(g.d0 + t) : Math.round((g.d0 + t) * 100) / 100 + this.pushView.setDistance(g.d) + this.setGizmoLabel(pushLabel(g.d)) + this.emitPush('move', g) + this.invalidate() + } + + /** Ends a push drag. Returns false when the press never became a drag, so the release counts as a click. */ + private pushEnd(cancel: boolean): boolean { + const g = this.pushDrag + if (!g) return false + this.pushDrag = null + this.controls.enabled = true + if (!g.started) return false + this.hideGizmoLabel() + if (cancel) { + g.d = g.d0 + this.pushView.setDistance(g.d0) + this.emitPush('cancel', g) + } else this.emitPush('end', g) + this.invalidate() + return true + } + + private emitPush(phase: PushEvent['phase'], g: NonNullable): void { + this.emit('push', { phase, objectId: g.objectId, partIndex: g.partIndex, triangle: g.triangle, point: [...g.point], normal: [...g.normal], distanceMm: g.d, snapped: g.snapped }) + } + + /** The ray under a client point, in bed coordinates. */ + private bedRayAt(e: { clientX: number; clientY: number }): { o: V3; d: V3 } { + const r = this.canvas.getBoundingClientRect() + this.tmpRay.setFromCamera(new Vector2(((e.clientX - r.left) / r.width) * 2 - 1, (-(e.clientY - r.top) / r.height) * 2 + 1), this.camera) + return this.bedRay(this.tmpRay) + } + + // ---------- sketch ---------- + + setSketch(scene: SketchScene | null): void { + if (!scene && !this.sketchLayer.scene) return + if (!scene) this.sketchDrag = null + this.sketchLayer.set(scene) + this.invalidate() + } + + setSketchCursor(cursor: SketchCursor | null): void { + if (!this.sketchLayer.scene) return + this.sketchLayer.cursor(cursor) + this.invalidate() + } + + private sketchOn(): boolean { + return this.sketchLayer.scene !== null && this.tool === 'probe' && this.mode === 'prepare' + } + + /** The cursor on the sketch plane, or null when the ray misses it. */ + private sketchAt(e: { clientX: number; clientY: number }): V2 | null { + const s = this.sketchLayer.scene + if (!s) return null + const { o, d } = this.bedRayAt(e) + return rayOnPlane(s.frame, o, d) + } + + private sketchEvent(kind: SketchEvent['kind'], e: { clientX: number; clientY: number; shiftKey: boolean; altKey: boolean }, handle?: number): void { + const s = this.sketchLayer.scene + const at = s ? this.sketchAt(e) : null + if (!s || !at) return + this.emit('sketch', { kind, at, ...(handle !== undefined ? { handle } : {}), mmPerPx: this.mmPerPx(fromPlane(s.frame, at)), screen: [e.clientX, e.clientY], shift: e.shiftKey, alt: e.altKey }) + } + + lookAtPlane(point: V3, normal: V3, radiusMm: number, opts: { animate?: boolean } = {}): void { + const m = this.stage.bedMatrix() + const target = new Vector3(...point).applyMatrix4(m) + const dir = new Vector3(...normal).transformDirection(m) + // Straight down the camera's up axis the orbit has no heading; a hair of tilt keeps the bed's front at the bottom. + if (Math.abs(dir.y) > 0.9995) dir.z += 0.0008 + dir.normalize() + const cam = this.camera + const fov = (cam.fov * Math.PI) / 180 + const fovH = 2 * Math.atan(Math.tan(fov / 2) * cam.aspect) + const dist = Math.max(radiusMm, 5) / Math.sin(Math.min(fov, fovH) / 2) + this.rig.preset = null + this.rig.go({ pos: target.clone().addScaledVector(dir, dist), target }, opts.animate ?? true, performance.now()) + this.invalidate() + } + + // ---------- kept dimensions ---------- + + setDimensions(marks: readonly DimensionMark[]): void { + if (this.dims.set(marks)) this.invalidate() + } + + setPaintSettings(settings: Partial): void { + this.painter.update(settings) + } + + getPaintSettings(): PaintSettings { + return { ...this.painter.settings, heightRangeMm: [...this.painter.settings.heightRangeMm] } + } + + setPaintColors(colors: readonly string[]): void { + this.painter.setColors(colors) + } + + getPaintData(objectId: string, partIndex: number, layer: PaintLayer): Record { + return this.painter.getData(objectId, partIndex, layer) + } + + setPaintData(objectId: string, partIndex: number, layer: PaintLayer, texts: Record | null): number[] { + return this.painter.setData(objectId, partIndex, layer, texts) + } + + applyPaintEdits(objectId: string, partIndex: number, layer: PaintLayer, edits: readonly { triangle: number; text: string | null }[]): void { + this.painter.applyEdits(objectId, partIndex, layer, edits) + } + + performGapFill(objectId: string): void { + const o = this.objects.get(objectId) + if (o) this.painter.performGapFill(o) + } + + paintHeightRange(objectId: string, range?: [number, number]): void { + const o = this.objects.get(objectId) + if (o) this.painter.paintHeightRange(o, range) + } + + /** + * Paint tool pointer down. The buttons and keys come from the preset's paint bindings: the left button paints the chosen + * state (an enforcer on the seam and support layers); the right button paints a blocker on those layers, and on the color layer + * either the second brush color or nothing (left to the camera), as the look says; the erase key erases. Returns true when the + * press belongs to the paint tool. + */ + private paintDown(e: PointerEvent, hit: PickHit): boolean { + const pb = this.controlsMap.gizmo.paint + const held = { shift: e.shiftKey, ctrl: e.ctrlKey || e.metaKey, alt: e.altKey } + // Any modifier other than the erase key belongs to the camera. + for (const k of ['shift', 'ctrl', 'alt'] as const) if (held[k] && k !== pb.eraseKey) return false + if (this.spaceDown) return false + const settings = this.painter.settings + if (settings.tool === 'gap') return false + const layer = settings.layer + let state: number | undefined + let button: 'left' | 'right' = 'left' + // Fuzzy skin has one painted state: the right button takes it off. + let rightErases = false + if (e.button === 2) { + button = 'right' + if (layer === 'fuzzy') rightErases = true + else if (layer !== 'color') state = 2 + else if (pb.colorRightButton === 'second-state') state = settings.secondState + else return false + } else if (e.button === 0) { + if (layer !== 'color') state = 1 + } else return false + const h: PaintHit = { entry: hit.entry, part: hit.part, point: hit.point, dir: hit.dir, face: hit.face } + this.painter.begin(hit.entry, hit.part, { erase: rightErases || (pb.eraseKey !== null && held[pb.eraseKey]), button, ...(state !== undefined ? { state } : {}) }) + this.painter.apply(h) + this.painting = { x: e.clientX, y: e.clientY, pointerId: e.pointerId } + this.controls.enabled = false + this.canvas.setPointerCapture(e.pointerId) + return true + } + + private paintMove(e: PointerEvent, pick: (p: { clientX: number; clientY: number }) => PickHit | null): void { + const s = this.painter.settings + const last = this.painting + if (!last) { + const h = pick(e) + this.painter.setCursor(h ? { entry: h.entry, part: h.part, point: h.point, dir: h.dir, face: h.face } : null, h?.dir ?? new Vector3(0, 0, -1)) + return + } + if (s.tool !== 'brush' && s.tool !== 'height' && s.tool !== 'triangle') return + // Walk from the last pointer position in small steps so a fast drag leaves no gaps. + const dist = Math.hypot(e.clientX - last.x, e.clientY - last.y) + const steps = Math.max(1, Math.ceil(dist / 6)) + for (let i = 1; i <= steps; i++) { + const x = last.x + ((e.clientX - last.x) * i) / steps + const y = last.y + ((e.clientY - last.y) * i) / steps + const h = pick({ clientX: x, clientY: y }) + if (h) { + this.painter.apply({ entry: h.entry, part: h.part, point: h.point, dir: h.dir, face: h.face }) + this.painter.setCursor({ entry: h.entry, part: h.part, point: h.point, dir: h.dir, face: h.face }, h.dir) + } + } + last.x = e.clientX + last.y = e.clientY + } + + pickFace(clientX: number, clientY: number): FacePick | null { + if (this.mode !== 'prepare') return null + const p = this.pickFn({ clientX, clientY }) + return p ? (this.faceFromHit(p)?.pick ?? null) : null + } + + private faceFromHit(p: PickHit): { pick: FacePick; triangles: number[] } | null { + const src = p.entry.parts[p.part]?.mesh.userData.source as { positions: Float32Array; indices: Uint32Array | Uint16Array } | undefined + if (!src || p.face < 0) return null + const patch = facePatch(src.positions, src.indices, p.face) + if (!patch) return null + const n = new Vector3(...patch.normal).applyMatrix3(new Matrix3().getNormalMatrix(p.entry.group.matrix)).normalize() + const c = this.bedBox(p.entry).getCenter(new Vector3()) + return { + pick: { objectId: p.entry.id, partIndex: p.part, normal: [n.x, n.y, n.z], centerBed: [c.x, c.y, c.z], areaMm2: patch.areaMm2, point: this.worldToBed(p.point) }, + triangles: patch.triangles, + } + } + + /** Highlights the face patch under the cursor (tool `face`). Null clears it. */ + private hoverFace(p: PickHit | null): void { + const f = p ? this.faceFromHit(p) : null + const key = f && p ? `${p.entry.id}:${p.part}:${Math.min(...f.triangles)}:${f.triangles.length}` : '' + if (key === this.faceKey) return + this.faceKey = key + if (this.faceOverlay) { + this.faceOverlay.removeFromParent() + this.faceOverlay.geometry.dispose() + this.faceOverlay = null + } + if (f && p) { + const mesh = p.entry.parts[p.part]?.mesh + const src = mesh?.userData.source as { positions: Float32Array; indices: Uint32Array | Uint16Array } | undefined + if (mesh && src) { + const pos = new Float32Array(f.triangles.length * 9) + f.triangles.forEach((t, k) => { + for (let v = 0; v < 3; v++) { + const vi = 3 * (src.indices[3 * t + v] ?? 0) + for (let a = 0; a < 3; a++) pos[9 * k + 3 * v + a] = src.positions[vi + a] ?? 0 + } + }) + const g = new BufferGeometry() + g.setAttribute('position', new BufferAttribute(pos, 3)) + const m = new MeshBasicMaterial({ color: new Color(this.faceColor), transparent: true, opacity: 0.6, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -8, toneMapped: false }) + const o = new Mesh(g, m) + o.raycast = () => {} + o.renderOrder = 3 + mesh.add(o) + this.faceOverlay = o + } + } + this.emit('facehover', f?.pick ?? null) + this.invalidate() + } + + // ---------- camera ---------- + + private framingBox(): Box3 { + const box = new Box3() + this.stage.scene.updateMatrixWorld(true) + const sel = this.selection.map((id) => this.objects.get(id)).filter((o): o is ObjectEntry => !!o) + if (this.mode === 'preview') { + const b = this.toolpaths.bounds() + if (b) { + const m = this.stage.bedRoot.matrixWorld + box.expandByPoint(new Vector3(...b.min).applyMatrix4(m)) + box.expandByPoint(new Vector3(...b.max).applyMatrix4(m)) + } + } + if (box.isEmpty()) { + const list = sel.length ? sel : [...this.objects.values()] + for (const o of list) box.expandByObject(o.group) + } + if (box.isEmpty()) box.setFromCenterAndSize(new Vector3(0, 20, 0), new Vector3(120, 40, 120)) + return box + } + + view(preset: ViewPreset, opts: { animate?: boolean } = {}): void { + const bed = this.stage.bed + const pose = this.rig.presetPose(preset, this.framingBox(), Math.max(bed.widthMm, bed.depthMm)) + this.rig.preset = preset + this.rig.go(pose, opts.animate ?? false, performance.now()) + this.invalidate() + } + + zoomToSelection(opts: { animate?: boolean } = {}): void { + const box = new Box3() + this.stage.scene.updateMatrixWorld(true) + const sel = this.selection.map((id) => this.objects.get(id)).filter((o): o is ObjectEntry => !!o) + for (const o of sel.length ? sel : [...this.objects.values()]) box.expandByObject(o.group) + if (box.isEmpty()) return this.view('bed', opts) + this.frameBox(box, opts.animate ?? true) + } + + /** + * Eases the camera so the bed point (x, y, z in mm) is at the center of the view, keeping the angle and zoom. + * With the system's reduced motion setting on, or `animate: false`, the camera jumps. + */ + focusBedPoint(x: number, y: number, z: number, opts: { animate?: boolean } = {}): void { + const world = new Vector3(x, y, z).applyMatrix4(this.stage.bedMatrix()) + this.rig.preset = null + this.rig.go(this.rig.centerOn(world), opts.animate ?? true, performance.now()) + this.invalidate() + } + + zoomToBed(opts: { animate?: boolean } = {}): void { + this.view('bed', { animate: opts.animate ?? true }) + } + + zoomBy(factor: number, opts: { animate?: boolean } = {}): void { + this.rig.preset = null + this.rig.go(this.rig.zoomed(factor), opts.animate ?? true, performance.now()) + this.invalidate() + } + + setProjection(projection: Projection): void { + if (projection === this.projection) return + const cam = this.camera + const t = this.controls.target + // Orthographic is a very long lens: a 1 degree field of view from far away, drawn identically to + // a true orthographic camera to within a pixel, so AO, shadows and picking keep one code path. + const from = cam.fov + const to = projection === 'orthographic' ? ORTHO_FOV : this.perspFov + if (projection === 'orthographic') this.perspFov = from + const k = Math.tan((from * Math.PI) / 360) / Math.tan((to * Math.PI) / 360) + cam.position.sub(t).multiplyScalar(k).add(t) + cam.fov = to + cam.updateProjectionMatrix() + this.controls.minDistance *= k + this.controls.maxDistance *= k + this.rig.move = null + this.projection = projection + this.controls.update() + this.cameraMoved = true + this.invalidate() + this.emit('camera', { preset: this.rig.preset }) + } + + getProjection(): Projection { + return this.projection + } + + toggleProjection(): Projection { + this.setProjection(this.projection === 'orthographic' ? 'perspective' : 'orthographic') + return this.projection + } + + /** Animates the camera to frame a world-space box, keeping the view direction. */ + private frameBox(box: Box3, animate = true): void { + const bed = this.stage.bed + this.rig.preset = null + this.rig.go(this.rig.presetPose('fit', box, Math.max(bed.widthMm, bed.depthMm)), animate, performance.now()) + this.invalidate() + } + + private worldToBed(v: Vector3): [number, number, number] { + const inv = this.stage.bedMatrix().invert() + const b = v.clone().applyMatrix4(inv) + return [b.x, b.y, b.z] + } + + setTheme(theme?: ViewportTheme): void { + const t = resolveTheme(theme) + this.theme = t + setSharedBandColors(t.heatRamp[0] ?? '#4f6bed', t.heatRamp[Math.floor((t.heatRamp.length - 1) / 2)] ?? '#f1fa8c', t.heatRamp[Math.floor((t.heatRamp.length - 1) * 0.75)] ?? '#ffb86c') + this.pipeline.setSceneColors(t.scene) + this.faceColor = t.scene.selection + this.guides.setColor(t.scene.selection) + this.brim.setColors(t.scene) + this.cutRings.setColor('v', t.scene.selection) + this.sketchLayer.setAccent(t.scene.selection) + this.stage.setSceneColors(t.scene) + setSharedSceneColors(t.scene) + this.mats.dispose() + this.toolpaths.setTheme(t) + this.strikes.setColors(t.scene.overhangRed, t.scene.overhangAmber) + this.toolpaths.setGantryColor(t.scene.overhangRed) + this.applyMaterials() + } + + setControls(controls: ControlsPresetId | ControlsMap): void { + const prev = this.controlsMap.id + this.controlsMap = typeof controls === 'string' ? CONTROL_PRESETS[controls] : controls + this.applyControls() + // A new look brings its own tool defaults (radius, band, angles); edits to one look's bindings keep the settings. + if (this.controlsMap.id !== prev) this.painter?.applyPreset() + this.painter?.update({}) + } + + getControls(): ControlsMap { + return this.controlsMap + } + + private applyControls(): void { + const m = this.controlsMap + const c = this.controls + c.rotateSpeed = m.rotateSpeed + c.zoomSpeed = m.wheel.invert ? -m.zoomSpeed : m.zoomSpeed + c.zoomToCursor = m.wheel.zoomToCursor + } + + /** + * Points OrbitControls at what the preset says the pressed button does. Runs + * before OrbitControls sees the event. Returns the resolved action. + */ + private routeDrag(e: PointerEvent, hit: () => Vector3 | null): DragAction { + if (e.pointerType === 'touch') return 'rotate' + const name = buttonName(e.button) + if (!name) return 'none' + const mods = modifiersOf(e, this.spaceDown) + const action = resolveDrag(this.controlsMap, name, mods, this.mode) + const code = orbitCodeFor(action, mods) as 0 | 1 | 2 + const key = name === 'left' ? 'LEFT' : name === 'middle' ? 'MIDDLE' : 'RIGHT' + this.controls.mouseButtons[key] = code + if (action === 'rotate') { + const pivot = this.controlsMap.freeCamera ? hit() : this.controlsMap.orbitAround === 'selection' ? this.selectionCenter() : null + if (pivot) this.rig.retargetToDepthOf(pivot) + } + return action + } + + private selectionCenter(): Vector3 | null { + const sel = [...this.objects.values()].filter((o) => this.selection.includes(o.id)) + if (!sel.length) return null + const box = new Box3() + for (const o of sel) { + o.group.updateMatrixWorld(true) + box.expandByObject(o.group) + } + return box.getCenter(new Vector3()) + } + + /** Trackpad two-finger scrolls become pan or rotate when the preset says so; pinch and mouse wheels stay with OrbitControls. */ + private routeWheel(e: WheelEvent): void { + // In the paint tool the wheel with the look's parameter key changes radius, band, fill angle or gap area, and with its clip key + // moves the clipping plane (Orca: Ctrl and Alt; PrusaSlicer: Alt and Ctrl). A pinch also arrives with ctrlKey, in small + // fractional steps, so only whole notches count. Alt wins over Ctrl, since Windows reports Right Alt as both. + if (this.tool === 'paint' && e.deltaMode === 0 ? Number.isInteger(e.deltaY) && Math.abs(e.deltaY) >= 40 : this.tool === 'paint') { + const pb = this.controlsMap.gizmo.paint + const key = e.altKey ? 'alt' : e.ctrlKey || e.metaKey ? 'ctrl' : e.shiftKey ? 'shift' : null + if (key && (key === pb.wheelParamKey || key === pb.wheelClipKey)) { + e.preventDefault() + e.stopImmediatePropagation() + const target = this.selection[0] ? this.objects.get(this.selection[0]) : [...this.objects.values()][0] + this.painter.wheel(e.deltaY > 0 ? -1 : 1, key === pb.wheelParamKey ? 'param' : 'clip', this.camera, target ?? null) + return + } + } + const action = resolveWheel(this.controlsMap, e) + if (action === 'zoom') return + e.preventDefault() + e.stopImmediatePropagation() + const h = this.canvas.clientHeight + if (action === 'pan') this.rig.panBy(-e.deltaX, -e.deltaY, h) + else this.rig.orbitBy(-e.deltaX, -e.deltaY, h, this.controlsMap.rotateSpeed) + this.cameraMoved = true + this.invalidate() + } + + getCamera(): CameraState { + const t = this.controls.target + const off = this.camera.position.clone().sub(t) + const d = off.length() + return { + target: this.worldToBed(t), + azimuthDeg: Math.atan2(off.x, off.z) / DEG, + elevationDeg: Math.asin(Math.max(-1, Math.min(1, off.y / Math.max(1e-6, d)))) / DEG, + distanceMm: d, + } + } + + setCamera(state: Partial, opts: { animate?: boolean } = {}): void { + const cur = this.getCamera() + const s = { ...cur, ...state } + const target = new Vector3(...s.target).applyMatrix4(this.stage.bedMatrix()) + const az = s.azimuthDeg * DEG + const el = Math.max(-89, Math.min(89, s.elevationDeg)) * DEG + const pos = target.clone().add(new Vector3(Math.sin(az) * Math.cos(el), Math.sin(el), Math.cos(az) * Math.cos(el)).multiplyScalar(s.distanceMm)) + this.rig.preset = null + this.rig.go({ pos, target }, opts.animate ?? false, performance.now()) + this.invalidate() + } + + // ---------- plate tools ---------- + + private bindPointer(): void { + const el = this.canvas + const ray = new Raycaster() + const ndc = new Vector2() + const plane = new Plane(new Vector3(0, 1, 0), 0) + const hit = new Vector3() + let down: { x: number; y: number } | null = null + const setRay = (e: { clientX: number; clientY: number }): void => { + const r = el.getBoundingClientRect() + ndc.set(((e.clientX - r.left) / r.width) * 2 - 1, (-(e.clientY - r.top) / r.height) * 2 + 1) + ray.setFromCamera(ndc, this.camera) + } + const pick = (e: { clientX: number; clientY: number }): PickHit | null => { + if (this.mode !== 'prepare') return null + setRay(e) + const meshes: Mesh[] = [] + for (const o of this.objects.values()) for (const p of o.parts) meshes.push(p.mesh) + const clipped = this.painter.clipPlane() !== null + // With the painter's clipping plane on, what lies in front of it cannot be hit, and the cut opens the model so the + // inside of its far wall can be reached: back faces count for the ray while the plane is on, as in Orca. + const sides = clipped ? meshes.map((m) => (m.material as Material).side) : [] + if (clipped) for (const m of meshes) (m.material as Material).side = DoubleSide + const hits = ray.intersectObjects(meshes, false) + if (clipped) meshes.forEach((m, i) => ((m.material as Material).side = sides[i] ?? FrontSide)) + const h = clipped ? hits.find((x) => !this.painter.isClipped(x.point)) : hits[0] + if (!h) return null + const id = h.object.userData.objectId as string + const entry = this.objects.get(id) + return entry ? { entry, part: (h.object.userData.partIndex as number) ?? 0, point: h.point, face: h.faceIndex ?? -1, dir: ray.ray.direction.clone() } : null + } + this.pickFn = pick + const bedHit = (e: PointerEvent): [number, number] | null => { + setRay(e) + if (!ray.ray.intersectPlane(plane, hit)) return null + const b = this.worldToBed(hit) + return [b[0], b[1]] + } + /** The ear under the cursor: by the model's hit point when the cursor is over the model, else by the bed under it. */ + const earAt = (e: PointerEvent, p: PickHit | null): { objectId: string; index: number } | null => { + let xy: [number, number] | null = null + if (p) { + const b = this.worldToBed(p.point) + xy = [b[0], b[1]] + } else xy = bedHit(e) + return xy ? this.brim.hit(xy[0], xy[1]) : null + } + /** Bed point under the cursor for a dragged ear: the model's hit, else the bed plane. */ + const earPoint = (e: PointerEvent): [number, number, number] | null => { + const h = pick(e) + if (h) return this.worldToBed(h.point) + const bh = bedHit(e) + return bh ? [bh[0], bh[1], 0] : null + } + // Sketch hovers and point drags go out at most once per frame, with the latest cursor. + type SketchPending = { kind: 'hover' | 'drag'; e: { clientX: number; clientY: number; shiftKey: boolean; altKey: boolean }; handle?: number } + let sketchPending: SketchPending | null = null + const flushSketch = (): void => { + const p = sketchPending + sketchPending = null + if (p && (p.kind === 'hover' ? this.sketchOn() : this.sketchDrag)) this.sketchEvent(p.kind, p.e, p.handle) + } + const queueSketch = (kind: SketchPending['kind'], e: PointerEvent, handle?: number): void => { + const first = sketchPending === null + sketchPending = { kind, e: { clientX: e.clientX, clientY: e.clientY, shiftKey: e.shiftKey, altKey: e.altKey }, ...(handle !== undefined ? { handle } : {}) } + if (first) requestAnimationFrame(flushSketch) + } + // Probe hovers go out at most once per frame, with the latest cursor, and only while a tool asks. + let probePending: { clientX: number; clientY: number } | null = null + let probeLast = '' + const flushProbe = (): void => { + const p = probePending + probePending = null + if (!p || !this.probeHover || this.tool !== 'probe') return + const h = pick(p) + const ev = h && h.face >= 0 ? { objectId: h.entry.id, partIndex: h.part, triangle: h.face, point: this.worldToBed(h.point) } : null + const key = ev ? `${ev.objectId}:${ev.partIndex}:${ev.point.map((v) => v.toFixed(3)).join(',')}` : '' + if (key === probeLast) return + probeLast = key + this.emit('probehover', ev) + } + const queueProbe = (e: PointerEvent): void => { + const first = probePending === null + probePending = { clientX: e.clientX, clientY: e.clientY } + if (first) requestAnimationFrame(flushProbe) + } + const onDown = (e: PointerEvent): void => { + const p0 = pick(e) + const action = this.routeDrag(e, () => p0?.point ?? null) + down = { x: e.clientX, y: e.clientY } + if (this.mode !== 'prepare') return + if (this.tool === 'brim') { + if (e.button === 2) { + // A right click on an ear removes it; anywhere else the button keeps its camera job. + const ear = earAt(e, p0) + if (ear) { + this.emit('brimremove', ear) + e.stopPropagation() + e.preventDefault() + } + return + } + if (e.button !== 0) return + const ear = earAt(e, p0) + if (e.shiftKey || e.altKey) { + // Shift draws a selection rectangle, Alt a deselect rectangle; a click without a drag toggles the ear under it. + this.brimDrag = { kind: 'rect', x0: e.clientX, y0: e.clientY, mode: e.altKey ? 'remove' : 'add', ear, moved: false } + } else if (ear) { + this.brimDrag = { kind: 'ear', objectId: ear.objectId, index: ear.index, moved: false } + } else return + this.controls.enabled = false + el.setPointerCapture(e.pointerId) + e.stopPropagation() + return + } + if (e.button !== 0 && !(e.button === 2 && this.tool === 'paint')) return + if (this.cut) { + setRay(e) + if (this.cutDown(ray, e)) { + el.setPointerCapture(e.pointerId) + e.stopPropagation() + } + // While a cut is set up the model stays put: a press off the gizmo is the camera's. + return + } + if (this.sketchOn()) { + // A press on a sketch point drags it; anywhere else the press is the camera's, and a click is the tool's. + const s = this.sketchLayer.scene! + const at = this.sketchAt(e) + const h = at ? this.sketchLayer.handleAt(at, 8 * this.mmPerPx(fromPlane(s.frame, at))) : -1 + if (h >= 0) { + this.sketchDrag = { handle: h } + this.controls.enabled = false + el.setPointerCapture(e.pointerId) + e.stopPropagation() + } + return + } + if (this.push && this.tool === 'probe') { + if (this.pushDown(e, p0)) { + el.setPointerCapture(e.pointerId) + e.stopPropagation() + } + return + } + if (this.tool === 'rotate') { + setRay(e) + if (this.rotDown(ray, e)) { + el.setPointerCapture(e.pointerId) + e.stopPropagation() + return + } + } + if (this.tool === 'scale') { + this.keys = { shift: e.shiftKey, ctrl: e.ctrlKey || e.metaKey, alt: e.altKey } + setRay(e) + if (this.scaleDown(ray)) { + el.setPointerCapture(e.pointerId) + e.stopPropagation() + } + return + } + const p = p0 + if (!p) return + if (this.tool === 'face' || this.tool === 'probe') return + if (this.tool === 'paint') { + if (this.paintDown(e, p)) e.stopPropagation() + return + } + const explicit = this.tool !== 'select' + // With the select tool the preset decides whether the press moves the model or orbits the view. + if (!explicit && !dragStartsOnModel(this.controlsMap, modifiersOf(e, this.spaceDown), action, this.selection.includes(p.entry.id))) return + this.selectIds([p.entry.id]) + const bh = bedHit(e) + if (!bh) return + const m = p.entry.group.matrix.toArray() + const box = this.bedBox(p.entry) + const tx = m[12] ?? 0 + const ty = m[13] ?? 0 + this.drag = { + entry: p.entry, + kind: this.tool === 'rotate' ? 'rotate' : 'move', + start: m, + offset: [tx - bh[0], ty - bh[1]], + rel: { min: [box.min.x - tx, box.min.y - ty], max: [box.max.x - tx, box.max.y - ty] }, + startX: e.clientX, + center: [(box.min.x + box.max.x) / 2, (box.min.y + box.max.y) / 2], + startYaw: Math.atan2(m[1] ?? 0, m[0] ?? 1), + } + this.controls.enabled = false + el.setPointerCapture(e.pointerId) + e.stopPropagation() + } + const onMove = (e: PointerEvent): void => { + if (this.brimDrag) { + const bd = this.brimDrag + const dist = down ? Math.hypot(e.clientX - down.x, e.clientY - down.y) : 0 + if (dist >= 4) bd.moved = true + if (bd.kind === 'ear' && bd.moved) { + const pt = earPoint(e) + if (pt) this.emit('brimmove', { objectId: bd.objectId, index: bd.index, point: pt, final: false }) + } else if (bd.kind === 'rect' && bd.moved) this.showBrimRect(bd.x0, bd.y0, e.clientX, e.clientY, bd.mode) + return + } + if (this.scaleDrag) { + setRay(e) + this.scaleMove(ray, e) + return + } + if (this.rotDrag) { + setRay(e) + this.rotMove(ray, e) + return + } + if (this.cutDrag) { + setRay(e) + this.cutMove(ray, e) + return + } + if (this.pushDrag) { + this.pushMove(e) + return + } + if (this.sketchDrag) { + queueSketch('drag', e, this.sketchDrag.handle) + return + } + if (e.buttons === 0 && this.mode === 'prepare' && !this.drag) { + if (this.sketchOn()) queueSketch('hover', e) + if (this.cut) { + setRay(e) + this.cutHover(ray) + } else if (this.tool === 'rotate') { + setRay(e) + this.ringHover(ray) + } + } + if (this.tool === 'scale' && e.buttons === 0) { + this.keys = { shift: e.shiftKey, ctrl: e.ctrlKey || e.metaKey, alt: e.altKey } + setRay(e) + this.updateGizmo() + if (this.gizmo.setHover(this.gizmo.hit(ray))) { + this.canvas.style.cursor = this.gizmo.hit(ray) ? 'pointer' : '' + this.updateGizmo() + this.invalidate() + } + } + const d = this.drag + if (!d) { + if ((this.tool === 'face' || (this.tool === 'probe' && this.probeFaces)) && this.mode === 'prepare' && e.buttons === 0) this.hoverFace(pick(e)) + if (this.tool === 'probe' && this.probeHover && this.mode === 'prepare' && e.buttons === 0) queueProbe(e) + if (this.tool === 'paint' && this.mode === 'prepare') this.paintMove(e, pick) + if (this.tool === 'brim' && this.mode === 'prepare' && e.buttons === 0) { + const h = pick(e) + const bp = h ? this.worldToBed(h.point) : null + if (this.brim.setHover(bp ? [bp[0], bp[1]] : null)) this.invalidate() + } + return + } + const bed = this.stage.bed + const m = new Matrix4().fromArray(d.start) + if (d.kind === 'move') { + const bh = bedHit(e) + if (!bh) return + let x = bh[0] + d.offset[0] + let y = bh[1] + d.offset[1] + const mv = this.controlsMap.gizmo.move + if (this.modDown(mv.snapKey, { shift: e.shiftKey, ctrl: e.ctrlKey || e.metaKey, alt: e.altKey })) { + // Orca and Bambu Studio round a move to a step while Shift is down; the model's own offset is kept. + x = Math.round(x / mv.snapStepMm) * mv.snapStepMm + y = Math.round(y / mv.snapStepMm) * mv.snapStepMm + } + x = Math.max(-d.rel.min[0], Math.min(bed.widthMm - d.rel.max[0], x)) + y = Math.max(-d.rel.min[1], Math.min(bed.depthMm - d.rel.max[1], y)) + m.elements[12] = x + m.elements[13] = y + } else { + let yaw = d.startYaw + (e.clientX - d.startX) * 0.012 + const rb = this.controlsMap.gizmo.rotate + if (this.modDown(rb.snapKey, { shift: e.shiftKey, ctrl: e.ctrlKey || e.metaKey, alt: e.altKey })) yaw = snapAngle(yaw, rb.snapStepDeg) + const [cx, cy] = d.center + const r = new Matrix4().makeTranslation(cx, cy, 0).multiply(new Matrix4().makeRotationZ(yaw - d.startYaw)).multiply(new Matrix4().makeTranslation(-cx, -cy, 0)) + m.premultiply(r) + } + d.entry.group.matrix.copy(m) + d.entry.group.matrixWorldNeedsUpdate = true + this.emit('transform', { id: d.entry.id, transform: m.toArray(), final: false }) + this.invalidate() + } + const onUp = (e: PointerEvent): void => { + if (this.brimDrag) { + const bd = this.brimDrag + this.brimDrag = null + this.controls.enabled = true + this.hideBrimRect() + down = null + if (bd.kind === 'ear') { + if (bd.moved) { + const pt = earPoint(e) + if (pt) this.emit('brimmove', { objectId: bd.objectId, index: bd.index, point: pt, final: true }) + } else this.emit('brimselect', { objectId: bd.objectId, indices: [bd.index], mode: 'set' }) + } else if (!bd.moved) { + if (bd.ear) { + const mode = bd.mode === 'remove' ? 'remove' : this.brim.isSelected(bd.ear.objectId, bd.ear.index) ? 'remove' : 'add' + this.emit('brimselect', { objectId: bd.ear.objectId, indices: [bd.ear.index], mode }) + } + } else this.brimRectSelect(bd.x0, bd.y0, e.clientX, e.clientY, bd.mode) + return + } + if (this.scaleDrag) { + this.scaleEnd(false) + down = null + return + } + if (this.rotDrag) { + this.rotEnd(false) + down = null + return + } + if (this.cutDrag) { + this.cutEnd(false) + down = null + return + } + if (this.sketchDrag) { + if (sketchPending?.kind === 'drag') flushSketch() + const h = this.sketchDrag.handle + this.sketchDrag = null + this.controls.enabled = true + this.sketchEvent('release', e, h) + down = null + return + } + // A press that never became a push drag is a click. + if (this.pushDrag && this.pushEnd(false)) { + down = null + return + } + if (this.painting) { + this.painting = null + this.controls.enabled = true + this.painter.end() + down = null + return + } + const d = this.drag + if (d) { + this.drag = null + this.controls.enabled = true + this.emit('transform', { id: d.entry.id, transform: d.entry.group.matrix.toArray(), final: true }) + this.objectsMoved() + down = null + return + } + if (!down) return + const moved = Math.hypot(e.clientX - down.x, e.clientY - down.y) + down = null + if (moved < 5 && this.sketchOn() && (e.button === 0 || e.button === 2)) { + // Sketch clicks belong to the sketch: nothing is picked or selected. + this.sketchEvent(e.button === 0 ? 'click' : 'context', e) + return + } + if (moved >= 5 || e.button !== 0) return + const p = pick(e) + this.emit('pick', { objectId: p?.entry.id ?? null, partIndex: p?.part ?? null, point: p ? this.worldToBed(p.point) : null, triangle: p && p.face >= 0 ? p.face : null, bed: bedHit(e), ...(e.shiftKey ? { shift: true } : {}) }) + if (this.mode === 'preview') { + // A click on a toolpath: which path it is, so the app can show the setting that made it. + setRay(e) + const toBed = this.stage.bedRoot.matrixWorld.clone().invert() + const o = ray.ray.origin.clone().applyMatrix4(toBed) + const d = ray.ray.direction.clone().transformDirection(toBed) + const r = el.getBoundingClientRect() + const hitPath = this.toolpaths.pick(o, d, (2 * Math.tan((this.camera.fov * Math.PI) / 360)) / Math.max(1, r.height)) + this.emit('pathpick', hitPath ? { ...hitPath, screen: [e.clientX - r.left, e.clientY - r.top] } : null) + return + } + // The probe tool only reports: the selection stays as it is. + if (this.tool === 'probe') return + if (this.tool === 'face' && p) { + const f = this.faceFromHit(p) + if (f) this.emit('facepick', f.pick) + } + if (this.tool === 'brim' && p && this.mode === 'prepare') { + const pt = this.worldToBed(p.point) + // A click on or near an ear never adds one; while ears are selected a click on the model only deselects them. + if (!this.brim.hit(pt[0], pt[1])) { + if (this.brim.anySelected) this.emit('brimselect', { objectId: p.entry.id, indices: [], mode: 'set' }) + else this.emit('brimadd', { objectId: p.entry.id, point: pt }) + } + return + } + if (this.mode === 'prepare') this.selectIds(p ? [p.entry.id] : []) + } + const onCancel = (): void => { + this.brimDrag = null + this.hideBrimRect() + this.scaleEnd(true) + this.rotEnd(true) + this.cutEnd(true) + this.pushEnd(true) + if (this.sketchDrag) { + this.sketchDrag = null + sketchPending = null + } + if (this.painting) { + this.painting = null + this.painter.end() + } + if (this.drag) { + this.drag.entry.group.matrix.fromArray(this.drag.start) + this.drag.entry.group.matrixWorldNeedsUpdate = true + this.drag = null + this.invalidate() + } + this.controls.enabled = true + down = null + } + const onWheel = (e: WheelEvent): void => { + if (this.tool === 'brim' && this.mode === 'prepare' && (e.ctrlKey || e.metaKey)) { + e.preventDefault() + e.stopPropagation() + this.emit('brimwheel', { delta: e.deltaY < 0 ? 1 : -1 }) + return + } + this.routeWheel(e) + } + const onKey = (e: KeyboardEvent): void => { + if (e.key === 'Escape') this.selectIds([]) + if (e.code === 'Space') { + this.spaceDown = true + e.preventDefault() + } + } + const onKeyUp = (e: KeyboardEvent): void => { + if (e.code === 'Space') this.spaceDown = false + } + const onBlur = (): void => { + this.spaceDown = false + } + const onDouble = (e: MouseEvent): void => { + if (e.button !== 0 || this.mode !== 'prepare') return + const dc = this.controlsMap.doubleClick + const p = pick(e as PointerEvent) + if (p && dc.object === 'zoom') { + p.entry.group.updateMatrixWorld(true) + this.frameBox(new Box3().setFromObject(p.entry.group)) + } else if (!p && dc.empty === 'fit') this.view('fit', { animate: true }) + } + el.addEventListener('pointerdown', onDown, true) + el.addEventListener('wheel', onWheel, { capture: true, passive: false }) + el.addEventListener('pointermove', onMove) + el.addEventListener('pointerup', onUp) + el.addEventListener('pointercancel', onCancel) + el.addEventListener('keydown', onKey) + el.addEventListener('keyup', onKeyUp) + el.addEventListener('blur', onBlur) + el.addEventListener('dblclick', onDouble) + this.cleanups.push(() => { + el.removeEventListener('pointerdown', onDown, true) + el.removeEventListener('wheel', onWheel, true) + el.removeEventListener('pointermove', onMove) + el.removeEventListener('pointerup', onUp) + el.removeEventListener('pointercancel', onCancel) + el.removeEventListener('keydown', onKey) + el.removeEventListener('keyup', onKeyUp) + el.removeEventListener('blur', onBlur) + el.removeEventListener('dblclick', onDouble) + }) + } + + private selectIds(ids: string[]): void { + const same = ids.length === this.selection.length && ids.every((id, i) => id === this.selection[i]) + this.selection = ids + this.invalidate() + if (!same) this.emit('select', { ids: [...ids] }) + } + + /** Object bounds in bed coordinates (x, y in mm; z up). */ + private bedBox(o: ObjectEntry): Box3 { + const group: Group = o.group + group.updateMatrixWorld(true) + const b = new Box3().setFromObject(group) + return b.applyMatrix4(this.stage.bedMatrix().invert()) + } + + arrange(opts: { animate?: boolean; gapMm?: number } = {}): Record { + const gap = opts.gapMm ?? 14 + const bed = this.stage.bed + const usable = bed.widthMm - 20 + const items = [...this.objects.values()].map((o) => { + const b = this.bedBox(o) + return { o, w: b.max.x - b.min.x, d: b.max.y - b.min.y, cx: (b.min.x + b.max.x) / 2, cy: (b.min.y + b.max.y) / 2 } + }) + items.sort((a, b) => b.d - a.d) + const rows: { items: typeof items; w: number; d: number }[] = [] + for (const it of items) { + let row = rows.find((r) => r.w + gap + it.w <= usable) + if (!row) { + row = { items: [], w: -gap, d: 0 } + rows.push(row) + } + row.w += gap + it.w + row.d = Math.max(row.d, it.d) + row.items.push(it) + } + const totalD = rows.reduce((a, r) => a + r.d, 0) + gap * Math.max(0, rows.length - 1) + if (totalD > bed.depthMm - 20) this.emit('degrade', { message: 'These models do not all fit on one plate. Scale one down or remove one.' }) + const out: Record = {} + const moves: { o: ObjectEntry; from: Matrix4; dx: number; dy: number }[] = [] + let y = bed.depthMm / 2 + totalD / 2 + for (const r of rows) { + let x = bed.widthMm / 2 - r.w / 2 + for (const it of r.items) { + const tx = x + it.w / 2 + const ty = y - r.d / 2 + const from = it.o.group.matrix.clone() + const m = from.clone() + m.elements[12] = (m.elements[12] ?? 0) + (tx - it.cx) + m.elements[13] = (m.elements[13] ?? 0) + (ty - it.cy) + out[it.o.id] = m.toArray() + moves.push({ o: it.o, from, dx: tx - it.cx, dy: ty - it.cy }) + x += it.w + gap + } + y -= r.d + gap + } + const reduce = reducedMotion() + const finish = (): void => { + for (const mv of moves) this.emit('transform', { id: mv.o.id, transform: mv.o.group.matrix.toArray(), final: true }) + this.objectsMoved() + } + if (!opts.animate || reduce) { + for (const mv of moves) { + mv.o.group.matrix.fromArray(out[mv.o.id] ?? mv.from.toArray()) + mv.o.group.matrixWorldNeedsUpdate = true + } + finish() + return out + } + let t0 = -1 + this.arrangeAnim = (now: number): boolean => { + if (t0 < 0) t0 = now + const k = Math.min(1, (now - t0) / 420) + const e = 1 - Math.pow(1 - k, 3) + for (const mv of moves) { + const m = mv.from.clone() + m.elements[12] = (m.elements[12] ?? 0) + mv.dx * e + m.elements[13] = (m.elements[13] ?? 0) + mv.dy * e + mv.o.group.matrix.copy(m) + mv.o.group.matrixWorldNeedsUpdate = true + } + if (k >= 1) { + this.arrangeAnim = null + finish() + return false + } + return true + } + this.invalidate() + return out + } + + // ---------- preview ---------- + + setPreview(buffers: PreviewBuffers | null): void { + this.previewGen++ + this.previewSetAt = performance.now() + this.firstFrameMs = null + this.toolpaths.set(buffers) + this.shadowDirty = true + this.invalidate() + } + + setPreviewStale(stale: boolean): void { + if (this.toolpaths.setStale(stale)) this.invalidate() + } + + setPreviewOrigin(x: number, y: number): void { + const root = this.stage.previewRoot + if (root.position.x === -x && root.position.y === -y) return + root.position.set(-x, -y, 0) + this.shadowDirty = true + this.invalidate() + } + + setPreviewGhost(buffers: PreviewBuffers | null): void { + if (!buffers) { + if (!this.ghost) return + this.ghost.root.removeFromParent() + this.ghost.dispose() + this.ghost = null + } else { + if (!this.ghost) { + this.ghost = new Toolpaths(true) + this.stage.previewRoot.add(this.ghost.root) + } + this.ghost.set(buffers) + this.ghost.setRange(this.toolpaths.lo, this.toolpaths.hi, null) + } + this.invalidate() + } + + /** Turns the bed outline orange (an object is off the bed). */ + setBedAlert(on: boolean): void { + this.stage.setBedAlert(on) + this.invalidate() + } + + setGround(on: boolean): void { + this.stage.setGround(on) + this.invalidate() + } + + /** Brightens one dual nozzle zone (by id); null resets. */ + setExcludedAreas(areas: readonly (readonly [number, number])[][]): void { + this.stage.setExcludedAreas(areas) + this.invalidate() + } + + setZoneHighlight(id: string | null): void { + this.stage.setZoneHighlight(id) + this.invalidate() + } + + setLayerRange(lo: number, hi: number): void { + this.toolpaths.setRange(lo, hi, this.toolpaths.moveCut) + this.ghost?.setRange(lo, hi, null) + this.scrubbed = true + this.shadowDirty = true + this.invalidate() + } + + setMoveCut(moves: number | null): void { + this.toolpaths.setRange(this.toolpaths.lo, this.toolpaths.hi, moves) + this.scrubbed = true + this.shadowDirty = true + this.invalidate() + } + + setColorMode(mode: ColorMode): void { + this.toolpaths.setColorMode(mode) + this.invalidate() + } + + setToolColors(colors: string[]): void { + this.toolpaths.setToolColors(colors) + this.invalidate() + } + + setToolFinishes(finishes: ToolpathFinish[]): void { + this.toolpaths.setToolFinishes(finishes) + this.invalidate() + } + + setPlateStyle(style: PlateStyle): void { + this.stage.setPlateStyle(style) + this.shadowDirty = true + this.invalidate() + } + + /** The printer family's toolhead, for a printer with one nozzle (`headFor` maps a profile id to it). */ + setHeadModel(model: HeadModel): void { + this.toolpaths.setHeadModel(model) + this.shadowDirty = true + this.invalidate() + } + + /** The printer's tool changer (toolhead, rack or dock to draw); null draws the printer's own single head. */ + setToolChanger(spec: ToolChangerSpec | null): void { + this.toolpaths.setToolChanger(spec) + this.shadowDirty = true + this.invalidate() + } + + /** Plays the tool change before `segment` at `seconds` into it; null returns the head to the current move. */ + setToolChange(c: { segment: number; seconds: number; fixed: number } | null): void { + this.toolpaths.setToolChange(c) + this.scrubbed = true + this.shadowDirty = true + this.invalidate() + } + + /** Preview's "Show toolhead": false hides the moving head and its carriage; the rack, dock, chute and wiper stay. */ + setShowToolhead(on: boolean): void { + this.toolpaths.setShowToolhead(on) + this.shadowDirty = true + this.invalidate() + } + + /** + * Preview's "Follow the nozzle": while the head moves, the orbit target and the camera shift with it by the same + * amount, so the view keeps its angle and zoom and the nozzle stays where it was on screen. + */ + setFollowNozzle(on: boolean): void { + this.toolpaths.onHead = on + ? (x, y, z) => { + const w = this.toolpaths.root.localToWorld(new Vector3(x, y, z)) + const d = w.sub(this.controls.target) + if (d.lengthSq() < 1e-10) return + this.controls.target.add(d) + this.camera.position.add(d) + this.invalidate() + } + : null + } + + /** Each tool change's purge at the chute (from the G-code), drawn while the change plays; null for none. */ + setPurges(plans: readonly PurgePlan[] | null): void { + this.toolpaths.setPurges(plans) + this.invalidate() + } + + setTravels(on: boolean): void { + this.toolpaths.setTravels(on) + this.invalidate() + } + + setPreviewExtras(extras: PreviewExtras | null): void { + this.toolpaths.setExtras(extras) + this.invalidate() + } + + previewExtras(): { fan: boolean; temperature: boolean } & Record { + return { ...this.toolpaths.hasExtras(), ...this.toolpaths.hasMarkers() } + } + + setMarkers(opts: Partial>): void { + this.toolpaths.setMarkers(opts) + this.invalidate() + } + + setGcodeMarkers(data: Partial>): void { + this.toolpaths.setGcodeMarkers(data) + this.invalidate() + } + + setGantry(spec: GantrySpec | null, hits: readonly GantryHit[] | null): void { + this.toolpaths.setGantry(spec) + this.toolpaths.setGantryHits(hits) + } + + setStrikes(marks: readonly StrikeMark[] | null): void { + this.strikes.set(marks) + this.invalidate() + } + + previewRanges(): PreviewRanges { + return this.toolpaths.ranges() + } + + previewLegend(): LegendFeature[] { + const b = this.toolpaths.buffers + if (!b) return [] + if (this.summaryFor !== b) { + this.summary = summarizePreview(b) + this.summaryFor = b + } + const s = this.summary + if (!s) return [] + return FEATURE_COLORS.filter((f) => (s.featureMm[f.id] ?? 0) > 0).map((f) => ({ + id: f.id, + label: f.label, + color: this.theme.featureColors[FEATURE_COLORS.indexOf(f)] ?? f.color, + timeS: s.featureTimeS[f.id] ?? 0, + lengthMm: s.featureMm[f.id] ?? 0, + visible: ((this.featureMask >>> f.id) & 1) === 1, + })) + } + + setFeatureVisible(id: number, visible: boolean): void { + this.featureMask = visible ? this.featureMask | (1 << id) : this.featureMask & ~(1 << id) + this.toolpaths.setFeatureMask(this.featureMask) + this.invalidate() + } + + setVisibleFeatures(ids: readonly number[]): void { + this.featureMask = ids.reduce((m, id) => m | (1 << id), 0) + this.toolpaths.setFeatureMask(this.featureMask) + this.invalidate() + } + + currentMove(): { segment: number; layer: number; gcodeLine: number } | null { + return this.toolpaths.currentMove() + } + + layerMoveCount(layer: number): number { + const b = this.toolpaths.buffers + if (!b || layer < 0 || layer >= b.layerCount) return 0 + return (b.layerStart[layer + 1] ?? 0) - (b.layerStart[layer] ?? 0) + } + + // ---------- stats ---------- + + stats(): ViewportStats { + const frameMs = this.frameMs.values() + const renderMs = this.renderMs.values() + const costMs = this.costMs.values() + const sorted = (costMs.length ? costMs : frameMs.length ? frameMs : renderMs).slice().sort((a, b) => a - b) + const info = this.renderer.info + const size = this.pipeline.size + return { + backend: 'webgl2', + gpu: this.gpu, + quality: this.quality, + pixelRatio: this.pr, + width: size.width, + height: size.height, + frames: this.frames, + frameMs, + renderMs, + costMs, + p50: percentile(sorted, 0.5), + p95: percentile(sorted, 0.95), + firstFrameMs: this.firstFrameMs, + firstDrawMs: this.firstFrame.ms, + drawCalls: info.render.calls, + triangles: info.render.triangles, + segments: this.toolpaths.segmentCount, + aoOn: this.aoOn, + motionScale: this.pipeline.motionScale, + } + } + + resetStats(): void { + this.frameMs.clear() + this.renderMs.clear() + this.costMs.clear() + this.lastRenderT = 0 + } + + /** Turns the frame probe on or off (see probe.ts). Turning it on starts a fresh measurement. */ + setProbe(on: boolean): void { + if (on && !this.probe && !this.disposed) this.probe = new FrameProbe(this.renderer) + else if (!on && this.probe) { + this.probe.dispose() + this.probe = null + } + this.probe?.reset() + } + + /** What the frame probe measured since it started or was reset; null while it is off. */ + probeStats(): ProbeStats | null { + return this.probe?.stats() ?? null + } + + resetProbe(): void { + this.probe?.reset() + } + + setGpuTiming(on: boolean): void { + this.gpuTiming = on + } + + dispose(): void { + if (this.disposed) return + this.disposed = true + this.strikes.dispose() + this.painter.dispose() + this.gizmo.dispose() + this.cutPreview.detach() + this.rotRings.dispose() + this.cutRings.dispose() + this.cutGizmo.dispose() + this.pushView.dispose() + this.edgeView.dispose() + this.sketchLayer.dispose() + this.dims.dispose() + this.gizmoLabel?.remove() + this.probe?.dispose() + this.probe = null + if (this.raf) cancelAnimationFrame(this.raf) + this.raf = 0 + for (const c of this.cleanups) c() + this.ro?.disconnect() + this.io?.disconnect() + this.controls.dispose() + for (const o of this.objects.values()) disposeObject(o) + this.objects.clear() + this.ghost?.dispose() + this.toolpaths.dispose() + this.brim.dispose() + this.brimRectEl?.remove() + this.mats.dispose() + this.pipeline.dispose() + this.stage.dispose() + this.listeners.clear() + this.renderer.dispose() + this.renderer.forceContextLoss() + } + + /** Canvas size in CSS pixels, for overlays. */ + get size(): { width: number; height: number } { + return { width: this.width, height: this.height } + } +} diff --git a/docs/testing/project-viewer/README.md b/docs/testing/project-viewer/README.md new file mode 100644 index 00000000..d3feba8c --- /dev/null +++ b/docs/testing/project-viewer/README.md @@ -0,0 +1,346 @@ +# Read-only project view (PR 3b) + +Studio shows a 3D, read-only view of the project the user opened, drawn from the engine's `scene/1` contract +(`docs/testing/scene-contract/README.md`). It appears on the project page in Simple mode (`DesignInsights`) and in Advanced +mode (`LiveWorkspace`), after the Doctor has finished, and loads its code only when first shown. + +It shows the objects, the bed, the engine's placement and size notes, a list of what the view cannot tell you, camera +buttons, and a slope view. It never edits, moves, cuts, paints or saves anything. + +**Where the numbers are.** Every measurement in this folder is in `results.json`, written by `harness/collect-results.mjs` +from one run, and the tables in "Measurements" below are generated from it by `harness/make-readme-tables.mjs`; no figure in +this README is typed by hand. `results.json` records the commit the run was taken on. A run is evidence about a commit only +when that line says the tree was clean outside this folder. `harness/README.md` says how to repeat it. + +## What was and was not run + +| Check | Status | +|---|---| +| Type check, unit tests, build | run by `collect-results.mjs` (see Measurements) | +| Real-browser run: dev server, real engine, real WebGL, light and dark, wide and narrow | run by the harness | +| Production build served with the app's real Tauri CSP | run by the harness | +| The scene client against the **real engine** (sessions, credentials, ordering) | run by `harness/real-engine.mjs` on a working tree that contains the reviewed engine: see "Against the real engine" below for exactly what was and was not covered. | +| **Packaged Windows app (Tauri, real WebView2)** | **Run, on the CI-built installer of commit `1836fd0`:** 10 of 10 steps passed in the acceptance-identity copy on a clean local account, with the production-state tripwire clean. Details and limits: [packaged-windows/README.md](packaged-windows/README.md). It is not the final head (later commits change one message string, tests, docs and these measurements) and not the production-identity installer. | +| **Packaged Linux app under real WebKitGTK** | **Run, on the CI-built `.deb` of commit `1836fd0`:** 15 of 15 checks on each of two example projects, graphics-enabled WSLg session, no Chromium. **WebGL ran on Mesa software rendering (llvmpipe), so GPU-backed WebGL in WebKitGTK is not proven.** Both example projects contain one object. Mouse wheel over the canvas also scrolls the page (not judged here). Details: [webkitgtk/README.md](webkitgtk/README.md). | +| macOS, screen reader, weak or GPU-specific rendering, a real printer | not run (a printer is never used) | + +Do not read the browser results as proof for the packaged apps. They show the code works in a Chromium browser with +hardware WebGL. + +## How read-only is enforced + +The vendored SlicerX viewport (`desktop/src/vendor/slicerx/UPDATING.md`) still contains its editing code (move, rotate, +scale, paint, cut, sketch), because its entry class imports and constructs it. That code is **in the bundle**; it was not +removed. Studio cannot reach it. The boundary is structural, in three places, and a test pins each: + +* **`defaultViewport.ts`** is the only file that imports the viewport's factory, and the only place that touches its tool: + it calls `setTool("probe")` once (a click only reports what is under the cursor), keeps the viewport inside a closure, and + hands out an inspection port (`InspectionPort`, defined in `readOnlyViewport.ts`) that has no `setTool`, no generic `on` and + no editing member: only the named pass-through calls pinned in the guard test and four named subscriptions (pick, select, + error, degrade). If anything after creation throws, it disposes the half-built viewport. `defaultViewport.test.ts` proves, + against a stand-in viewport, that the tool is set once and first, that the adapter hands out no `setTool` or `on`, and that a + throw from `setTool`, `setTheme` or any of the four subscriptions disposes the viewport. +* **`readOnlyViewport.ts`** turns the port into the facade (`ReadOnlyViewport`: show, select, camera preset, slope view, + theme, onPick, onSelect, onTrouble, dispose). Type-level test: editing calls, `setTool`, a generic `on`, a raw handle and an + unknown camera preset do not type-check on the facade, and `setTool`, `on` and `setCutPlane` do not type-check on the port + (`@ts-expect-error` lines in `readOnlyViewport.test.ts`, enforced by `tsc`). +* **`readOnly.guard.test.ts`** scans every non-test, non-vendor file in `src/` (not just the view's folder). It fails when any + file other than those named below mentions the vendor tree in any quoted string (import, re-export, dynamic `import()`, + `?raw`, alias, relative path), when a dynamic `import()` has a computed argument, when any editing member name (`setTool`, + `setCutPlane`, `setTransforms`, `setPaint*`, ...) appears in any spelling that keeps the name (call, bracket access, + destructuring, alias, string), when `.arrange(` is used, or when `createViewport` is named outside the adapter (inside it, + only its import and one call expression are allowed: a re-export, alias or second call fails). Allowed: `readOnlyViewport.ts` + (a type import of the vendor entry), `defaultViewport.ts` (the value import of it, with exactly one `setTool("probe")`) and + `credits.ts` (the vendored NOTICE and LICENSE-APACHE as plain text). **Mutation tests** feed the scan a bypass in + `components/project-scene/sub/`, in `routes/`, in `lib/`, a computed and a literal dynamic import, a re-export, bracket + access, destructuring, an alias, a value import in the facade, a second or different `setTool`, extra imports in + `credits.ts`, and a re-export, alias or second call of `createViewport` in the adapter; each must fail, and does. Real bypass + files were also dropped into `project-scene/sub/` and `routes/` on disk; the guard was run, failed naming both files, and the + files were deleted. Limit: a source scan cannot see a member name built at run time ("set" + "Tool"); code review covers that. +* **`vendor.integrity.test.ts`** checks the vendored tree against its own record in `UPDATING.md`: every verbatim file is + byte-for-byte upstream (git blob id), each of the seven patched files carries the modification notice after the upstream + header and, with the notice removed and the import path put back, is byte-for-byte upstream, no other file has a notice, and + every sha256 in the table is current. +* UI test: no button in the panel is named move, rotate, scale, paint, cut and so on, and the panel has no input. +* Real input: on the real viewport set up the way the adapter sets it up (create, `setTool("probe")`; the adapter itself is + covered by the unit tests above), a script sends left, right and middle drags with no modifier and with Shift, Control, Alt, + Shift+Control and Shift+Alt, Space+drag, double click, wheel (also with each modifier) and a fixed list of key presses + (Delete, Backspace, R, S, M, P, C, X, B, F, Enter, arrows, Control+Z/Y/C/V/A, Escape). The object centers, read through the + viewport's own hit test before and after, must be identical. **Control run:** the same input on the same viewport with its + upstream default tool does move an object, so the check is able to detect movement and is not vacuous. The control's final + position differs a little from run to run because the drag is timed by real input. Results are in Measurements. +* Original files: every fixture is hashed before and after each run (including a large project) and must be unchanged. The + engine only reads the file (backend tests in the PR 3a folder compare bytes and modification time as well). + +## What the view claims, and does not + +* Highlighting comes only from engine findings keyed to node ids. A finding is object-level only when it names exactly one + target and that target is a known node. A finding with several targets (even in one object), an unknown id, or any finding + when the scene cannot prove placement, stays a project-level note and highlights and selects nothing. +* Highlighting is off, with the reason in words, when a source unit is not millimeters, the project has more than one plate, + any object's placement is unknown (STL files, models with no build item), or the bed outline fell back. Screenshots: + `wide-dark-inch`, `wide-dark-two-plates`, `wide-dark-stl`. +* Position claims say "Placement". The word "fits" is never produced (a test scans every finding and limitation string, and + also for "ready", "guarantee", "100%", "safe", "best", "clean"). The slope label is exactly + "Geometric slope visualization - review supports in Orca." +* The physical bed edge and the policy margin are told apart: the engine measures past the margin line, so the note says how + far past the bed edge, or that the object is inside the bed but within the margin. The margin is also drawn as a faint inner + outline, and the bed outline turns orange only for a placement note. The legend appears only when highlighting is on, and + takes the margin from the scene. +* The view is advisory. It does not say anything prints, and its footer points to Snapmaker Orca for placement and supports. +* A mirrored instance (negative-determinant world matrix) keeps its triangle order. An earlier version also reversed the + triangles, which turned the faces inward a second time: a downward ray through a mirrored cube hit the bottom face instead + of the top. `sceneModel.test.ts` builds a real reflection matrix, puts it on a three.js mesh and raycasts it: the top face is + hit, and a control with the triangles reversed hits the bottom, so the test can fail. + +## Talking to the engine + +`scene.ts` starts a job, follows it, and returns the scene. What it relies on, and what it does not: + +* **Ordering of overlapping starts is the engine's job, within one session.** The client opens ONE session lazily per app run + (`POST /scene/session`, answered with `client_id` and a time to live) and opens another after `SESSION_EXPIRED`. Every start + carries that `client_id` and a `seq` that is strictly increasing within the session, starting at 1. The agreed engine rules: + a start whose `seq` is not higher than the highest seen is refused (`STALE_START`; this includes an exact retry of a start + already processed, so every retry uses a fresh request id and the next `seq`); a start for a cancelled request or `seq` is + refused (`CANCELLED_BEFORE_START`); an unknown or idle-expired session is refused (`SESSION_EXPIRED`); more sessions than the + engine allows is `503 SESSION_LIMIT`. `/scene/cancel` takes `{client_id, request_id, seq}` and keeps that `seq` dead for the + session; on an expired session it answers `SESSION_EXPIRED`, which the client ignores (best effort). +* The client sends that cancel immediately when a view is abandoned (unmount, path change, StrictMode's first mount), whether + or not the start has been answered or even delivered. It is best effort, bounded, never awaited and never holds up the next + start. A load abandoned before it learned the session, or before it took its `seq`, sent nothing and has nothing to cancel. +* An abandoned start that reaches the engine after a newer one therefore cannot cancel or replace it, and one that reaches the + engine after its session expired meets an unknown session: its answer is dropped and it triggers nothing. This is proved + against a stand-in engine that implements the rules above, with every delivery order controlled by hand (no timers): + `scene.test.ts`, "sessions" and "job credentials". The real engine is then driven through the cases it can be driven through, below; that run does not repeat every ordering in these tests, and its limits are listed there. +* **Job credentials.** `/scene/status` and `/scene/result` carry the session's `client_id` along with the `job_id`; a job that + belongs to a session is visible only to the same session. A foreign, missing or unknown `client_id` all answer + `404 EXPIRED` (no leak), which the client reports as expired. Cancel by `{client_id, request_id, seq}` cancels the job only when + its `seq` is exactly that `seq`, and raises a mark below which every start of the session is refused. After an admitted start + is rejected (503 `WORKER_WEDGED`, 422 `UNSUPPORTED_FORMAT`, a missing file) the client's next try always uses a fresh request id + and a higher `seq`. `replaced_job_id` is set only for a job of the same session. +* **The guarantee is per session only.** A start from another session (another Studio window, or a client that did not use + this session) replaces the running job as it always did. Sessions do not make one engine serve two windows at once. +* **Residual, stated plainly.** After `SESSION_EXPIRED` the client opens a new session, starts `seq` again at 1, and restarts + ONCE with a fresh request id; a second expiry is shown ("Studio lost its connection to the engine for the 3D view. Try + again."). `SESSION_LIMIT` is shown with Try again and never retried; it reads "The engine is serving as many 3D views as it allows. Close another Studio window, then try again." Separately, if a wanted request still comes + back cancelled or refused as superseded, the client starts it ONCE more with a fresh request id and the next `seq`. Both + restarts are resilience only; neither is what makes the ordering correct. +* **An engine that stops answering cannot stall the view.** Every call has a limit (start 15 s, status and result 30 s) and + ends with an `AbortError` (the caller left) or `TIMEOUT` ("Reading the project took too long", with a **Try again** button). + The limit is a race, so a transport that ignores its abort signal still releases the caller. A timeout also cancels the + request by id. +* `/scene/start` answers only job id, request id, state, revision and the id of a job it replaced; it carries no stage, + progress or error. `scene.ts` models that as `JobStart`. A request id the engine still holds can come back already failed; the + reason is then fetched from `/scene/status`, so the user sees the real message and not a generic one. +* `STALE_START`, `CANCELLED_BEFORE_START`, `SESSION_EXPIRED` and `SESSION_LIMIT` have plain wording. For an abandoned generation they never reach the screen: + answers for a generation that is no longer current, or a path that changed, are dropped (`sceneController.test.ts`, including + A, then B, then A). + +## Against the real engine + +`harness/real-engine.mjs` runs the real client (`src/lib/scene.ts`, in Edge, over real loopback HTTP) against the real engine +process, using the repository example projects and one synthetic large project. Its output is `real-engine-results.json` +(collected into `results.json` by `collect-results.mjs`). What it covers, each with assertions on the wire: + +* **Round trip:** session, start (seq 1, with the session's client id), status polls and result, every status and result carrying + the client id and answered 200. +* **Cancel round trip:** a load of the large project is abandoned right after its start is answered; the cancel goes by + `{client_id, request_id, seq}` and is answered 200; the job is then `cancelled`. Status for that job with a foreign client id, + and with none, is `404 EXPIRED`. +* **Abandoned A after B:** A's start is held in the browser on its way out, A is abandoned (the cancel is real), B loads, and A's + start body is then replayed by hand to the real `/scene/start` route: it is refused (`CANCELLED_BEFORE_START`), a start with a + lower seq is refused, B's job is neither cancelled nor replaced, and an exact retry of B's start returns B's same job (the + client never sends one). +* **`SESSION_EXPIRED` after a fresh engine process:** the engine is stopped and a new process started on the same port; the + client's next start is answered `SESSION_EXPIRED`, one new session is opened, and the restart (seq 1, fresh request id) loads. + **Qualification:** the harness hands the client a transport that carries the restarted engine's NEW token. This proves session + recovery once credentials are available; it does not prove how the real app rediscovers a restarted engine's token, which was + not exercised. +* **Abandoned A replayed after its session expired:** against that fresh engine, A's late start (old session id) is answered + `SESSION_EXPIRED` twice, a cancel for the dead session is `SESSION_EXPIRED`, a status call with the dead id is `404 EXPIRED`, and + the replay opens no session: nothing is revived. +* **`SESSION_LIMIT`:** sessions are opened until the real engine refuses; a load then fails with `SESSION_LIMIT` in plain words, + the client having sent exactly one session request and nothing else (no retry, no start). + +**Not covered, plainly:** a start that is genuinely in flight at the engine when the browser aborts it (the browser cannot recall +a request already on the wire, and a held request was never sent, so the late delivery was replayed by hand rather than raced); +the idle expiry of a session after its time to live (a fresh engine process was used instead); the packaged Windows and Linux +apps (below). + +## Lifecycle on real WebGL + +* One canvas and one viewer per effect; disposal removes the canvas, unregisters listeners and observers, and releases the GL + context. The real adapter is exercised in a loop of create and dispose, and the real panel is mounted and unmounted under + React StrictMode, with some mounts waiting for the view and some unmounted while still loading. Numbers are in Measurements. +* An earlier version of this check found two real defects, both fixed and tested: when React unmounts a route it removes the DOM + before passive cleanup runs, and three.js then fails to remove a document-level keydown listener, so the controller now + disposes the viewer with its canvas attached; and two scene starts sent back to back could be handled by the engine in the + opposite order (the session contract above is the fix for that). +* No WebGL: the context-creation failure is caught; the object list and notes stay, the camera buttons are disabled, and + **Retry 3D view** builds a new canvas. A lost context (forced with `WEBGL_lose_context`) shows the same panel with a different + message and Retry builds a different canvas. Screenshots: `wide-dark-no-webgl`, `narrow-light-no-webgl`, + `wide-dark-context-lost`. +* Keyboard: every control is a real `