3D curves drawn in the viewport (W: lines, arcs, splines on workplanes, snapped to vertices, edge midpoints, workplane origins; a point on a workplane follows it, a snapped vertex is a scad.ref), wires and edges drawn from kernel samples; a failing step previews the model before it; independent spline handles, anchors added while drawing, Shift+A anchor mode; sketch regions (make_faces_from_sketch_rfacelist: outer loops with their holes); a tag on several entities names a set and keeps its pieces; exact surface normals in preview meshes (smooth shading, shared vertices); SimpleWorkplane.point; scad.ref.of a vertex
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -37,6 +37,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi
|
||||
- [make_face_from_sketch_rface](make_face_from_sketch_rface.md) *(from operators/sketch.py)* `top-level`
|
||||
- [make_face_from_wire_rface](make_face_from_wire_rface.md) *(from operators/geometry.py)* `top-level`
|
||||
- [make_face_from_wires_rface](make_face_from_wires_rface.md) *(from operators/geometry.py)* `top-level`
|
||||
- [make_faces_from_sketch_rfacelist](make_faces_from_sketch_rfacelist.md) *(from operators/sketch.py)* `top-level`
|
||||
- [make_gordon_surface_rface](make_gordon_surface_rface.md) *(from operators/geometry.py)* `top-level`
|
||||
- [make_helix_redge](make_helix_redge.md) *(from operators/geometry.py)* `top-level`
|
||||
- [make_helix_rwire](make_helix_rwire.md) *(from operators/geometry.py)* `top-level`
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# make_faces_from_sketch_rfacelist
|
||||
|
||||
## API Definition
|
||||
|
||||
```python
|
||||
def make_faces_from_sketch_rfacelist(sketch, profiles=None, *, require_fully_constrained=False, strict=True, tolerance=1e-07, max_iterations=80)
|
||||
```
|
||||
|
||||
*Source: operators/sketch.py*
|
||||
|
||||
## Import Surface
|
||||
|
||||
- top-level: `from simplecadapi import make_faces_from_sketch_rfacelist`
|
||||
|
||||
## Description
|
||||
|
||||
Make one face per region of the sketch: a closed outer loop minus the loops directly inside it.
|
||||
|
||||
Holes come by themselves: a loop inside an outer loop is a hole of that region, and a loop inside a hole is the
|
||||
outer loop of another region (``inspect_sketch_rsketchprofiles`` reports each closed profile's ``parent`` and
|
||||
``depth`` and the ``regions`` as ``{"outer": i, "holes": [...]}``). ``profiles`` names the regions to make by their
|
||||
outer profile (an index of ``inspect_sketch_rsketchprofiles`` or a profile id); leave it out for every region, in
|
||||
profile order. An open chain, a hole or an unknown profile is refused by name.
|
||||
|
||||
Returns the faces as ``scad.Pieces`` (a list) in that order: a one-shape operation such as ``extrude_rsolid`` runs on
|
||||
every face and returns ``Pieces`` (one solid per region; ``union_rsolid`` joins them, ``make_part_rpart`` makes them
|
||||
bodies). Each face is recorded as ``make_face_from_sketch_rface(sketch, outer, inner_profiles=holes)`` and replays
|
||||
from model JSON.
|
||||
@@ -20,7 +20,10 @@ Bring geometry from another sketch, or from the edges of shapes, into the sketch
|
||||
of shapes (what ``ql.edges().resolve(shape)`` returns). Points go through the plane frames: u = (P - origin) .
|
||||
x_axis, v = (P - origin) . y_axis. Points, lines, circles and arcs in a parallel plane are copied (an arc keeps its
|
||||
counter-clockwise sense); a circle or arc seen edge on becomes a line, a line along the sketch normal a point, an
|
||||
oblique full circle an ellipse; an oblique arc, and edges that are not lines or circles, are refused by name.
|
||||
oblique full circle an ellipse; an oblique arc is refused by name, and so is an edge that is not a line or a circle when
|
||||
it is passed on its own (an Edge); inside a face, wire, shell, solid or compound such an edge is skipped and noted, so
|
||||
``project_rsketch(sketch, face)`` brings the face's boundary in (its lines and arcs) for a sketch on that face to snap
|
||||
and constrain to; in a cell the face comes from the model, so the projection follows it.
|
||||
``entities`` limits the source sketch entities (default: all lines, circles, arcs and free points; ellipses and
|
||||
B-splines are skipped and listed in ``get_metadata("last_edit")``); it is not used with shapes. The copies are
|
||||
``construction`` (default True) and fixed at their projected coordinates. Ids are ``proj_<source sketch id>_<n>``
|
||||
|
||||
@@ -83,7 +83,9 @@ if __name__ == "__main__":
|
||||
A `kind = "part"` notebook needs **no product cell**: when no top-level
|
||||
`Part` has the notebook id, the runtime makes one from the notebook's
|
||||
*open bodies* (public top-level `Solid`s, or the piece lists of split cuts,
|
||||
that no other cell reads and that no other such value was built from), with
|
||||
that no other cell reads and that no other such value was built from; a cell
|
||||
that only makes construction geometry -- workplanes, wires, edges, e.g. a path
|
||||
through the body's vertices -- does not count as reading it), with
|
||||
the notebook id. One open body is a one-body Part (body id `"body"`); several
|
||||
are the bodies of one Part, named by their variables (pieces `<name>_1..n`).
|
||||
Write a `make_part_rpart` cell only to add connectors or a material, or to
|
||||
@@ -227,6 +229,9 @@ The editor and a coding agent share the notebook file:
|
||||
selection, each cell's state and errors, the parameter values, and the path
|
||||
of the viewport image (`.sca-editor/viewport.png`) the agent can look at. The
|
||||
editor keeps `.sca-editor/snapshot.json` current while it runs.
|
||||
When a cell failed, the editor previews the model before it and the snapshot
|
||||
says so in `partial` (the failing cell, its error, the cells that did not run,
|
||||
the bodies shown; `runtime.live.preview_product`); `null` when the model is whole.
|
||||
- The local modules a notebook imports (`from dimensions import DIMS`) are
|
||||
listed under *modules* in the workspace tab, with the notebooks that use
|
||||
them. A module opens in a module view: its source, autosaved, and the fields
|
||||
|
||||
@@ -197,6 +197,22 @@ Errors there are the same errors `sca snapshot` reports per cell. A module that
|
||||
does not compile is reported as `setup failed` with the file and line; fix that
|
||||
file first, since every cell is blocked until it compiles.
|
||||
|
||||
## When a step fails: the model before it
|
||||
|
||||
A cell that fails (a parameter change that breaks a fillet, an edit) leaves no
|
||||
values, and the cells after it do not run, so the product is not made. The
|
||||
viewport then shows **the model before the failing step**, not the last model
|
||||
that built: for a part notebook the open bodies of the cells that are left (the
|
||||
body the failing feature was applied to); for an assembly built up over cells,
|
||||
the assembly before the failing cell. A red notice in the viewport says which
|
||||
step failed and why, and the snapshot carries it as `partial`:
|
||||
`{failed: [{cell, name, status, error}], skipped: [cell ids that did not run],
|
||||
shown: [bodies on screen]}` (`null` when the model is whole). Fix the failing
|
||||
cell; the whole model replaces it. When nothing before the failing cell makes a
|
||||
model (a broken params cell, an assembly made in one cell), the last model stays
|
||||
on screen and the error names the failing cell. Exports never use a partial
|
||||
model: they fail until the cell is fixed.
|
||||
|
||||
## Features the person made with buttons
|
||||
|
||||
Cells with a `# gui:` line, the `sca feature` / `sca sketch` commands, sketches, workplanes and `scad.ref` selections
|
||||
|
||||
@@ -62,6 +62,13 @@ HOLE_DIAMETER = scad.var(name="hole_diameter", default=6.0, unit="mm", comment="
|
||||
rz=...)` (on a face: `make_workplane_from_face_rworkplane(face, x_dir=...)` as the base), the numbers in its params cell.
|
||||
Each new plane becomes the active one and the next Space starts on it: a chain of planes in space, each sketched on and
|
||||
promoted to a wire (below) to loft or sweep between. Shift+Space looks straight at the active workplane.
|
||||
- 3D curves (W, or the command "3D curve"): lines (L), three-point arcs (A) and splines (S) one after another through points
|
||||
on the drawing plane (the active workplane, else XY; Tab changes it between points), snapped to the model's vertices
|
||||
and edge midpoints, the workplanes' origins, the points of other curves and the plane's grid. Enter makes a `curve`
|
||||
feature (`# ---- feature: path (datum) ----`): a point drawn on a workplane is `wp.point(u, v)` (it follows the
|
||||
workplane), one snapped to a vertex is `scad.ref.vertex(...).one(base).get_coordinates()` (it follows the model), others
|
||||
are numbers; the curves become one `make_wire_from_edges_rwire([...])`, a value sweep/loft forms take. Every wire or
|
||||
edge value of the notebook is drawn in the viewport from the kernel's samples (`runtime/live_curves.py`).
|
||||
- A hole is placed with the pointer: while its form is open a ghost of the hole (its diameter and depth) follows the model
|
||||
under the pointer, along the surface's normal there by default ("along the picked face's normal"), and a click writes
|
||||
the start point and direction into the form. Nothing is computed by the kernel until Add.
|
||||
@@ -123,9 +130,13 @@ sca sketch op CELL insert_spline_anchor --args '{"spline": "s1", "at": [12, 8]}'
|
||||
- The spline tool (B) is a pen: a click places an anchor, press-and-drag pulls out its two handles; the curve is a B-spline in
|
||||
anchor form (`"knots": [0, 1, ..], "multiplicities": [4, 3, .., 4]`, control points `[A0, out0, in1, A1, ..]`; see
|
||||
`sketch-and-features.md`, "B-splines with anchors"). Picking the spline shows its handles: dragging an anchor carries its
|
||||
handles, dragging a handle keeps a smooth anchor smooth (Alt while dragging: a corner; S smooths again), a double-click on
|
||||
the curve inserts an anchor and Delete removes the picked anchor (the SDK edits above). A B-spline with control points
|
||||
(older documents) shows its control polygon and a "convert to anchors" button (K).
|
||||
handles; dragging a handle moves only that handle (each side has its own direction and pull; Shift while dragging turns
|
||||
the other handle into line, keeping its length; S smooths the picked anchors). Inserting anchors is part of drawing: a
|
||||
point, line or pen click on an anchor-form spline's curve (the cursor shows "+ anchor") inserts an anchor there with
|
||||
`insert_spline_anchor_rsketch` and uses that point. With a spline picked, Shift+A (or the "anchors" toolbar button) is
|
||||
anchor mode: a click on a curve adds an anchor, a click on an inner anchor removes it (`remove_spline_anchor_rsketch`);
|
||||
Esc or Shift+A leaves. Delete removes the picked anchor; a double-click on the curve inserts one. A B-spline with control
|
||||
points (older documents) shows its control polygon and a "convert to anchors" button (K).
|
||||
- A sketch document may say `"output": "wire"`: the cell then ends in
|
||||
`name = scad.make_wire_from_sketch_rwire(sketch=_sketch, profile=<i>, ...)` (a closed loop or an open chain from
|
||||
`inspect_sketch_rsketchprofiles`, whose `closed` says which) and the notebook lists it as a wire, so `op.sweep_rsolid`
|
||||
|
||||
@@ -145,9 +145,9 @@ control points `[A0, out0, in1, A1, out1, in2, A2, ...]`, the anchors `A<i>` on
|
||||
curve, each with an in-handle and an out-handle (a pen tool's curve; the editor's
|
||||
spline tool draws this form, knots `0..n`, multiplicities `[4, 3, ..., 3, 4]`). Every
|
||||
control point is a sketch point and the solver moves all of them, so moving an anchor
|
||||
or a handle is moving a point; the two handles of an anchor are independent (their
|
||||
lengths are the pull on each side; in one line the anchor is smooth). Trim and extend
|
||||
keep the form.
|
||||
or a handle is moving a point; the two handles of an anchor are independent (each
|
||||
has its own direction and length, the pull on that side; they need not be in one line
|
||||
-- when they are, the anchor is smooth). Trim and extend keep the form.
|
||||
|
||||
```python
|
||||
sketch = scad.insert_spline_anchor_rsketch(sketch, "s1", (12.0, 8.0)) # curve unchanged: new p<n> anchor + 2 handles
|
||||
|
||||
+109
-5
@@ -16,7 +16,12 @@ import { AssemblyPanel } from "@/components/AssemblyPanel";
|
||||
import { ConnectorGizmos, type Gizmo } from "@/components/ConnectorGizmos";
|
||||
import { WorkplanePatches } from "@/components/WorkplanePatches";
|
||||
import { TagSplits, parseTagSplits, type TagSplit } from "@/components/TagSplits";
|
||||
import { PartialNotice } from "@/components/PartialModel";
|
||||
import { describePartial, parsePartial, samePartial, type PartialModel } from "@/lib/partial";
|
||||
import { WorkplanePlacePanel, WorkplanePlacer, type PlaceBase, type PlaceMode } from "@/components/WorkplanePlacer";
|
||||
import { CurveDrawer } from "@/components/CurveDrawer";
|
||||
import { CurveLines, curveEnds, parseCurves, type CurveSample } from "@/components/CurveLines";
|
||||
import type { CurveDoc, DrawPlane } from "@/lib/curve3d";
|
||||
import { NAMED_FRAMES, ZERO_PLACE, cleanValues, faceFrame, type PlaceFrame, type PlaceValues } from "@/lib/workplane-place";
|
||||
import { parseWorkplanes, resolvePlane, workplanePlane, workplaneRequest, type WorkplaneFrame } from "@/lib/workplanes";
|
||||
import { fitDistanceMm } from "@/lib/sketch-view";
|
||||
@@ -106,10 +111,19 @@ export function App() {
|
||||
// The notebook's workplanes as the kernel reported them, and the one Space made (or chose) last: new sketches go on it.
|
||||
const [workplanes, setWorkplanes] = useState<WorkplaneFrame[]>([]);
|
||||
const [tagSplits, setTagSplits] = useState<TagSplit[]>([]);
|
||||
// A cell failed: the model shown is the one before it (the preview says which step failed); null when it is whole.
|
||||
const [partial, setPartial] = useState<PartialModel | null>(null);
|
||||
const partialRef = useRef<PartialModel | null>(null);
|
||||
const cellTitles = useMemo(() => new Map(cells.map((cell) => [cell.id, cell.title ?? ""])), [cells]);
|
||||
const [curves, setCurves] = useState<CurveSample[]>([]);
|
||||
// A workplane being placed by hand (Space): its base, the numbers the handles write, move or turn, its name.
|
||||
const [placing, setPlacing] = useState<{ base: string; values: PlaceValues; mode: PlaceMode; name: string; face: { item: SelectionItem; frame: PlaceFrame } | null; error: string | null } | null>(null);
|
||||
const placingRef = useRef(placing);
|
||||
placingRef.current = placing;
|
||||
// A 3D curve being drawn in the viewport (W): the plane it starts on, the error of a failed commit.
|
||||
const [drawing, setDrawing] = useState<{ plane: string; error: string | null } | null>(null);
|
||||
const drawingRef = useRef(drawing);
|
||||
drawingRef.current = drawing;
|
||||
const [activeWorkplane, setActiveWorkplane] = useState<string | null>(null);
|
||||
const [selectionMode, setSelectionMode] = useState<SelectionMode>("solid");
|
||||
const [sceneVersion, setSceneVersion] = useState(0);
|
||||
@@ -327,11 +341,21 @@ export function App() {
|
||||
socket.on("notebook.features", (envelope) => setFeatures((envelope["features"] as NotebookFeature[]) ?? []));
|
||||
socket.on("workplanes", (envelope) => setWorkplanes(parseWorkplanes(envelope["workplanes"])));
|
||||
socket.on("tag_splits", (envelope) => setTagSplits(parseTagSplits(envelope["splits"])));
|
||||
socket.on("curves", (envelope) => setCurves(parseCurves(envelope["curves"])));
|
||||
|
||||
socket.on("preview", (envelope) => {
|
||||
setLoading(null);
|
||||
const shown = hasModel.current;
|
||||
hasModel.current = true;
|
||||
// Every preview says whether it is whole or the model before a failing step (an unchanged one too); a new failure
|
||||
// is noted in the log once (the cell's own error is logged already), not on every slider tick that fails the same way.
|
||||
const nextPartial = parsePartial(envelope["partial"]);
|
||||
if (nextPartial && !samePartial(partialRef.current, nextPartial)) {
|
||||
const { title, reason } = describePartial(nextPartial);
|
||||
log.push("info", `showing ${title.charAt(0).toLowerCase()}${title.slice(1)}: ${reason}`);
|
||||
}
|
||||
partialRef.current = nextPartial;
|
||||
setPartial(nextPartial);
|
||||
// The kernel published the model that is already on screen: nothing to
|
||||
// reload. (A page that has none yet, a refresh replaying this envelope, needs it.)
|
||||
if (envelope["unchanged"] && shown) {
|
||||
@@ -465,7 +489,7 @@ export function App() {
|
||||
leftTabRef.current = leftTab;
|
||||
const selectComponent = asm.setSelected;
|
||||
const handlePick = useCallback((result: PickResult) => {
|
||||
if (placingRef.current) return; // a click on the handles is not a pick
|
||||
if (placingRef.current || drawingRef.current) return; // a click on the handles, or a curve's point, is not a pick
|
||||
if (dialogRef.current?.spec.id === "hole") return; // a click places the hole (HolePlacer), it picks nothing
|
||||
if (choosingRef.current) {
|
||||
void pickSketchFace(result);
|
||||
@@ -731,6 +755,63 @@ export function App() {
|
||||
}
|
||||
}, [gui.run, log.push]);
|
||||
|
||||
// -- drawing a 3D curve ----------------------------------------------------------------------------------------------
|
||||
|
||||
/** The planes a 3D curve is drawn on: the datum planes and every workplane (as the kernel reported its frame). */
|
||||
const drawPlanes = useMemo<DrawPlane[]>(
|
||||
() => [
|
||||
...(["XY", "XZ", "YZ"] as const).map((name) => ({ name, workplane: false, ...NAMED_FRAMES[name] })),
|
||||
...workplanes.map((wp) => ({ name: wp.name, workplane: true, origin: wp.origin, x_axis: wp.x_axis, y_axis: wp.y_axis, normal: wp.normal })),
|
||||
],
|
||||
[workplanes],
|
||||
);
|
||||
/** The points of the notebook's 3D curves, from their documents: a new path snaps to them. */
|
||||
const curveSnapPoints = useMemo(
|
||||
() =>
|
||||
(gui.state?.features ?? []).flatMap((feature) =>
|
||||
feature.gui?.spec === "curve"
|
||||
? ((feature.gui.values?.curve as CurveDoc | undefined)?.points ?? []).map((point) => ({ at: point.at, label: `${feature.slug}.${point.id}` }))
|
||||
: [],
|
||||
).concat(curveEnds(curves)),
|
||||
[gui.state?.features, curves],
|
||||
);
|
||||
const startDrawing = useCallback(() => {
|
||||
if (sketchingRef.current || placingRef.current) return;
|
||||
const active = activeWorkplaneRef.current;
|
||||
setPicked([]);
|
||||
setDrawing({ plane: active && workplanesRef.current.some((wp) => wp.name === active) ? active : "XY", error: null });
|
||||
}, []);
|
||||
const commitCurve = useCallback(
|
||||
async (doc: CurveDoc, name: string) => {
|
||||
setGuiBusy(true);
|
||||
try {
|
||||
const result = await gui.run({ op: "add", spec: "curve", name, values: { curve: doc } });
|
||||
assertCellRan(result);
|
||||
log.push("ok", `add ${result.name}`);
|
||||
setDrawing(null);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
setDrawing((d) => (d ? { ...d, error: message } : d));
|
||||
} finally {
|
||||
setGuiBusy(false);
|
||||
}
|
||||
},
|
||||
[gui.run, log.push],
|
||||
);
|
||||
// W: draw a 3D curve (not while typing, sketching or placing a workplane).
|
||||
useEffect(() => {
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key.toLowerCase() !== "w" || event.repeat || event.metaKey || event.ctrlKey || event.altKey || event.defaultPrevented) return;
|
||||
if (drawingRef.current || sketchingRef.current || placingRef.current) return;
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (target?.closest("input, textarea, select, [contenteditable=true], .cm-editor, [role=dialog]")) return;
|
||||
event.preventDefault();
|
||||
startDrawing();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [startDrawing]);
|
||||
|
||||
// -- placing a workplane by hand ----------------------------------------------------------------------------------
|
||||
|
||||
/** The bases a workplane can be placed on: the datum planes, every workplane of the notebook, and the picked face. */
|
||||
@@ -868,7 +949,7 @@ export function App() {
|
||||
useEffect(() => {
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key !== " " || event.repeat || event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
if (sketchingRef.current || placingRef.current) return; // space pans the sketch view
|
||||
if (sketchingRef.current || placingRef.current || drawingRef.current) return; // space pans the sketch view
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (target?.closest("input, textarea, select, button, [contenteditable=true], .cm-editor, [role=dialog]")) return;
|
||||
event.preventDefault();
|
||||
@@ -905,7 +986,16 @@ export function App() {
|
||||
const allCommands = useMemo<Command[]>(
|
||||
() => [
|
||||
// The assembly layout is not a dialog: it is its own panel (registered below), so its spec is left out of the generic list.
|
||||
...commandsFromSpecs((gui.catalog?.specs ?? []).filter((spec) => spec.id !== "assembly" && spec.id !== "workplane"), openSpec, FEATURE_ICONS),
|
||||
...commandsFromSpecs((gui.catalog?.specs ?? []).filter((spec) => spec.id !== "assembly" && spec.id !== "workplane" && spec.id !== "curve"), openSpec, FEATURE_ICONS),
|
||||
{
|
||||
id: "curve_draw",
|
||||
label: "3D curve",
|
||||
group: "Sketch",
|
||||
keywords: ["curve", "wire", "path", "3d", "polyline", "spline", "arc", "rail", "sweep"],
|
||||
description: "Draw a path in space (W): lines, arcs and splines on workplanes, snapped to the model; it becomes a wire to sweep along or loft through.",
|
||||
icon: FEATURE_ICONS.sketch,
|
||||
run: () => startDrawing(),
|
||||
},
|
||||
{
|
||||
id: "workplane_place",
|
||||
label: "Workplane",
|
||||
@@ -949,7 +1039,7 @@ export function App() {
|
||||
},
|
||||
...assemblyCommands(openAssembly, { assembly: Boxes, connectors: Cable }),
|
||||
],
|
||||
[gui.catalog, openSpec, sketchOnSelectedFace, editSelectedSketch, openAssembly, workplaneFromSelection],
|
||||
[gui.catalog, openSpec, sketchOnSelectedFace, editSelectedSketch, openAssembly, workplaneFromSelection, startPlacing, startDrawing],
|
||||
);
|
||||
// The stand-alone combine commands (Cut, Union, Intersect, Cut/Boss with sketch) are offered only while several bodies are open:
|
||||
// a new solid says how it meets the body in its own dialog.
|
||||
@@ -1236,7 +1326,21 @@ export function App() {
|
||||
onHover={setHoverSketch}
|
||||
/>
|
||||
{viewRef.current && workplanes.length > 0 && <WorkplanePatches view={viewRef.current} workplanes={workplanes} active={activeWorkplane} />}
|
||||
{!sketching && !placing && viewRef.current && <TagSplits view={viewRef.current} splits={tagSplits} sceneVersion={sceneVersion} />}
|
||||
{!sketching && !placing && !drawing && viewRef.current && <TagSplits view={viewRef.current} splits={tagSplits} sceneVersion={sceneVersion} />}
|
||||
{partial && !sketching && <PartialNotice partial={partial} titles={cellTitles} />}
|
||||
{viewRef.current && curves.length > 0 && <CurveLines view={viewRef.current} curves={curves} />}
|
||||
{drawing && viewRef.current && (
|
||||
<CurveDrawer
|
||||
view={viewRef.current}
|
||||
planes={drawPlanes}
|
||||
others={curveSnapPoints}
|
||||
plane={drawing.plane}
|
||||
busy={guiBusy}
|
||||
error={drawing.error}
|
||||
onCommit={(doc, name) => void commitCurve(doc, name)}
|
||||
onCancel={() => setDrawing(null)}
|
||||
/>
|
||||
)}
|
||||
{placing && viewRef.current && placeBase && (
|
||||
<>
|
||||
<WorkplanePlacer
|
||||
|
||||
@@ -0,0 +1,415 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import * as THREE from "three";
|
||||
import { Spline, Slash, Waves } from "lucide-react";
|
||||
|
||||
import {
|
||||
SNAP_PX,
|
||||
addSegment,
|
||||
dropLast,
|
||||
gridStep,
|
||||
nextId,
|
||||
onGrid,
|
||||
pathEnd,
|
||||
pickSnap,
|
||||
pointAt,
|
||||
pointFor,
|
||||
rayOnPlane,
|
||||
segmentPoints,
|
||||
type CurveDoc,
|
||||
type CurveKind,
|
||||
type DrawPlane,
|
||||
type SnapCandidate,
|
||||
} from "@/lib/curve3d";
|
||||
import type { Vec3 } from "@/lib/sketch-plane";
|
||||
import { rayThrough } from "@/scene/camera-projection";
|
||||
import { OVERLAY_LAYER } from "@/scene/renderer/brep-renderer";
|
||||
import type { SceneView } from "@/scene/scene-view";
|
||||
|
||||
const EMPTY: CurveDoc = { points: [], curves: [] };
|
||||
const PATH = "#2563eb";
|
||||
const DRAFT = "#f59e0b";
|
||||
const TOOLS: { kind: CurveKind; key: string; label: string; icon: typeof Slash }[] = [
|
||||
{ kind: "line", key: "l", label: "line", icon: Slash },
|
||||
{ kind: "arc", key: "a", label: "arc", icon: Waves },
|
||||
{ kind: "spline", key: "s", label: "spline", icon: Spline },
|
||||
];
|
||||
|
||||
const world = (p: Vec3) => new THREE.Vector3(p[0] / 1000, p[1] / 1000, p[2] / 1000);
|
||||
|
||||
/** The model's vertices and edge midpoints, in world mm, as snap targets (screen positions filled per pointer move). */
|
||||
function modelTargets(view: SceneView): Omit<SnapCandidate, "screen">[] {
|
||||
const out: Omit<SnapCandidate, "screen">[] = [];
|
||||
const position = new THREE.Vector3();
|
||||
view.engine.modelRoot.updateMatrixWorld(true);
|
||||
view.engine.modelRoot.traverse((object) => {
|
||||
if (!object.visible) return;
|
||||
if (object instanceof THREE.Points && Array.isArray(object.userData.vertexEntityIds)) {
|
||||
const ids = object.userData.vertexEntityIds as string[];
|
||||
const positions = object.geometry.getAttribute("position");
|
||||
for (let i = 0; i < positions.count && i < ids.length; i++) {
|
||||
position.fromBufferAttribute(positions, i).applyMatrix4(object.matrixWorld);
|
||||
out.push({ kind: "vertex", at: [position.x * 1000, position.y * 1000, position.z * 1000], entityId: ids[i], label: "vertex", priority: 0 });
|
||||
}
|
||||
} else if (object instanceof THREE.LineSegments && typeof object.userData.nodeId === "string") {
|
||||
const node = view.engine.nodes.find((item) => item.node_id === object.userData.nodeId);
|
||||
const sidecar = view.sidecarFor(node);
|
||||
const positions = object.geometry.getAttribute("position");
|
||||
const index = object.geometry.index;
|
||||
if (!sidecar || !positions) return;
|
||||
for (const group of sidecar.edge_groups) {
|
||||
// the midpoint along the edge's polyline
|
||||
const segment = (k: number): [THREE.Vector3, THREE.Vector3] => {
|
||||
const at = (j: number) => new THREE.Vector3().fromBufferAttribute(positions, index ? index.getX(j) : j).applyMatrix4(object.matrixWorld);
|
||||
return [at(group.first_index + k), at(group.first_index + k + 1)];
|
||||
};
|
||||
const lengths: number[] = [];
|
||||
for (let k = 0; k + 1 < group.index_count; k += 2) {
|
||||
const [a, b] = segment(k);
|
||||
lengths.push(a.distanceTo(b));
|
||||
}
|
||||
const total = lengths.reduce((s, l) => s + l, 0);
|
||||
if (!(total > 0)) continue;
|
||||
let left = total / 2;
|
||||
for (let s = 0; s < lengths.length; s++) {
|
||||
if (left <= lengths[s]) {
|
||||
const [a, b] = segment(s * 2);
|
||||
const p = a.lerp(b, lengths[s] > 0 ? left / lengths[s] : 0);
|
||||
out.push({ kind: "midpoint", at: [p.x * 1000, p.y * 1000, p.z * 1000], label: "midpoint", priority: 1 });
|
||||
break;
|
||||
}
|
||||
left -= lengths[s];
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
function line(points: Vec3[], color: string, dashed = false): THREE.Line {
|
||||
const geometry = new THREE.BufferGeometry().setFromPoints(points.map(world));
|
||||
const material = dashed
|
||||
? new THREE.LineDashedMaterial({ color, dashSize: 0.002, gapSize: 0.0015, depthTest: false, transparent: true })
|
||||
: new THREE.LineBasicMaterial({ color, depthTest: false, transparent: true });
|
||||
const object = new THREE.Line(geometry, material);
|
||||
if (dashed) object.computeLineDistances();
|
||||
object.renderOrder = 30;
|
||||
object.layers.enable(OVERLAY_LAYER);
|
||||
return object;
|
||||
}
|
||||
|
||||
/** Draws a 3D curve in the viewport: lines, arcs and splines, one after another, through points on the drawing plane (a
|
||||
* datum plane or a workplane, Tab to change it between points), snapped to the model's vertices and edge midpoints, the
|
||||
* workplanes' origins, the path's own points and the plane's grid. A point drawn on a workplane is kept on it (u, v),
|
||||
* one snapped to a vertex is kept at it (its reference), so the path follows both. Enter makes the `curve` feature. */
|
||||
export function CurveDrawer({
|
||||
view,
|
||||
planes,
|
||||
others = [],
|
||||
plane: initialPlane,
|
||||
busy,
|
||||
error,
|
||||
onCommit,
|
||||
onCancel,
|
||||
}: {
|
||||
view: SceneView;
|
||||
planes: DrawPlane[];
|
||||
/** The points of the notebook's other 3D curves (snap targets: a new path can start where one ends). */
|
||||
others?: { at: Vec3; label: string }[];
|
||||
plane: string;
|
||||
busy: boolean;
|
||||
error: string | null;
|
||||
onCommit: (doc: CurveDoc, name: string) => void;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
const [doc, setDoc] = useState<CurveDoc>(EMPTY);
|
||||
const [tool, setTool] = useState<CurveKind>("line");
|
||||
const [planeName, setPlaneName] = useState(initialPlane);
|
||||
const [pending, setPending] = useState<string[]>([]); // an arc's middle point, a spline's points so far
|
||||
const [hover, setHover] = useState<{ at: Vec3; snap: SnapCandidate | null; screen: [number, number] } | null>(null);
|
||||
const [name, setName] = useState("path");
|
||||
const plane = planes.find((p) => p.name === planeName) ?? planes[0];
|
||||
const state = useRef({ doc, tool, plane, pending });
|
||||
state.current = { doc, tool, plane, pending };
|
||||
|
||||
// -- what the pointer is over -------------------------------------------------------------------------------------
|
||||
const targets = useMemo(() => modelTargets(view), [view]);
|
||||
const toScreen = useCallback(
|
||||
(p: Vec3): [number, number] | null => {
|
||||
const rect = view.engine.domElement.getBoundingClientRect();
|
||||
const v = world(p).project(view.engine.camera);
|
||||
if (v.z > 1 || v.z < -1) return null;
|
||||
return [((v.x + 1) / 2) * rect.width, ((1 - v.y) / 2) * rect.height];
|
||||
},
|
||||
[view],
|
||||
);
|
||||
const locate = useCallback(
|
||||
(clientX: number, clientY: number): { at: Vec3; snap: SnapCandidate | null; screen: [number, number] } | null => {
|
||||
const { engine } = view;
|
||||
const rect = engine.domElement.getBoundingClientRect();
|
||||
const pointer: [number, number] = [clientX - rect.left, clientY - rect.top];
|
||||
const { doc: current, plane: drawOn } = state.current;
|
||||
const candidates: SnapCandidate[] = [];
|
||||
const offer = (c: Omit<SnapCandidate, "screen">) => {
|
||||
const screen = toScreen(c.at);
|
||||
if (screen) candidates.push({ ...c, screen });
|
||||
};
|
||||
targets.forEach(offer);
|
||||
for (const point of current.points) offer({ kind: "point", at: point.at, pointId: point.id, label: point.id, priority: 0 });
|
||||
for (const p of planes) if (p.workplane) offer({ kind: "origin", at: p.origin, label: `${p.name} origin`, priority: 1, workplane: p.name });
|
||||
for (const other of others) offer({ kind: "point", at: other.at, label: other.label, priority: 1 });
|
||||
const raycaster = new THREE.Raycaster();
|
||||
rayThrough(raycaster, new THREE.Vector2((pointer[0] / rect.width) * 2 - 1, -(pointer[1] / rect.height) * 2 + 1), engine.camera);
|
||||
const o = raycaster.ray.origin;
|
||||
const d = raycaster.ray.direction;
|
||||
const hit = rayOnPlane([o.x * 1000, o.y * 1000, o.z * 1000], [d.x, d.y, d.z], drawOn);
|
||||
if (hit) {
|
||||
// a grid of about 24 px on screen where the pointer is
|
||||
const mmPerPx = (engine.camera.position.distanceTo(world(hit)) * 1000 * 2 * Math.tan(THREE.MathUtils.degToRad(engine.camera.fov) / 2)) / rect.height;
|
||||
const step = gridStep(mmPerPx * 24);
|
||||
offer({ kind: "grid", at: onGrid(drawOn, hit, step), label: `grid ${step} mm`, priority: 3 });
|
||||
}
|
||||
const snap = pickSnap(candidates, pointer, SNAP_PX);
|
||||
const at = snap ? snap.at : hit;
|
||||
return at ? { at, snap, screen: snap ? snap.screen : pointer } : null;
|
||||
},
|
||||
[view, targets, planes, others, toScreen],
|
||||
);
|
||||
|
||||
// -- clicks make points; Enter, Backspace, Esc, Tab and the tool keys ---------------------------------------------
|
||||
const place = useCallback((spot: { at: Vec3; snap: SnapCandidate | null }) => {
|
||||
const { doc: current, tool: kind, plane: drawOn, pending: waiting } = state.current;
|
||||
const start = pathEnd(current) ?? current.points[0]?.id ?? null; // where the next segment starts
|
||||
const made = pointFor(current, drawOn, spot.at, spot.snap);
|
||||
let next = made.doc;
|
||||
if (start === null) {
|
||||
setDoc(next); // the path's first point
|
||||
return;
|
||||
}
|
||||
if (kind === "line") {
|
||||
if (made.id === start) return;
|
||||
next = addSegment(next, "line", [start, made.id]);
|
||||
setPending([]);
|
||||
} else if (kind === "arc") {
|
||||
if (waiting.length === 0) {
|
||||
setDoc(next);
|
||||
setPending([made.id]); // the point the arc passes through
|
||||
return;
|
||||
}
|
||||
next = addSegment(next, "arc", [start, waiting[0], made.id]);
|
||||
setPending([]);
|
||||
} else {
|
||||
setDoc(next);
|
||||
setPending([...waiting, made.id]);
|
||||
return;
|
||||
}
|
||||
setDoc(next);
|
||||
}, []);
|
||||
|
||||
/** The spline drawn so far becomes a segment (a spline ends when another tool or Enter takes over). */
|
||||
const settleSpline = useCallback((current: CurveDoc, waiting: string[]): CurveDoc => {
|
||||
if (state.current.tool !== "spline" || waiting.length === 0) return current;
|
||||
const start = pathEnd(current) ?? current.points[0]?.id;
|
||||
return start ? addSegment(current, "spline", [start, ...waiting]) : current;
|
||||
}, []);
|
||||
|
||||
const finish = useCallback(() => {
|
||||
const settled = settleSpline(state.current.doc, state.current.pending);
|
||||
if (settled.curves.length === 0) return;
|
||||
const used = new Set(settled.curves.flatMap((c) => c.points));
|
||||
onCommit({ ...settled, points: settled.points.filter((p) => used.has(p.id)) }, name);
|
||||
}, [onCommit, name, settleSpline]);
|
||||
|
||||
const switchTool = useCallback(
|
||||
(kind: CurveKind) => {
|
||||
const settled = settleSpline(state.current.doc, state.current.pending);
|
||||
const used = new Set([...settled.curves.flatMap((c) => c.points), settled.points[0]?.id]);
|
||||
setDoc({ ...settled, points: settled.points.filter((p) => used.has(p.id)) });
|
||||
setPending([]);
|
||||
setTool(kind);
|
||||
},
|
||||
[settleSpline],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const element = view.engine.domElement;
|
||||
let down: { x: number; y: number } | null = null;
|
||||
const onMove = (event: PointerEvent) => {
|
||||
if (event.buttons !== 0) return;
|
||||
setHover(locate(event.clientX, event.clientY));
|
||||
};
|
||||
const onDown = (event: PointerEvent) => {
|
||||
down = event.button === 0 ? { x: event.clientX, y: event.clientY } : null;
|
||||
};
|
||||
const onUp = (event: PointerEvent) => {
|
||||
if (!down || Math.hypot(event.clientX - down.x, event.clientY - down.y) > 4) return; // a drag turns the view
|
||||
down = null;
|
||||
const spot = locate(event.clientX, event.clientY);
|
||||
if (spot) place(spot);
|
||||
};
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (target?.closest("input, textarea, select, [contenteditable=true], .cm-editor")) return;
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
const key = event.key.toLowerCase();
|
||||
const tool = TOOLS.find((t) => t.key === key);
|
||||
if (tool) {
|
||||
event.preventDefault();
|
||||
switchTool(tool.kind);
|
||||
} else if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
finish();
|
||||
} else if (event.key === "Tab") {
|
||||
event.preventDefault();
|
||||
setPlaneName((current) => {
|
||||
const at = planes.findIndex((p) => p.name === current);
|
||||
return planes[(at + (event.shiftKey ? planes.length - 1 : 1)) % planes.length].name;
|
||||
});
|
||||
} else if (event.key === "Backspace") {
|
||||
event.preventDefault();
|
||||
const { doc: current, pending: waiting } = state.current;
|
||||
if (waiting.length) {
|
||||
const kept = waiting.slice(0, -1);
|
||||
const used = new Set([...current.curves.flatMap((c) => c.points), current.points[0]?.id, ...kept]);
|
||||
setPending(kept);
|
||||
setDoc({ ...current, points: current.points.filter((p) => used.has(p.id)) });
|
||||
} else if (current.curves.length) setDoc(dropLast(current));
|
||||
else setDoc(EMPTY);
|
||||
} else if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
if (state.current.pending.length) setPending([]);
|
||||
else onCancel();
|
||||
}
|
||||
};
|
||||
element.addEventListener("pointermove", onMove);
|
||||
element.addEventListener("pointerdown", onDown);
|
||||
element.addEventListener("pointerup", onUp);
|
||||
window.addEventListener("keydown", onKey);
|
||||
element.style.cursor = "crosshair";
|
||||
return () => {
|
||||
element.removeEventListener("pointermove", onMove);
|
||||
element.removeEventListener("pointerdown", onDown);
|
||||
element.removeEventListener("pointerup", onUp);
|
||||
window.removeEventListener("keydown", onKey);
|
||||
element.style.cursor = "";
|
||||
};
|
||||
}, [view, locate, place, finish, switchTool, planes, onCancel]);
|
||||
|
||||
// -- what is drawn: the path, the segment being drawn, the points, the plane's grid --------------------------------
|
||||
const group = useMemo(() => new THREE.Group(), []);
|
||||
useEffect(() => {
|
||||
view.engine.threeScene.add(group);
|
||||
return () => {
|
||||
group.removeFromParent();
|
||||
view.engine.invalidate();
|
||||
};
|
||||
}, [view, group]);
|
||||
useEffect(() => {
|
||||
for (const child of [...group.children]) {
|
||||
child.removeFromParent();
|
||||
child.traverse((o) => {
|
||||
const mesh = o as THREE.Mesh;
|
||||
mesh.geometry?.dispose();
|
||||
(mesh.material as THREE.Material | undefined)?.dispose?.();
|
||||
});
|
||||
}
|
||||
const at = (id: string) => pointAt(doc, id)!;
|
||||
for (const curve of doc.curves) group.add(line(segmentPoints(curve.kind, curve.points.map(at)), PATH));
|
||||
const start = pathEnd(doc) ?? doc.points[0]?.id;
|
||||
if (start && hover) {
|
||||
const draft = [at(start), ...pending.map(at), hover.at];
|
||||
group.add(line(segmentPoints(tool === "arc" && draft.length === 3 ? "arc" : tool === "spline" ? "spline" : "line", draft), DRAFT, true));
|
||||
}
|
||||
const marks = new THREE.Points(
|
||||
new THREE.BufferGeometry().setFromPoints(doc.points.map((p) => world(p.at))),
|
||||
new THREE.PointsMaterial({ color: PATH, size: 7, sizeAttenuation: false, depthTest: false }),
|
||||
);
|
||||
marks.renderOrder = 31;
|
||||
marks.layers.enable(OVERLAY_LAYER);
|
||||
group.add(marks);
|
||||
if (plane) {
|
||||
// the drawing plane: a grid around its origin, about the model's size
|
||||
const bounds = view.modelBoundsMm();
|
||||
const extent = bounds ? Math.max(...bounds.max.map((v, i) => v - bounds.min[i]), 20) : 100;
|
||||
const size = extent * 1.6;
|
||||
const grid = new THREE.GridHelper(size / 1000, 16, 0x2563eb, 0x64748b);
|
||||
const material = grid.material as THREE.Material;
|
||||
material.transparent = true;
|
||||
material.opacity = 0.25;
|
||||
material.depthWrite = false;
|
||||
const basis = new THREE.Matrix4().makeBasis(new THREE.Vector3(...plane.x_axis), new THREE.Vector3(...plane.normal), new THREE.Vector3(...plane.y_axis).negate());
|
||||
grid.quaternion.setFromRotationMatrix(basis);
|
||||
grid.position.copy(world(plane.origin));
|
||||
grid.layers.enable(OVERLAY_LAYER);
|
||||
group.add(grid);
|
||||
}
|
||||
view.engine.invalidate();
|
||||
}, [doc, pending, hover, tool, plane, group, view]);
|
||||
|
||||
const hint =
|
||||
doc.points.length === 0
|
||||
? "Click the first point."
|
||||
: tool === "arc"
|
||||
? pending.length === 0
|
||||
? "Click a point the arc passes through."
|
||||
: "Click where the arc ends."
|
||||
: tool === "spline"
|
||||
? "Click the points the spline passes through; another tool or Enter ends it."
|
||||
: "Click where the line ends.";
|
||||
|
||||
return (
|
||||
<>
|
||||
{hover?.snap && (
|
||||
<div className="pointer-events-none absolute z-20" style={{ left: hover.screen[0] - 9, top: hover.screen[1] - 9 }}>
|
||||
<div className="size-[18px] rounded-full border-2 border-amber-500" />
|
||||
<span className="absolute left-5 top-0 whitespace-nowrap bg-popover/90 px-1 font-mono text-[10px] text-amber-600">{hover.snap.label}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="pointer-events-auto absolute left-3 top-3 z-30 flex max-w-[min(460px,90%)] flex-col gap-2 border-2 border-primary bg-popover px-3 py-2 text-[11px] shadow-[4px_4px_0_var(--shadow-hard)]" data-testid="curve-drawer">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-semibold">3D curve</span>
|
||||
<input id="curve-name" aria-label="name" className="w-20 border border-input bg-background px-1 font-mono" value={name} onChange={(event) => setName(event.target.value)} />
|
||||
<span className="flex border border-input">
|
||||
{TOOLS.map((item) => (
|
||||
<button
|
||||
key={item.kind}
|
||||
type="button"
|
||||
title={`${item.label} (${item.key.toUpperCase()})`}
|
||||
className={`flex items-center gap-1 px-1.5 ${tool === item.kind ? "bg-primary text-primary-foreground" : ""}`}
|
||||
onClick={() => switchTool(item.kind)}
|
||||
>
|
||||
<item.icon className="size-3" /> {item.label}
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
<span className="text-muted-foreground">on</span>
|
||||
<select id="curve-plane" aria-label="drawing plane" className="border border-input bg-background px-1" value={plane?.name} onChange={(event) => setPlaneName(event.target.value)}>
|
||||
{planes.map((item) => (
|
||||
<option key={item.name} value={item.name}>
|
||||
{item.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<span className="text-muted-foreground">
|
||||
{hint} Snaps to vertices, edge midpoints, workplane origins, its own points and the grid. Tab: next plane · ⌫: back
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<button type="button" disabled={busy || doc.curves.length + (pending.length && tool === "spline" ? 1 : 0) === 0} className="border-2 border-primary bg-primary px-2 py-0.5 font-semibold text-primary-foreground disabled:opacity-50" onClick={finish}>
|
||||
Finish (Enter)
|
||||
</button>
|
||||
<button type="button" className="border border-border px-2 py-0.5 hover:bg-accent" onClick={onCancel}>
|
||||
Cancel (Esc)
|
||||
</button>
|
||||
<span className="font-mono text-muted-foreground">
|
||||
{doc.curves.length} {doc.curves.length === 1 ? "segment" : "segments"} · {nextId(doc.points.map((p) => p.id), "p")}
|
||||
</span>
|
||||
</div>
|
||||
{error && (
|
||||
<div role="alert" className="text-fail">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useEffect, useMemo } from "react";
|
||||
import * as THREE from "three";
|
||||
|
||||
import { SceneLabel } from "@/components/scene/SceneLabel";
|
||||
import type { Vec3 } from "@/lib/sketch-plane";
|
||||
import { OVERLAY_LAYER } from "@/scene/renderer/brep-renderer";
|
||||
import type { SceneView } from "@/scene/scene-view";
|
||||
|
||||
/** A wire or edge value of the notebook, as the kernel sampled it (the server's `curves` envelope): world mm. */
|
||||
export type CurveSample = { name: string; kind: "wire" | "edge"; edges: Vec3[][] };
|
||||
|
||||
const COLOR = "#0ea5e9";
|
||||
|
||||
export function parseCurves(raw: unknown): CurveSample[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw.filter(
|
||||
(item): item is CurveSample =>
|
||||
!!item && typeof item.name === "string" && Array.isArray(item.edges) && item.edges.every((e: unknown) => Array.isArray(e) && e.length >= 2),
|
||||
);
|
||||
}
|
||||
|
||||
/** The ends of the curves' edges: where a new path can join one (snap targets). */
|
||||
export function curveEnds(curves: readonly CurveSample[]): { at: Vec3; label: string }[] {
|
||||
return curves.flatMap((curve) => curve.edges.flatMap((edge, i) => [{ at: edge[0], label: `${curve.name} ${i}` }, { at: edge[edge.length - 1], label: `${curve.name} ${i}` }]));
|
||||
}
|
||||
|
||||
/** The notebook's curves (3D paths, rails, sketches made into wires) drawn in the viewport: they are not solids, so the
|
||||
* model preview does not show them. Display only; the samples are the kernel's (runtime/live_curves.py). */
|
||||
export function CurveLines({ view, curves }: { view: SceneView; curves: CurveSample[] }) {
|
||||
const group = useMemo(() => new THREE.Group(), []);
|
||||
useEffect(() => {
|
||||
view.engine.threeScene.add(group);
|
||||
return () => {
|
||||
group.removeFromParent();
|
||||
view.engine.invalidate();
|
||||
};
|
||||
}, [view, group]);
|
||||
useEffect(() => {
|
||||
for (const child of [...group.children]) {
|
||||
child.removeFromParent();
|
||||
const line = child as THREE.Line;
|
||||
line.geometry.dispose();
|
||||
(line.material as THREE.Material).dispose();
|
||||
}
|
||||
for (const curve of curves) {
|
||||
for (const edge of curve.edges) {
|
||||
const line = new THREE.Line(
|
||||
new THREE.BufferGeometry().setFromPoints(edge.map((p) => new THREE.Vector3(p[0] / 1000, p[1] / 1000, p[2] / 1000))),
|
||||
new THREE.LineBasicMaterial({ color: COLOR }),
|
||||
);
|
||||
line.layers.enable(OVERLAY_LAYER);
|
||||
line.renderOrder = 12;
|
||||
group.add(line);
|
||||
}
|
||||
}
|
||||
view.engine.invalidate();
|
||||
}, [curves, group, view]);
|
||||
|
||||
return (
|
||||
<div className="pointer-events-none absolute inset-0 z-[5] overflow-hidden" data-testid="curve-lines" data-curves={curves.map((c) => c.name).join(",")}>
|
||||
{curves.map((curve) => {
|
||||
const edge = curve.edges[Math.floor(curve.edges.length / 2)];
|
||||
const point = edge[Math.floor(edge.length / 2)];
|
||||
return (
|
||||
<SceneLabel
|
||||
key={curve.name}
|
||||
view={view}
|
||||
getPoint={() => new THREE.Vector3(point[0] / 1000, point[1] / 1000, point[2] / 1000)}
|
||||
offset={[4, -14]}
|
||||
className="rounded border border-sky-500 bg-background/85 px-1 font-mono text-[11px] font-bold text-sky-600"
|
||||
>
|
||||
<span data-curve-label={curve.name}>{curve.name}</span>
|
||||
</SceneLabel>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useMemo } from "react";
|
||||
import { TriangleAlert } from "lucide-react";
|
||||
|
||||
import { describePartial, type PartialModel } from "@/lib/partial";
|
||||
|
||||
/** Says that the model in the viewport is the one before a failing step (a cell failed, so the product was not made): which
|
||||
* step failed and why, and that the steps after it did not run. It stays while the model is partial and goes when the
|
||||
* whole model replaces it; the failing step is marked in the feature tree as well. */
|
||||
export function PartialNotice({ partial, titles }: { partial: PartialModel; titles: ReadonlyMap<string, string> }) {
|
||||
const { title, reason, after } = useMemo(() => describePartial(partial, titles), [partial, titles]);
|
||||
const full = partial.failed.map((cell) => cell.error).filter(Boolean).join("\n");
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
className="pointer-events-auto absolute right-3 top-3 z-20 flex max-w-[min(380px,60%)] flex-col gap-0.5 border-2 border-fail bg-popover px-3 py-1.5 text-[11px] shadow-[4px_4px_0_var(--shadow-hard)]"
|
||||
data-testid="partial-model"
|
||||
title={full || undefined}
|
||||
>
|
||||
<div className="flex items-center gap-2 font-semibold">
|
||||
<TriangleAlert className="size-3.5 shrink-0 text-fail" />
|
||||
<span>{title}</span>
|
||||
</div>
|
||||
<span className="line-clamp-2 text-fail">{reason}</span>
|
||||
<span className="text-muted-foreground">{after ? `${after}; the` : "The"} whole model comes back once it is fixed.</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -47,11 +47,12 @@ export function TagSplits({ view, splits, sceneVersion }: { view: SceneView; spl
|
||||
|
||||
if (!open) return null;
|
||||
return (
|
||||
<div className="pointer-events-auto absolute left-3 top-3 z-20 flex max-w-[min(420px,80%)] flex-col gap-1.5 border-2 border-[var(--focus)] bg-popover px-3 py-2 text-[11px] shadow-[4px_4px_0_var(--shadow-hard)]" data-testid="tag-splits">
|
||||
<div className="pointer-events-auto absolute left-3 top-3 z-20 flex max-h-[min(50%,360px)] max-w-[min(420px,80%)] flex-col gap-1.5 border-2 border-[var(--focus)] bg-popover px-3 py-2 text-[11px] shadow-[4px_4px_0_var(--shadow-hard)]" data-testid="tag-splits">
|
||||
<div className="flex items-center gap-2 font-semibold">
|
||||
<Scissors className="size-3.5 text-[var(--focus)]" />
|
||||
<span>{splits.length === 1 ? "A tagged entity was split" : `${splits.length} tagged entities were split`}</span>
|
||||
</div>
|
||||
<div className="flex min-h-0 flex-col gap-1.5 overflow-y-auto pr-1">
|
||||
{splits.map((row) => (
|
||||
<div key={`${row.op}:${row.tag}:${row.into.join(",")}`} className="flex flex-col gap-1">
|
||||
<span className="text-muted-foreground">
|
||||
@@ -67,7 +68,8 @@ export function TagSplits({ view, splits, sceneVersion }: { view: SceneView; spl
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex gap-2 pt-0.5">
|
||||
</div>
|
||||
<div className="flex shrink-0 gap-2 pt-0.5">
|
||||
<button type="button" className="border border-border px-2 py-0.5 hover:bg-accent" onClick={() => setShown((value) => !value)}>
|
||||
{shown ? "Hide highlight" : "Show highlight"}
|
||||
</button>
|
||||
|
||||
@@ -17,9 +17,35 @@ import { defaultExtrudeDistance, sketchShape } from "@/lib/sketch-scene";
|
||||
import { fitDistanceMm, planeToScreen, screenRay } from "@/lib/sketch-view";
|
||||
import { projectSources } from "@/lib/sketch-edit";
|
||||
import { useSketchEditor } from "@/lib/useSketchEditor";
|
||||
import { planeSegments } from "@/lib/sketch-face";
|
||||
import { disposeObject } from "@/scene/cad-three";
|
||||
import type { PickResult, SceneView } from "@/scene/scene-view";
|
||||
|
||||
/** The model's edges (the line segments the viewport draws them with) in world mm, visible ones only. */
|
||||
function modelEdges(view: SceneView): [[number, number, number], [number, number, number]][] {
|
||||
const root = view.engine.modelRoot;
|
||||
root.updateMatrixWorld(true);
|
||||
const out: [[number, number, number], [number, number, number]][] = [];
|
||||
const a = new THREE.Vector3();
|
||||
const b = new THREE.Vector3();
|
||||
const shown = (object: THREE.Object3D): boolean => {
|
||||
for (let at: THREE.Object3D | null = object; at; at = at.parent) if (!at.visible) return false;
|
||||
return true;
|
||||
};
|
||||
root.traverse((object) => {
|
||||
if (!(object instanceof THREE.LineSegments) || !shown(object)) return;
|
||||
const position = object.geometry.getAttribute("position");
|
||||
const index = object.geometry.getIndex();
|
||||
const count = index ? index.count : position.count;
|
||||
for (let i = 0; i + 1 < count; i += 2) {
|
||||
a.fromBufferAttribute(position, index ? index.getX(i) : i).applyMatrix4(object.matrixWorld).multiplyScalar(1000);
|
||||
b.fromBufferAttribute(position, index ? index.getX(i + 1) : i + 1).applyMatrix4(object.matrixWorld).multiplyScalar(1000);
|
||||
out.push([[a.x, a.y, a.z], [b.x, b.y, b.z]]);
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A sketch being made or edited in the viewport. `plane` is null while the plane is being chosen. */
|
||||
export type SketchSession = { id: number; mode: "new" | "edit"; cell?: string; name: string; plane: PlaneSpec | null; doc: SketchDoc };
|
||||
|
||||
@@ -293,7 +319,9 @@ function SketchEditorView({
|
||||
const modelPoints = useMemo(() => view.modelVertices().map((p) => worldToPlane(plane, p)), [view, plane]);
|
||||
// The sketch being edited is the feature `session.name` (a new one has no feature yet): every other sketch can be projected.
|
||||
const sources = useMemo(() => projectSources(features, editing ? session.name : null), [features, editing, session.name]);
|
||||
const editor = useSketchEditor(session.doc, modelPoints, sources);
|
||||
// The model's edges in the sketch plane (the boundary of the face the sketch is on): drawn faintly and snapped to.
|
||||
const faceEdges = useMemo(() => planeSegments(modelEdges(view), plane), [view, plane]);
|
||||
const editor = useSketchEditor(session.doc, modelPoints, sources, faceEdges);
|
||||
const editorRef = useRef(editor);
|
||||
editorRef.current = editor;
|
||||
const spaceRef = useRef(false);
|
||||
@@ -448,8 +476,9 @@ function SketchEditorView({
|
||||
<SketchToolbar editor={editor} onFit={() => turn.current(true)} onNormal={() => turn.current(false)} />
|
||||
{editor.projectOpen && <SketchProject editor={editor} />}
|
||||
<SketchDrawer editor={editor} plane={planeLabel(plane)} wide={wide} />
|
||||
<div className="pointer-events-auto absolute left-1/2 top-2 z-30 flex -translate-x-1/2 flex-col items-stretch gap-1">
|
||||
<div className="flex flex-wrap items-center gap-2 border-2 border-primary bg-popover px-2 py-1 shadow-[4px_4px_0_var(--shadow-hard)]">
|
||||
{/* The bar and its notes take the pointer; the space between them (beside the hint) is the canvas. */}
|
||||
<div className="pointer-events-none absolute left-1/2 top-2 z-30 flex -translate-x-1/2 flex-col items-stretch gap-1">
|
||||
<div className="pointer-events-auto flex flex-wrap items-center gap-2 border-2 border-primary bg-popover px-2 py-1 shadow-[4px_4px_0_var(--shadow-hard)]">
|
||||
<Pencil className="size-3.5 shrink-0" />
|
||||
<Input
|
||||
aria-label="Sketch name"
|
||||
@@ -481,7 +510,7 @@ function SketchEditorView({
|
||||
</Button>
|
||||
</div>
|
||||
{shown && (
|
||||
<p role="alert" data-testid="sketch-error" className="border-2 border-fail bg-popover px-2 py-1 text-[11px] text-fail">
|
||||
<p role="alert" data-testid="sketch-error" className="pointer-events-auto border-2 border-fail bg-popover px-2 py-1 text-[11px] text-fail">
|
||||
{shown}
|
||||
</p>
|
||||
)}
|
||||
@@ -491,7 +520,7 @@ function SketchEditorView({
|
||||
role={editor.editNote.tone === "fail" ? "alert" : "status"}
|
||||
data-testid="sketch-edit-note"
|
||||
data-tone={editor.editNote.tone}
|
||||
className={`max-w-[460px] self-center border-2 bg-popover px-2 py-1 text-[11px] ${editor.editNote.tone === "fail" ? "border-fail text-fail" : "border-pass text-foreground"}`}
|
||||
className={`pointer-events-auto max-w-[460px] self-center border-2 bg-popover px-2 py-1 text-[11px] ${editor.editNote.tone === "fail" ? "border-fail text-fail" : "border-pass text-foreground"}`}
|
||||
>
|
||||
{editor.editNote.text}
|
||||
</p>
|
||||
@@ -501,7 +530,7 @@ function SketchEditorView({
|
||||
{coords && <span className="ml-2 text-foreground">{coords}</span>}
|
||||
</p>
|
||||
{confirming && (
|
||||
<div className="flex items-center gap-2 border-2 border-focus bg-popover px-2 py-1 text-[11px]" data-testid="sketch-confirm">
|
||||
<div className="pointer-events-auto flex items-center gap-2 border-2 border-focus bg-popover px-2 py-1 text-[11px]" data-testid="sketch-confirm">
|
||||
<span className="flex-1">Discard the unsaved sketch edits?</span>
|
||||
<Button type="button" size="sm" variant="destructive" className="h-6 px-2" onClick={onExit}>
|
||||
discard
|
||||
|
||||
@@ -521,8 +521,37 @@ export function SketchOverlay({
|
||||
);
|
||||
})();
|
||||
|
||||
// "+ anchor" on a spline's curve (a drawing click, or a click in anchor mode, adds an anchor there); "- anchor" on an inner
|
||||
// anchor in anchor mode (a click removes it).
|
||||
const anchorMark = (at: P, remove: boolean, key: string) => {
|
||||
const s = project(at[0], at[1]);
|
||||
if (!s) return null;
|
||||
const ink = remove ? FAIL : NAME;
|
||||
return (
|
||||
<g key={key} data-anchor-mark={remove ? "remove" : "add"} pointerEvents="none">
|
||||
<rect x={s[0] - 7} y={s[1] - 7} width={14} height={14} transform={`rotate(45 ${s[0]} ${s[1]})`} fill={ink} fillOpacity={0.15} stroke={ink} strokeWidth={2.2} />
|
||||
<path d={remove ? `M${s[0] - 4} ${s[1]}H${s[0] + 4}` : `M${s[0] - 4} ${s[1]}H${s[0] + 4}M${s[0]} ${s[1] - 4}V${s[1] + 4}`} stroke={ink} strokeWidth={2} />
|
||||
<text x={s[0] + 14} y={s[1] - 12} fontSize={10} fontWeight={700} fill={ink} stroke={HALO} strokeWidth={3} paintOrder="stroke" style={{ fontFamily: "var(--mono)" }}>
|
||||
{remove ? "- anchor" : "+ anchor"}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
};
|
||||
const modeMark = (() => {
|
||||
const action = editor.anchorMode ? editor.anchorHover : null;
|
||||
if (!action || action.kind === "refuse") return null;
|
||||
if (action.kind === "add") return anchorMark(action.at, false, "mode-add");
|
||||
const at = pts.get(action.anchor);
|
||||
return at ? anchorMark(at, true, "mode-remove") : null;
|
||||
})();
|
||||
const cursorMark = (() => {
|
||||
if (!cursor || tool === "select" || tool === "delete" || tool === "trim" || tool === "extend" || tool === "fillet" || tool === "chamfer") return null;
|
||||
if (cursor.onSpline) return anchorMark([cursor.x, cursor.y], false, "on-curve");
|
||||
if (cursor.onEdge) {
|
||||
// on an edge of the face the sketch is on
|
||||
const e = project(cursor.x, cursor.y);
|
||||
return e ? <rect x={e[0] - 5} y={e[1] - 5} width={10} height={10} fill="none" stroke={NAME} strokeWidth={2} data-snap-edge /> : null;
|
||||
}
|
||||
const s = project(cursor.x, cursor.y);
|
||||
if (!s) return null;
|
||||
return cursor.pointId ? (
|
||||
@@ -536,10 +565,10 @@ export function SketchOverlay({
|
||||
})();
|
||||
|
||||
const dragging = editor.drag !== null;
|
||||
const cursorStyle = moving ? "grabbing" : tool === "select" || tool === "trim" || tool === "extend" || tool === "fillet" || tool === "chamfer" ? (dragging ? "grabbing" : hover ? "pointer" : "default") : "crosshair";
|
||||
const cursorStyle = moving ? "grabbing" : editor.anchorMode && tool === "select" ? (editor.anchorHover?.kind === "add" ? "copy" : editor.anchorHover?.kind === "remove" ? "pointer" : "crosshair") : tool === "select" || tool === "trim" || tool === "extend" || tool === "fillet" || tool === "chamfer" ? (dragging ? "grabbing" : hover ? "pointer" : "default") : "crosshair";
|
||||
|
||||
return (
|
||||
<div ref={wrap} className="absolute inset-0 overflow-hidden outline-none" data-testid="sketch-canvas" tabIndex={-1}>
|
||||
<div ref={wrap} className="absolute inset-0 overflow-hidden outline-none" data-testid="sketch-canvas" data-anchor-mode={editor.anchorMode ?? undefined} tabIndex={-1}>
|
||||
<svg
|
||||
ref={svg}
|
||||
width={size.w}
|
||||
@@ -568,6 +597,10 @@ export function SketchOverlay({
|
||||
y
|
||||
</text>
|
||||
)}
|
||||
{editor.faceEdges.length > 0 && (
|
||||
// the face the sketch is on (and every model edge in its plane): what drawing snaps to
|
||||
<path d={editor.faceEdges.map((seg) => polyline(seg)).join(" ")} stroke={NAME} strokeWidth={1.6} opacity={0.55} fill="none" pointerEvents="none" data-face-edges={editor.faceEdges.length} />
|
||||
)}
|
||||
{loops.map((loop) => {
|
||||
const wireMode = doc.output === "wire"; // a wire sketch fills the loop it makes the wire of, and has no holes
|
||||
const isOuter = wireMode ? loop.key === editor.wire?.key : loop.key === choice.outer;
|
||||
@@ -656,6 +689,7 @@ export function SketchOverlay({
|
||||
{labelNodes}
|
||||
{preview}
|
||||
{cursorMark}
|
||||
{modeMark}
|
||||
</svg>
|
||||
{boxNode}
|
||||
{entryNode}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Construction, Layers, Maximize, Magnet, Undo2, Redo2, ScanLine, WandSparkles } from "lucide-react";
|
||||
import { Construction, Layers, Maximize, Magnet, Undo2, Redo2, ScanLine, Spline, WandSparkles } from "lucide-react";
|
||||
|
||||
import { CONSTRAINT_INFO, isDimensional } from "@/lib/sketch";
|
||||
import type { SketchEditor } from "@/lib/useSketchEditor";
|
||||
@@ -32,6 +32,11 @@ export function SketchToolbar({ editor, onFit, onNormal }: { editor: SketchEdito
|
||||
<span className="flex-1">project</span>
|
||||
<Tip>J</Tip>
|
||||
</button>
|
||||
<button type="button" title="Anchor mode (Shift+A, with a B-spline picked): a click on its curve adds an anchor, a click on an inner anchor removes it (SDK insert/remove_spline_anchor_rsketch); Esc leaves" aria-label="Anchor mode" aria-pressed={editor.anchorMode !== null} data-tool="anchors" onClick={editor.toggleAnchorMode} className={toggle}>
|
||||
<Spline className="size-3.5 shrink-0" />
|
||||
<span className="flex-1">anchors</span>
|
||||
<Tip>⇧A</Tip>
|
||||
</button>
|
||||
<button type="button" title="Construction geometry (X): toggles the selected lines, or what you draw next" aria-label="Construction" aria-pressed={editor.construction} onClick={editor.toggleConstruction} className={toggle}>
|
||||
<Construction className="size-3.5 shrink-0" />
|
||||
<span className="flex-1">construct</span>
|
||||
|
||||
@@ -9,7 +9,7 @@ export const TOOLS: { id: Tool; label: string; key: string; icon: typeof Slash }
|
||||
{ id: "line", label: "Line (chained; Esc ends)", key: "L", icon: Slash },
|
||||
{ id: "circle", label: "Circle: centre, then radius", key: "C", icon: Circle },
|
||||
{ id: "arc", label: "Arc: centre, start, end (counter-clockwise)", key: "A", icon: Spline },
|
||||
{ id: "spline", label: "Spline (pen): click anchors, press and drag for handles; Enter makes it, a click on the first anchor closes it (SDK add_bspline_rsketch, anchor form)", key: "B", icon: Waves },
|
||||
{ id: "spline", label: "Spline (pen): click anchors, press and drag for handles, click another spline's curve to add an anchor there; Enter makes it, a click on the first anchor closes it (SDK add_bspline_rsketch, anchor form)", key: "B", icon: Waves },
|
||||
{ id: "delete", label: "Delete", key: "D", icon: Trash2 },
|
||||
{ id: "trim", label: "Trim: cut an entity back to its neighbours (SDK trim_rsketch)", key: "T", icon: Scissors },
|
||||
{ id: "extend", label: "Extend: grow a line's end to the next entity (SDK extend_rsketch)", key: "E", icon: UnfoldHorizontal },
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { addSegment, arcPoints, dropLast, gridStep, onGrid, pathEnd, pickSnap, pointFor, rayOnPlane, type CurveDoc, type DrawPlane, type SnapCandidate } from "./curve3d";
|
||||
|
||||
const XY: DrawPlane = { name: "XY", workplane: false, origin: [0, 0, 0], x_axis: [1, 0, 0], y_axis: [0, 1, 0], normal: [0, 0, 1] };
|
||||
const WP: DrawPlane = { name: "wp", workplane: true, origin: [0, 0, 10], x_axis: [1, 0, 0], y_axis: [0, 0, 1], normal: [0, -1, 0] };
|
||||
const close = (a: readonly number[], b: readonly number[]) => a.forEach((v, i) => expect(v).toBeCloseTo(b[i], 9));
|
||||
|
||||
describe("drawing a 3D curve", () => {
|
||||
it("snaps to the nearest candidate, a vertex before a grid point", () => {
|
||||
const c = (kind: SnapCandidate["kind"], x: number, priority: number): SnapCandidate => ({ kind, at: [x, 0, 0], screen: [x, 0], label: kind, priority });
|
||||
expect(pickSnap([c("grid", 2, 3), c("vertex", 5, 0)], [2, 0])?.kind).toBe("vertex");
|
||||
expect(pickSnap([c("grid", 2, 3)], [40, 0])).toBeNull();
|
||||
});
|
||||
|
||||
it("puts the pointer on the drawing plane and its grid", () => {
|
||||
close(rayOnPlane([0, 0, 10], [0, 0, -1], XY)!, [0, 0, 0]);
|
||||
expect(rayOnPlane([0, 0, 10], [1, 0, 0], XY)).toBeNull();
|
||||
expect(gridStep(3.2)).toBe(5);
|
||||
close(onGrid(WP, [1.4, 0, 12.6], 1), [1, 0, 13]);
|
||||
});
|
||||
|
||||
it("draws an arc through its middle point", () => {
|
||||
const points = arcPoints([1, 0, 0], [0, 1, 0], [-1, 0, 0], 4);
|
||||
close(points[2], [0, 1, 0]);
|
||||
points.forEach((p) => expect(Math.hypot(...p)).toBeCloseTo(1, 9));
|
||||
});
|
||||
|
||||
it("keeps a workplane point on its workplane and a vertex by its entity", () => {
|
||||
let doc: CurveDoc = { points: [], curves: [] };
|
||||
const a = pointFor(doc, WP, [3, 0, 14], null);
|
||||
doc = a.doc;
|
||||
expect(doc.points[0]).toEqual({ id: "p1", at: [3, 0, 14], on: "wp", uv: [3, 4] });
|
||||
const b = pointFor(doc, XY, [5, 5, 5], { kind: "vertex", at: [5, 5, 5], screen: [0, 0], entityId: "entity/p/vertex/vertex_2", label: "", priority: 0 });
|
||||
doc = addSegment(b.doc, "line", [a.id, b.id]);
|
||||
expect(doc.points[1].entity_id).toBe("entity/p/vertex/vertex_2");
|
||||
expect(pathEnd(doc)).toBe("p2");
|
||||
expect(dropLast(doc)).toEqual({ points: [doc.points[0]], curves: [] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,183 @@
|
||||
/** Drawing a 3D curve in the viewport: the document the `curve` feature takes (points in space, on workplanes or at model
|
||||
* vertices; lines, arcs and splines that follow one another), what the pointer snaps to, and the shape drawn while
|
||||
* drawing. Pure: no React, no three.js. World coordinates are CAD mm, Z up. */
|
||||
|
||||
import { add, cross, dot, length, scale, sub, unit, type Vec3 } from "@/lib/sketch-plane";
|
||||
|
||||
export type CurveKind = "line" | "arc" | "spline";
|
||||
|
||||
/** A point of the document: `at` (world mm) always (a hint for vertices and workplane points), `on` + `uv` for a point
|
||||
* drawn on a workplane variable, `entity_id` for one snapped to a model vertex (the server names it by its reference). */
|
||||
export type CurvePoint = { id: string; at: Vec3; on?: string; uv?: [number, number]; entity_id?: string };
|
||||
export type CurveSegment = { id: string; kind: CurveKind; points: string[] };
|
||||
export type CurveDoc = { points: CurvePoint[]; curves: CurveSegment[] };
|
||||
|
||||
/** A drawing plane: a named plane or a workplane, its frame in world mm. */
|
||||
export type DrawPlane = { name: string; workplane: boolean; origin: Vec3; x_axis: Vec3; y_axis: Vec3; normal: Vec3 };
|
||||
|
||||
/** Something the pointer can snap to. `screen` is where it is drawn (CSS px), `priority` breaks ties (lower wins). */
|
||||
export type SnapCandidate = {
|
||||
kind: "vertex" | "midpoint" | "point" | "origin" | "grid";
|
||||
at: Vec3;
|
||||
screen: [number, number];
|
||||
entityId?: string;
|
||||
pointId?: string;
|
||||
/** For a workplane's origin: the workplane, so the point is kept on it. */
|
||||
workplane?: string;
|
||||
label: string;
|
||||
priority: number;
|
||||
};
|
||||
|
||||
export const SNAP_PX = 14;
|
||||
|
||||
/** The candidate nearest the pointer within `radius` px (ties by priority), or null. */
|
||||
export function pickSnap(candidates: readonly SnapCandidate[], pointer: [number, number], radius = SNAP_PX): SnapCandidate | null {
|
||||
let best: SnapCandidate | null = null;
|
||||
let bestScore = Infinity;
|
||||
for (const c of candidates) {
|
||||
const d = Math.hypot(c.screen[0] - pointer[0], c.screen[1] - pointer[1]);
|
||||
if (d > radius) continue;
|
||||
const score = d + c.priority * 4; // a vertex 4 px further still beats a grid point
|
||||
if (score < bestScore) {
|
||||
best = c;
|
||||
bestScore = score;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Where a ray meets the plane, or null when it runs along it. */
|
||||
export function rayOnPlane(origin: Vec3, direction: Vec3, plane: DrawPlane): Vec3 | null {
|
||||
const denom = dot(direction, plane.normal);
|
||||
if (Math.abs(denom) < 1e-9) return null;
|
||||
const t = dot(sub(plane.origin, origin), plane.normal) / denom;
|
||||
return t < 0 ? null : add(origin, scale(direction, t));
|
||||
}
|
||||
|
||||
/** The plane coordinates (u, v) of a world point (projected onto the plane). */
|
||||
export function planeUV(plane: DrawPlane, p: Vec3): [number, number] {
|
||||
const d = sub(p, plane.origin);
|
||||
return [dot(d, plane.x_axis), dot(d, plane.y_axis)];
|
||||
}
|
||||
|
||||
export function planePoint(plane: DrawPlane, u: number, v: number): Vec3 {
|
||||
return add(plane.origin, add(scale(plane.x_axis, u), scale(plane.y_axis, v)));
|
||||
}
|
||||
|
||||
/** A grid step for the plane: 1, 2 or 5 times a power of ten mm, about `targetMm` across. */
|
||||
export function gridStep(targetMm: number): number {
|
||||
const power = 10 ** Math.floor(Math.log10(Math.max(targetMm, 1e-6)));
|
||||
for (const k of [1, 2, 5, 10]) if (k * power >= targetMm) return k * power;
|
||||
return 10 * power;
|
||||
}
|
||||
|
||||
/** The point snapped to the plane's grid (in its own u, v). */
|
||||
export function onGrid(plane: DrawPlane, p: Vec3, step: number): Vec3 {
|
||||
const [u, v] = planeUV(plane, p);
|
||||
return planePoint(plane, Math.round(u / step) * step, Math.round(v / step) * step);
|
||||
}
|
||||
|
||||
/** Points along a circle arc through a, m, b (world mm); the straight segment when they are (nearly) on one line. */
|
||||
export function arcPoints(a: Vec3, m: Vec3, b: Vec3, steps = 48): Vec3[] {
|
||||
const ab = sub(b, a);
|
||||
const am = sub(m, a);
|
||||
const n = cross(ab, am);
|
||||
const nn = dot(n, n);
|
||||
if (nn < 1e-12 * Math.max(dot(ab, ab), 1) ** 2) return [a, b];
|
||||
// circumcentre of the triangle a, m, b
|
||||
const center = add(a, scale(add(scale(cross(n, ab), dot(am, am)), scale(cross(am, n), dot(ab, ab))), 1 / (2 * nn)));
|
||||
const ra = sub(a, center);
|
||||
const radius = length(ra);
|
||||
const e1 = unit(ra)!;
|
||||
const e2 = unit(cross(unit(n)!, e1))!;
|
||||
const angle = (p: Vec3) => {
|
||||
const d = sub(p, center);
|
||||
const t = Math.atan2(dot(d, e2), dot(d, e1));
|
||||
return t < 0 ? t + 2 * Math.PI : t;
|
||||
};
|
||||
const tm = angle(m);
|
||||
const tb = angle(b);
|
||||
// a is at 0; go the way that passes m
|
||||
const sweep = tm <= tb ? tb : tb - 2 * Math.PI;
|
||||
return Array.from({ length: steps + 1 }, (_, i) => {
|
||||
const t = (sweep * i) / steps;
|
||||
return add(center, add(scale(e1, radius * Math.cos(t)), scale(e2, radius * Math.sin(t))));
|
||||
});
|
||||
}
|
||||
|
||||
/** Points along a smooth curve through `points` (centripetal Catmull-Rom): what a spline looks like while it is drawn
|
||||
* (the kernel's interpolation is close to it; the curve made is the kernel's). */
|
||||
export function splinePoints(points: readonly Vec3[], perSpan = 16): Vec3[] {
|
||||
if (points.length < 3) return [...points];
|
||||
const out: Vec3[] = [];
|
||||
const at = (i: number) => points[Math.max(0, Math.min(points.length - 1, i))];
|
||||
for (let i = 0; i < points.length - 1; i++) {
|
||||
const p0 = i === 0 ? sub(scale(at(0), 2), at(1)) : at(i - 1);
|
||||
const p1 = at(i);
|
||||
const p2 = at(i + 1);
|
||||
const p3 = i + 2 >= points.length ? sub(scale(at(points.length - 1), 2), at(points.length - 2)) : at(i + 2);
|
||||
const t0 = 0;
|
||||
const t1 = t0 + Math.sqrt(Math.max(length(sub(p1, p0)), 1e-9));
|
||||
const t2 = t1 + Math.sqrt(Math.max(length(sub(p2, p1)), 1e-9));
|
||||
const t3 = t2 + Math.sqrt(Math.max(length(sub(p3, p2)), 1e-9));
|
||||
for (let k = 0; k < perSpan; k++) {
|
||||
const t = t1 + ((t2 - t1) * k) / perSpan;
|
||||
const lerp = (a: Vec3, b: Vec3, ta: number, tb: number) => add(scale(a, (tb - t) / (tb - ta)), scale(b, (t - ta) / (tb - ta)));
|
||||
const a1 = lerp(p0, p1, t0, t1);
|
||||
const a2 = lerp(p1, p2, t1, t2);
|
||||
const a3 = lerp(p2, p3, t2, t3);
|
||||
const b1 = lerp(a1, a2, t0, t2);
|
||||
const b2 = lerp(a2, a3, t1, t3);
|
||||
out.push(lerp(b1, b2, t1, t2));
|
||||
}
|
||||
}
|
||||
out.push(points[points.length - 1]);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The polyline a segment is drawn as. */
|
||||
export function segmentPoints(kind: CurveKind, points: readonly Vec3[]): Vec3[] {
|
||||
if (kind === "arc" && points.length === 3) return arcPoints(points[0], points[1], points[2]);
|
||||
if (kind === "spline") return splinePoints(points);
|
||||
return [...points];
|
||||
}
|
||||
|
||||
/** The world point of a document point. */
|
||||
export const pointAt = (doc: CurveDoc, id: string): Vec3 | null => doc.points.find((p) => p.id === id)?.at ?? null;
|
||||
|
||||
/** The next free point id ("p1", "p2" ...) or curve id ("c1" ...). */
|
||||
export function nextId(taken: readonly string[], prefix: string): string {
|
||||
let n = 1;
|
||||
while (taken.includes(`${prefix}${n}`)) n++;
|
||||
return `${prefix}${n}`;
|
||||
}
|
||||
|
||||
/** The document's point for a place the pointer chose: the snapped session point itself, a model vertex (named later by
|
||||
* the server), a point on a workplane (u, v: it follows the workplane), or a point in space. */
|
||||
export function pointFor(doc: CurveDoc, plane: DrawPlane, at: Vec3, snap: SnapCandidate | null): { doc: CurveDoc; id: string } {
|
||||
if (snap?.pointId) return { doc, id: snap.pointId };
|
||||
const id = nextId(doc.points.map((p) => p.id), "p");
|
||||
let point: CurvePoint = { id, at };
|
||||
if (snap?.kind === "vertex" && snap.entityId) point = { id, at, entity_id: snap.entityId };
|
||||
else if (snap?.kind === "origin" && snap.workplane) point = { id, at, on: snap.workplane, uv: [0, 0] };
|
||||
else if (plane.workplane && (!snap || snap.kind === "grid")) point = { id, at, on: plane.name, uv: planeUV(plane, at) };
|
||||
return { doc: { ...doc, points: [...doc.points, point] }, id };
|
||||
}
|
||||
|
||||
/** The document with one more segment from the path's end through `ids`, and the points it no longer uses dropped. */
|
||||
export function addSegment(doc: CurveDoc, kind: CurveKind, ids: string[]): CurveDoc {
|
||||
const id = nextId(doc.curves.map((c) => c.id), "c");
|
||||
return { ...doc, curves: [...doc.curves, { id, kind, points: ids }] };
|
||||
}
|
||||
|
||||
/** The path's last point id (where the next segment starts), or null before the first segment. */
|
||||
export const pathEnd = (doc: CurveDoc): string | null => doc.curves.at(-1)?.points.at(-1) ?? null;
|
||||
|
||||
/** The document without its last segment, and without the points only that segment used. */
|
||||
export function dropLast(doc: CurveDoc): CurveDoc {
|
||||
const curves = doc.curves.slice(0, -1);
|
||||
const used = new Set(curves.flatMap((c) => c.points));
|
||||
const first = doc.curves[0]?.points[0];
|
||||
if (curves.length === 0 && first) used.add(first);
|
||||
return { points: doc.points.filter((p) => used.has(p.id)), curves };
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { describePartial, parsePartial, samePartial } from "./partial";
|
||||
|
||||
const ROUNDED = {
|
||||
failed: [{ cell: "bkHC", name: "rounded", status: "exception", error: "SimpleCADError: fillet_rsolid: the radius is too large" }],
|
||||
skipped: ["lEQa"],
|
||||
shown: ["bore"],
|
||||
};
|
||||
|
||||
describe("parsePartial", () => {
|
||||
it("reads what the kernel sends and drops what is not a failure", () => {
|
||||
expect(parsePartial(ROUNDED)).toEqual(ROUNDED);
|
||||
expect(parsePartial(null)).toBeNull();
|
||||
expect(parsePartial(undefined)).toBeNull();
|
||||
expect(parsePartial({ failed: [], skipped: [], shown: [] })).toBeNull();
|
||||
expect(parsePartial({ failed: [{ name: "no cell id" }] })).toBeNull();
|
||||
expect(parsePartial({ failed: [{ cell: "x" }] })).toEqual({ failed: [{ cell: "x", name: "x", status: "exception", error: "" }], skipped: [], shown: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("describePartial", () => {
|
||||
it("names the failing step, why, and what did not run", () => {
|
||||
const partial = parsePartial(ROUNDED)!;
|
||||
expect(describePartial(partial)).toEqual({
|
||||
title: "The model before rounded",
|
||||
reason: "rounded failed: SimpleCADError: fillet_rsolid: the radius is too large",
|
||||
after: "1 later step did not run",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the notebook's title for a step without a feature header, and says when it was stopped", () => {
|
||||
const partial = parsePartial({ failed: [{ cell: "c1", name: "c1", status: "interrupted", error: "" }], skipped: ["c2", "c3"], shown: [] })!;
|
||||
const told = describePartial(partial, new Map([["c1", "slow loft"]]));
|
||||
expect(told.title).toBe("The model before slow loft");
|
||||
expect(told.reason).toBe("slow loft was stopped");
|
||||
expect(told.after).toBe("2 later steps did not run");
|
||||
});
|
||||
|
||||
it("keeps a long error to one short line", () => {
|
||||
const partial = parsePartial({ failed: [{ cell: "c", name: "c", status: "exception", error: `E: ${"x ".repeat(200)}\nmore` }] })!;
|
||||
expect(describePartial(partial).reason.length).toBeLessThan(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("samePartial", () => {
|
||||
it("is the same failure when the same cells fail the same way, whatever is shown", () => {
|
||||
const a = parsePartial(ROUNDED);
|
||||
expect(samePartial(a, parsePartial({ ...ROUNDED, shown: ["other"] }))).toBe(true);
|
||||
expect(samePartial(a, parsePartial({ ...ROUNDED, failed: [{ ...ROUNDED.failed[0], error: "another" }] }))).toBe(false);
|
||||
expect(samePartial(a, null)).toBe(false);
|
||||
expect(samePartial(null, null)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
/** The model before a failing step: a `preview` envelope's `partial` (`simplecadapi.runtime.live.preview_product`).
|
||||
*
|
||||
* A cell failed, so the product was not made; the kernel previewed what the cells before it made instead (the body the
|
||||
* failing feature was applied to) and says so. `null` when the model is the whole product. */
|
||||
|
||||
export type FailedCell = {
|
||||
/** The marimo cell id (the notebook's cells carry the same ids). */
|
||||
cell: string;
|
||||
/** The feature the cell makes, else the cell's name. */
|
||||
name: string;
|
||||
/** marimo's run state: `exception`, `interrupted` or `marimo-error`. */
|
||||
status: string;
|
||||
/** `Type: message`, cut short; empty when marimo kept none. */
|
||||
error: string;
|
||||
};
|
||||
|
||||
export type PartialModel = {
|
||||
/** The failing steps (cells downstream of no other failed cell), in notebook order. */
|
||||
failed: FailedCell[];
|
||||
/** The ids of the cells after them that did not run. */
|
||||
skipped: string[];
|
||||
/** The bodies (or the product) on screen. */
|
||||
shown: string[];
|
||||
};
|
||||
|
||||
const strings = (value: unknown): string[] => (Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : []);
|
||||
|
||||
export function parsePartial(value: unknown): PartialModel | null {
|
||||
if (!value || typeof value !== "object") return null;
|
||||
const row = value as Record<string, unknown>;
|
||||
const failed = (Array.isArray(row.failed) ? row.failed : [])
|
||||
.filter((item): item is Record<string, unknown> => !!item && typeof item === "object" && typeof item.cell === "string")
|
||||
.map((item) => ({
|
||||
cell: String(item.cell),
|
||||
name: typeof item.name === "string" && item.name ? item.name : String(item.cell),
|
||||
status: typeof item.status === "string" ? item.status : "exception",
|
||||
error: typeof item.error === "string" ? item.error : "",
|
||||
}));
|
||||
if (!failed.length) return null;
|
||||
return { failed, skipped: strings(row.skipped), shown: strings(row.shown) };
|
||||
}
|
||||
|
||||
/** What the notice says: the step the model stops before, why, and what did not run. *titles* maps a cell id to the
|
||||
* title the notebook shows for it (a step without a feature header is told by its title). */
|
||||
export function describePartial(partial: PartialModel, titles: ReadonlyMap<string, string> = new Map()): { title: string; reason: string; after: string } {
|
||||
const [first, ...rest] = partial.failed;
|
||||
const name = (cell: FailedCell) => titles.get(cell.cell) || cell.name;
|
||||
const what = first.status === "interrupted" ? "was stopped" : first.status === "marimo-error" ? "cannot run" : "failed";
|
||||
const reason = first.error ? `${name(first)} ${what}: ${firstLine(first.error)}` : `${name(first)} ${what}`;
|
||||
const later = partial.skipped.length + rest.length;
|
||||
const after = [
|
||||
rest.length ? `${rest.map(name).join(", ")} failed too` : "",
|
||||
later ? `${later} later ${later === 1 ? "step" : "steps"} did not run` : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("; ");
|
||||
return { title: `The model before ${name(first)}`, reason, after };
|
||||
}
|
||||
|
||||
/** An error kept to one short line (the kernel already put the SDK's errors as "Type: operation: what happened"). */
|
||||
function firstLine(error: string): string {
|
||||
const text = error.replace(/\s+/g, " ").trim();
|
||||
return text.length > 180 ? `${text.slice(0, 179)}…` : text;
|
||||
}
|
||||
|
||||
/** Whether two partial states say the same thing (the log is told once per failure, not per slider tick). */
|
||||
export function samePartial(a: PartialModel | null, b: PartialModel | null): boolean {
|
||||
return JSON.stringify(a?.failed.map((cell) => [cell.cell, cell.error]) ?? null) === JSON.stringify(b?.failed.map((cell) => [cell.cell, cell.error]) ?? null);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { emptyDoc, normalizeDoc, wireProfiles, type SketchDoc, type SolveResult } from "@/lib/sketch";
|
||||
import { addPenSpline, anchorRoles, bezierPath, handlePoints, isAnchorSpline, isSmooth, mirrorHandle, penPoles, shownHandles, smoothAnchors } from "@/lib/sketch-anchors";
|
||||
import { addPenSpline, anchorAction, anchorRoles, bezierPath, curveAt, handlePoints, isAnchorSpline, isSmooth, mirrorHandle, penPoles, shownHandles, smoothAnchors } from "@/lib/sketch-anchors";
|
||||
import { convertSplineRequest, insertAnchorRequest, removeAnchorRequest } from "@/lib/sketch-edit";
|
||||
|
||||
const opts = { auto: false, construction: false };
|
||||
@@ -109,3 +109,28 @@ describe("anchor edits are SDK requests; a wire sketch chooses any profile", ()
|
||||
expect(wireProfiles(solve)).toEqual([{ index: 0, key: "l0+l1", closed: false, entities: ["l1", "l0"] }]);
|
||||
});
|
||||
});
|
||||
|
||||
/** Two spans along the x axis (anchors at 0, 15 and 30; the handles on the axis too), so its path is the x axis from 0 to 30. */
|
||||
function straight(): SketchDoc {
|
||||
return addPenSpline(emptyDoc(), [{ spot: { x: 0, y: 0 }, handle: [5, 0] }, { spot: { x: 15, y: 0 }, handle: [5, 0] }, { spot: { x: 30, y: 0 }, handle: [5, 0] }], false, opts, at)!.doc;
|
||||
}
|
||||
|
||||
describe("adding and removing anchors by clicking", () => {
|
||||
it("a place on an anchor-form curve is found within the pick distance", () => {
|
||||
const doc = straight();
|
||||
expect(curveAt(doc, null, [7, 0.5], 1)).toEqual({ spline: "s1", at: [7, 0] });
|
||||
expect(curveAt(doc, null, [7, 3], 1)).toBeNull();
|
||||
// a control-point B-spline offers no place for an anchor
|
||||
const old: SketchDoc = { ...doc, entities: [{ ...doc.entities[0], knots: [0, 0.3, 0.6, 1], multiplicities: [4, 1, 2, 4] }] };
|
||||
expect(curveAt(old, null, [7, 0.5], 1)).toBeNull();
|
||||
});
|
||||
|
||||
it("anchor mode: an inner anchor is removed, the curve gets an anchor, an end anchor or a handle is refused", () => {
|
||||
const doc = straight();
|
||||
const ids = doc.entities[0].control_points!;
|
||||
expect(anchorAction(doc, null, [15, 0], 1, ids[3])).toEqual({ kind: "remove", spline: "s1", anchor: ids[3] });
|
||||
expect(anchorAction(doc, null, [22, 0.2], 1, null)).toEqual({ kind: "add", spline: "s1", at: [22, 0] });
|
||||
expect(anchorAction(doc, null, [0, 0], 1, ids[0])).toMatchObject({ kind: "refuse" });
|
||||
expect(anchorAction(doc, null, [9, 5], 1, null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
* anchor smooth while one of its handles is dragged. A B-spline in another form (control points, an old file) has no anchors
|
||||
* here: it shows its control polygon and offers `convert_spline_to_anchors_rsketch`. */
|
||||
|
||||
import { ensurePoint, nextId, type DrawOptions, type SEntity, type SketchDoc, type Spot } from "@/lib/sketch";
|
||||
import { ensurePoint, nextId, solvedPoints, splinePath, type DrawOptions, type SEntity, type SketchDoc, type SolveResult, type Spot } from "@/lib/sketch";
|
||||
|
||||
type P = [number, number];
|
||||
|
||||
@@ -71,6 +71,47 @@ export function handlePoints(roles: Map<string, AnchorRole>): Set<string> {
|
||||
return new Set([...roles].filter(([, r]) => r.kind === "handle").map(([id]) => id));
|
||||
}
|
||||
|
||||
/** The place on an anchor-form spline's curve nearest `pos`, within `tol` (sketch units): where a click adds an anchor. The
|
||||
* curve is the SDK's samples of the last solve; the SDK puts the anchor at the curve point nearest the click. */
|
||||
export function curveAt(doc: SketchDoc, solve: SolveResult | null, pos: readonly [number, number], tol: number): { spline: string; at: P } | null {
|
||||
const pts = solvedPoints(doc, solve);
|
||||
let best: { spline: string; at: P; d: number } | null = null;
|
||||
for (const e of doc.entities) {
|
||||
if (!isAnchorSpline(e)) continue;
|
||||
const path = splinePath(e, pts, solve);
|
||||
for (let i = 0; i + 1 < path.length; i++) {
|
||||
const [a, b] = [path[i], path[i + 1]];
|
||||
const dx = b[0] - a[0];
|
||||
const dy = b[1] - a[1];
|
||||
const len2 = dx * dx + dy * dy;
|
||||
const t = len2 > 0 ? Math.min(1, Math.max(0, ((pos[0] - a[0]) * dx + (pos[1] - a[1]) * dy) / len2)) : 0;
|
||||
const at: P = [a[0] + t * dx, a[1] + t * dy];
|
||||
const d = Math.hypot(pos[0] - at[0], pos[1] - at[1]);
|
||||
if (d <= tol && (!best || d < best.d)) best = { spline: e.id, at, d };
|
||||
}
|
||||
}
|
||||
return best ? { spline: best.spline, at: best.at } : null;
|
||||
}
|
||||
|
||||
/** What a click in anchor mode does where it lands: remove the inner anchor under it (`hit`: a point id within reach), else add
|
||||
* an anchor on the curve under it, else nothing. End anchors and handles are not removed (the reason is the `refuse` text). */
|
||||
export type AnchorAction = { kind: "add"; spline: string; at: P } | { kind: "remove"; spline: string; anchor: string } | { kind: "refuse"; text: string } | null;
|
||||
|
||||
export function anchorAction(doc: SketchDoc, solve: SolveResult | null, pos: readonly [number, number], tol: number, hit: string | null, roles: Map<string, AnchorRole> = anchorRoles(doc)): AnchorAction {
|
||||
const role = hit ? roles.get(hit) : undefined;
|
||||
if (hit && role?.kind === "anchor" && !role.end) {
|
||||
const e = doc.entities.find((x) => x.id === role.spline);
|
||||
const closedSeam = e?.start === hit; // the seam of a closed spline is its start and end
|
||||
if (!closedSeam) return { kind: "remove", spline: role.spline, anchor: hit };
|
||||
return { kind: "refuse", text: `${hit} is where ${role.spline} starts and ends: it cannot be removed` };
|
||||
}
|
||||
if (hit && role?.kind === "anchor") return { kind: "refuse", text: `${hit} is an end of ${role.spline}: an end anchor cannot be removed (trim the spline instead)` };
|
||||
const on = curveAt(doc, solve, pos, tol);
|
||||
if (on) return { kind: "add", spline: on.spline, at: on.at };
|
||||
if (hit && role?.kind === "handle") return { kind: "refuse", text: `${hit} is a handle of ${role.spline}: click its anchor ${role.anchor} to remove the anchor` };
|
||||
return null;
|
||||
}
|
||||
|
||||
// -- the drawn path -------------------------------------------------------------------------------------------------------
|
||||
|
||||
/** Points along a chain of cubic Bezier spans given by their control points [A0, out0, in1, A1, ...]. */
|
||||
|
||||
@@ -217,7 +217,9 @@ export function addSpline(doc: SketchDoc, spots: readonly Spot[], opts: DrawOpti
|
||||
|
||||
const round = (v: number) => Math.round(v * 1e4) / 1e4;
|
||||
|
||||
export type Spot = { x: number; y: number; pointId?: string };
|
||||
/** Where a drawing click lands: an existing point (`pointId`), or a place on the curve of an anchor-form B-spline
|
||||
* (`onSpline`: the SDK inserts an anchor there first, and the click uses it), or a free / grid position. */
|
||||
export type Spot = { x: number; y: number; pointId?: string; onSpline?: string; onEdge?: boolean };
|
||||
|
||||
/** The point a spot names (an existing one) or a new one at its position. */
|
||||
export function ensurePoint(doc: SketchDoc, spot: Spot): { doc: SketchDoc; id: string; created: boolean } {
|
||||
|
||||
@@ -72,11 +72,15 @@ import {
|
||||
type End,
|
||||
} from "@/lib/sketch-edit";
|
||||
import { typedFields, typedTarget, type TypedDims } from "@/lib/sketch-typed";
|
||||
import { addPenSpline, anchorRoles, handlePoints, isAnchorSpline, isSmooth, mirrorHandle, shownHandles, smoothAnchors } from "@/lib/sketch-anchors";
|
||||
import { edgeSnap, type Segment } from "@/lib/sketch-face";
|
||||
import { addPenSpline, anchorAction, anchorRoles, curveAt, handlePoints, isAnchorSpline, mirrorHandle, shownHandles, smoothAnchors, type AnchorAction } from "@/lib/sketch-anchors";
|
||||
|
||||
/** How near the pointer (screen pixels) must be to a point or a curve to snap to it or pick it. */
|
||||
const PICK_PX = 16;
|
||||
const DRAW_TOOLS = new Set(["point", "line", "circle", "arc", "spline"]);
|
||||
/** The drawing tools whose click on the curve of a B-spline in anchor form adds an anchor there and uses it (a point on the
|
||||
* curve, a line's end on it, a pen path through it). */
|
||||
const ON_CURVE_TOOLS = new Set(["point", "line", "spline"]);
|
||||
|
||||
export type Tool = "select" | "point" | "line" | "circle" | "arc" | "spline" | "delete" | "trim" | "extend" | "fillet" | "chamfer";
|
||||
/** The corner value box (fillet radius / chamfer distance) open at a corner. */
|
||||
@@ -87,8 +91,9 @@ const EDIT_TOOLS: ReadonlySet<Tool> = new Set<Tool>(["trim", "extend", "fillet",
|
||||
/** The spline draft is a pen path: its anchors and, for each, the out-handle a drag pulled out (an offset; null: none). */
|
||||
export type SplineDraft = { tool: "spline"; points: Spot[]; handles: ([number, number] | null)[] };
|
||||
export type Draft = { tool: "line"; from: Spot } | { tool: "circle"; center: Spot } | { tool: "arc"; center: Spot; start?: Spot } | SplineDraft | null;
|
||||
/** A drag of points. `lead` is the point that snaps (an anchor; its handles follow it); `mirror` keeps a smooth anchor smooth
|
||||
* while one of its handles is dragged: the opposite handle turns with it and keeps its own length. */
|
||||
/** A drag of points. `lead` is the point that snaps (an anchor; its handles follow it). A dragged handle moves alone (each
|
||||
* side of an anchor has its own direction and pull); `mirror` is the opposite handle of its anchor, which turns into line with
|
||||
* it, keeping its own length, while Shift is held. */
|
||||
export type Drag = {
|
||||
ids: string[];
|
||||
origin: Record<string, [number, number]>;
|
||||
@@ -109,13 +114,17 @@ export type KeyOutcome = "handled" | "leave" | "ignored";
|
||||
/** The state and the behaviour of the sketch editor, apart from where it is drawn: the document with its undo history,
|
||||
* the live solve, loops and the chosen profile, the tools and their drafts, drag with a temporary fix, the value box.
|
||||
* The overlay feeds it pointer events already mapped into the plane. */
|
||||
export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [number, number][] = [], projectFrom: readonly string[] = []) {
|
||||
export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [number, number][] = [], projectFrom: readonly string[] = [], faceEdges: readonly Segment[] = []) {
|
||||
const [doc, setDoc] = useState<SketchDoc>(initial);
|
||||
const [tool, setTool] = useState<Tool>("select");
|
||||
const [selection, setSelection] = useState<string[]>([]);
|
||||
const [highlight, setHighlight] = useState<string | null>(null);
|
||||
const [draft, setDraft] = useState<Draft>(null);
|
||||
const [cursor, setCursor] = useState<{ x: number; y: number; pointId?: string } | null>(null);
|
||||
const [cursor, setCursor] = useState<{ x: number; y: number; pointId?: string; onSpline?: string; onEdge?: boolean } | null>(null);
|
||||
/** Anchor mode (Shift+A with a B-spline picked): a click on a curve adds an anchor, a click on an inner anchor removes it.
|
||||
* Holds the spline it was entered with; `anchorHover` is what a click would do where the pointer is. */
|
||||
const [anchorMode, setAnchorMode] = useState<string | null>(null);
|
||||
const [anchorHover, setAnchorHover] = useState<AnchorAction>(null);
|
||||
const [hover, setHover] = useState<Hit | null>(null);
|
||||
const [drag, setDrag] = useState<Drag | null>(null);
|
||||
const [box, setBox] = useState<ValueBox | null>(null);
|
||||
@@ -294,11 +303,27 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
}, [pts, modelPoints, crossings, roles]);
|
||||
|
||||
const spotAt = useCallback(
|
||||
(world: [number, number], info: Pick<PointerInfo, "scale" | "alt">): Spot => {
|
||||
const s = snap(world, snapTargets, { grid: snapOn && !info.alt ? gridStep(info.scale) : null, tol: PICK_PX / info.scale });
|
||||
return { x: s.x, y: s.y, pointId: s.pointId?.startsWith("m:") || s.pointId?.startsWith("x:") ? undefined : s.pointId };
|
||||
(world: [number, number], info: Pick<PointerInfo, "scale" | "alt">, curves = false): Spot => {
|
||||
const tol = PICK_PX / info.scale;
|
||||
const s = snap(world, snapTargets, { grid: snapOn && !info.alt ? gridStep(info.scale) : null, tol });
|
||||
const pointId = s.pointId?.startsWith("m:") || s.pointId?.startsWith("x:") ? undefined : s.pointId;
|
||||
if (pointId || !snapOn || info.alt) return { x: s.x, y: s.y, pointId };
|
||||
if (!curves) {
|
||||
if (s.kind === "point") return { x: s.x, y: s.y };
|
||||
const edge = edgeSnap(world, faceEdges, tol);
|
||||
return edge ? { x: edge[0], y: edge[1], onEdge: true } : { x: s.x, y: s.y };
|
||||
}
|
||||
// A point of the sketch wins; then the curve of a spline in anchor form beats the grid (a crossing on it keeps its place).
|
||||
if (s.kind === "point") {
|
||||
const on = curveAt(docRef.current, resultRef.current, [s.x, s.y], tol / 4);
|
||||
return on ? { x: s.x, y: s.y, onSpline: on.spline } : { x: s.x, y: s.y };
|
||||
}
|
||||
const on = curveAt(docRef.current, resultRef.current, world, tol);
|
||||
if (on) return { x: on.at[0], y: on.at[1], onSpline: on.spline };
|
||||
const edge = edgeSnap(world, faceEdges, tol); // the edges of the face the sketch is on beat the grid
|
||||
return edge ? { x: edge[0], y: edge[1], onEdge: true } : { x: s.x, y: s.y };
|
||||
},
|
||||
[snapTargets, snapOn],
|
||||
[snapTargets, snapOn, faceEdges],
|
||||
);
|
||||
|
||||
// -- constraints, value box -------------------------------------------------------------------------------------------------
|
||||
@@ -358,6 +383,8 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
setPendingLine(null);
|
||||
setCornerBox(null);
|
||||
setProjectOpen(false);
|
||||
setAnchorMode(null);
|
||||
setAnchorHover(null);
|
||||
setTool(next);
|
||||
setDraft(null);
|
||||
if (next !== "select") setSelection([]);
|
||||
@@ -447,6 +474,46 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
}),
|
||||
[runEdit],
|
||||
);
|
||||
/** A drawing click on a spline's curve: the SDK adds an anchor there first, then the click goes on with that point. */
|
||||
const placeOnCurve = useCallback(
|
||||
async (spot: Spot, then: (spot: Spot) => void) => {
|
||||
let anchor: string | undefined;
|
||||
await runEdit(insertAnchorRequest(docRef.current, spot.onSpline!, [spot.x, spot.y]), (next, created) => {
|
||||
const made = anchorRoles(next);
|
||||
anchor = created.find((id) => made.get(id)?.kind === "anchor");
|
||||
return [];
|
||||
});
|
||||
const at = anchor ? docRef.current.points.find((p) => p.id === anchor) : undefined;
|
||||
if (at) then({ x: at.x, y: at.y, pointId: at.id });
|
||||
},
|
||||
[runEdit],
|
||||
);
|
||||
|
||||
/** Shift+A: anchor mode on (a B-spline in anchor form, or a point of one, must be picked) or off. */
|
||||
const toggleAnchorMode = useCallback(() => {
|
||||
if (anchorMode) {
|
||||
setAnchorMode(null);
|
||||
setAnchorHover(null);
|
||||
return;
|
||||
}
|
||||
const d = docRef.current;
|
||||
const picked = selection.map((id) => roles.get(id)?.spline ?? id).find((id) => d.entities.some((e) => e.id === id && e.kind === "bspline"));
|
||||
const spline = d.entities.find((e) => e.id === picked);
|
||||
if (!spline) {
|
||||
setEditNote({ tone: "fail", text: "anchor mode: pick a B-spline first (click its curve), then Shift+A" });
|
||||
return;
|
||||
}
|
||||
if (!isAnchorSpline(spline)) {
|
||||
setEditNote({ tone: "fail", text: `anchor mode: ${spline.id} has control points, not anchors: convert it first (K; the shape stays)` });
|
||||
return;
|
||||
}
|
||||
setTool("select");
|
||||
setDraft(null);
|
||||
setEditNote(null);
|
||||
setSelection([spline.id]);
|
||||
setAnchorMode(spline.id);
|
||||
}, [anchorMode, selection, roles]);
|
||||
|
||||
/** The selected B-spline that has control points rather than anchors (the one a convert would change), or null. */
|
||||
const convertTarget = useMemo(() => {
|
||||
const picked = doc.entities.filter((e) => e.kind === "bspline" && selection.includes(e.id));
|
||||
@@ -659,6 +726,16 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
}
|
||||
return "handled";
|
||||
}
|
||||
if (anchorMode && tool === "select") {
|
||||
if (editBusy) return "handled";
|
||||
const hit = hitTest(d, result, world, tol, hidden);
|
||||
const action = anchorAction(d, result, world, tol, hit?.kind === "point" ? hit.id : null, roles);
|
||||
if (action?.kind === "add") void runEdit(insertAnchorRequest(d, action.spline, action.at), () => [action.spline]);
|
||||
else if (action?.kind === "remove") void runEdit(removeAnchorRequest(d, action.spline, action.anchor), () => [action.spline]);
|
||||
else if (action?.kind === "refuse") setEditNote({ tone: "fail", text: action.text });
|
||||
setAnchorHover(null);
|
||||
return "handled";
|
||||
}
|
||||
if (tool === "select" || tool === "delete") {
|
||||
const hit = hitTest(d, result, world, tol, hidden);
|
||||
if (tool === "delete") {
|
||||
@@ -698,6 +775,15 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
if (!shiftKey) setSelection([]);
|
||||
return "handled";
|
||||
}
|
||||
if (ON_CURVE_TOOLS.has(tool)) {
|
||||
const spot = spotAt(world, info, true);
|
||||
const path = draftRef.current?.tool === "spline" ? draftRef.current.points : [];
|
||||
const ending = path.length >= 2 && [path[0], path[path.length - 1]].some((a) => Math.hypot(a.x - spot.x, a.y - spot.y) <= tol);
|
||||
if (spot.onSpline && !ending) {
|
||||
if (!editBusy) void placeOnCurve(spot, (made) => place(made));
|
||||
return "handled";
|
||||
}
|
||||
}
|
||||
if (tool === "spline") {
|
||||
// The pen: a press places an anchor (or finishes / closes the path, as a click does); a drag from it pulls out handles.
|
||||
const spot = spotAt(world, info);
|
||||
@@ -743,11 +829,10 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
ids = [p.hit.id, ...role.handles.filter((h) => !isFixed(d, h))];
|
||||
lead = p.hit.id;
|
||||
} else if (role?.kind === "handle" && role.other && !isFixed(d, role.other)) {
|
||||
// a handle of a smooth anchor turns the opposite handle with it
|
||||
// the opposite handle of the anchor, which Shift turns into line with this one
|
||||
const a = pts.get(role.anchor);
|
||||
const h = pts.get(p.hit.id);
|
||||
const o = pts.get(role.other);
|
||||
if (a && h && o && isSmooth(a, h, o)) mirror = { other: role.other, anchor: a, length: Math.hypot(o[0] - a[0], o[1] - a[1]) };
|
||||
if (a && o) mirror = { other: role.other, anchor: a, length: Math.hypot(o[0] - a[0], o[1] - a[1]) };
|
||||
}
|
||||
if (ids.length && !ids.some((id) => isFixed(d, id))) {
|
||||
const origin: Record<string, [number, number]> = {};
|
||||
@@ -762,12 +847,13 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
// the lead point snaps; the points it carries move by as much
|
||||
const lead = drag.lead ?? drag.ids[0];
|
||||
const s = snap(world, snapTargets, { grid: snapOn && !info.alt ? gridStep(info.scale) : null, tol: snapOn ? tol : 0, skip: new Set(drag.ids) });
|
||||
positions[lead] = [s.x, s.y];
|
||||
const edge = s.kind !== "point" && snapOn && !info.alt ? edgeSnap(world, faceEdges, tol) : null;
|
||||
positions[lead] = edge ?? [s.x, s.y];
|
||||
const dx = s.x - drag.origin[lead][0];
|
||||
const dy = s.y - drag.origin[lead][1];
|
||||
for (const id of drag.ids) if (id !== lead) positions[id] = [drag.origin[id][0] + dx, drag.origin[id][1] + dy];
|
||||
// Alt while dragging a handle breaks the anchor into a corner: the opposite handle stays where it was
|
||||
const turned = drag.mirror && !info.alt ? mirrorHandle(drag.mirror.anchor, positions[lead], drag.mirror.length) : null;
|
||||
// Shift while dragging a handle makes the anchor smooth: the opposite handle turns into line, keeping its own length
|
||||
const turned = drag.mirror && info.shift ? mirrorHandle(drag.mirror.anchor, positions[lead], drag.mirror.length) : null;
|
||||
if (drag.mirror && turned) positions[drag.mirror.other] = turned;
|
||||
} else {
|
||||
const dx = world[0] - drag.start[0];
|
||||
@@ -789,7 +875,12 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
setDraft(next);
|
||||
}
|
||||
}
|
||||
if (tool === "select") {
|
||||
if (tool === "select" && anchorMode) {
|
||||
const hit = hitTest(docRef.current, result, world, tol, hidden);
|
||||
setAnchorHover(anchorAction(docRef.current, result, world, tol, hit?.kind === "point" ? hit.id : null, roles));
|
||||
setHover(null);
|
||||
setCursor({ x: world[0], y: world[1] });
|
||||
} else if (tool === "select") {
|
||||
setHover(hitTest(docRef.current, result, world, tol, hidden));
|
||||
setCursor({ x: world[0], y: world[1] });
|
||||
} else if (tool === "fillet" || tool === "chamfer") {
|
||||
@@ -805,8 +896,8 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
setHoverEnd(hit && tool === "extend" ? nearerEnd(docRef.current, pts, hit.id, world) : null);
|
||||
setCursor({ x: world[0], y: world[1] });
|
||||
} else {
|
||||
const s = spotAt(world, info);
|
||||
setCursor({ x: s.x, y: s.y, pointId: s.pointId });
|
||||
const s = spotAt(world, info, ON_CURVE_TOOLS.has(tool));
|
||||
setCursor({ x: s.x, y: s.y, pointId: s.pointId, onSpline: s.onSpline, onEdge: s.onEdge });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -855,7 +946,9 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
if (draft.points.length >= 2) finishSpline(draft, false);
|
||||
return "handled";
|
||||
}
|
||||
if (k === "s" && tool === "select") smoothSelection();
|
||||
if (k === "a" && event.shiftKey) toggleAnchorMode(); // before A (arc): Shift+A is anchor mode
|
||||
else if (anchorMode && (k === "delete" || k === "backspace")) return "handled"; // a click removes in anchor mode
|
||||
else if (k === "s" && tool === "select") smoothSelection();
|
||||
else if (k === "k" && tool === "select") {
|
||||
if (convertTarget) convertSpline(convertTarget);
|
||||
else setEditNote({ tone: "fail", text: "convert: select one B-spline that has control points (a spline drawn with the spline tool already has anchors)" });
|
||||
@@ -869,7 +962,10 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
else if (cornerBox) setCornerBox(null);
|
||||
else if (projectOpen) setProjectOpen(false);
|
||||
else if (pendingLine) setPendingLine(null);
|
||||
else if (draft) setDraft(null);
|
||||
else if (anchorMode) {
|
||||
setAnchorMode(null);
|
||||
setAnchorHover(null);
|
||||
} else if (draft) setDraft(null);
|
||||
else if (tool !== "select") setTool("select");
|
||||
else if (selection.length) setSelection([]);
|
||||
else return "leave";
|
||||
@@ -914,20 +1010,22 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
|
||||
const typed = DRAW_TOOLS.has(tool) ? " Or type numbers (Tab between fields, Enter places)." : "";
|
||||
const hint =
|
||||
(tool === "select"
|
||||
(tool === "select" && anchorMode
|
||||
? "ANCHOR MODE: click a spline's curve to add an anchor (the curve stays), click an inner anchor to remove it. Esc or Shift+A leaves."
|
||||
: tool === "select"
|
||||
? shown.size
|
||||
? "Drag an anchor (its handles follow) or a handle (its length is that side's pull); a smooth anchor keeps its handles in line: hold Alt while dragging for a corner, S smooths it again. Double-click the curve to add an anchor; Delete removes the selected anchor."
|
||||
? "Drag an anchor (its handles follow) or a handle: each side has its own direction and pull. Hold Shift while dragging a handle to put the other one in line (smooth); S smooths the selected anchors. Shift+A: anchor mode (add/remove anchors by clicking); Delete removes the selected anchor."
|
||||
: convertTarget
|
||||
? `${convertTarget} has control points, not anchors: K (or the button by the curve) converts it, keeping its shape.`
|
||||
: "Click or shift-click to select; drag a point or a line to move it; click inside a loop for the profile, shift-click for a hole. Click a spline to show its handles."
|
||||
: tool === "line"
|
||||
? draft ? "Click the next point; clicking an existing point ends the chain; Esc ends." : "Click the first point."
|
||||
? draft ? "Click the next point; clicking an existing point ends the chain (a click on a spline's curve adds an anchor there and ends on it); Esc ends." : "Click the first point (on a spline's curve: an anchor is added there)."
|
||||
: tool === "circle"
|
||||
? draft ? "Click a point on the circle." : "Click the centre."
|
||||
: tool === "spline"
|
||||
? draft
|
||||
? "Click the next anchor; press and drag to pull out its handles. Finish: Enter, the last anchor again (double-click) or the button; the first anchor closes it. Esc drops it."
|
||||
: "Click the first anchor; press and drag to pull out its handles (a click alone makes a smooth curve through the anchors)."
|
||||
? "Click the next anchor; press and drag to pull out its handles; a click on another spline's curve adds an anchor there and goes through it. Finish: Enter, the last anchor again (double-click) or the button; the first anchor closes it. Esc drops it."
|
||||
: "Click the first anchor; press and drag to pull out its handles (a click alone makes a smooth curve through the anchors). A click on a spline's curve adds an anchor there and starts from it."
|
||||
: tool === "arc"
|
||||
? draft ? (draft.tool === "arc" && draft.start ? "Click the end (counter-clockwise from start)." : "Click the start point (sets the radius).") : "Click the centre."
|
||||
: tool === "delete"
|
||||
@@ -940,13 +1038,14 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
? "Click the part of a line, arc or circle to cut away; the SDK decides the piece between its neighbours."
|
||||
: tool === "extend"
|
||||
? "Click a line near the end to extend; it grows to the next entity."
|
||||
: "Click to place a point.") + typed;
|
||||
: "Click to place a point; on a spline's curve the point is a new anchor of the spline.") + typed;
|
||||
|
||||
return {
|
||||
cornerHover, pendingLine, cornerBox, setCornerBox, submitCorner, projectOpen, setProjectOpen, openProject, projectSketch, projectFrom,
|
||||
doc, commit, undo, redo, edits, editNote, editBusy, flash, hoverEnd, runEdit, tool, chooseTool, selection, highlight, setHighlight, draft, cursor, hover, drag, box, setBox, result, error, auto, setAuto, snapOn,
|
||||
setSnapOn, construction, choice, pts, loops, applicable, blamed, fresh, crossings, finishSplineDraft: () => draft?.tool === "spline" && draft.points.length >= 2 && finishSpline(draft, false), entry,
|
||||
wires, wire, setWireKey, setOutput,
|
||||
wires, wire, setWireKey, setOutput, faceEdges,
|
||||
anchorMode, anchorHover, toggleAnchorMode,
|
||||
roles, shown, hidden, convertTarget, convertSpline, insertAnchor, smoothSelection, pressingPen: () => pen.current !== null, setEntry, entryFields, submitEntry, failing, highlighted, fixedPoints, solved, badge, diagnostics, outer, hint, extents,
|
||||
openBox, applyConstraint, submitBox, deleteSelection, toggleConstruction, pointerDown, pointerMove, pointerUp, pointerLeave, key,
|
||||
};
|
||||
|
||||
@@ -111,6 +111,14 @@ void bind_core(py::module_& m) {
|
||||
.def_property_readonly(
|
||||
"plane", [](const Workplane& w) { return scad::pybind::value_to_python(w.plane_value()); },
|
||||
"The frame as a sketch plane mapping {'origin', 'x_axis', 'y_axis'} (world coordinates).")
|
||||
.def(
|
||||
"point",
|
||||
[tuple3](const Workplane& w, double u, double v, double h) {
|
||||
return tuple3(w.cs().transform_point({u, v, h}));
|
||||
},
|
||||
py::arg("u"), py::arg("v"), py::arg("w") = 0.0,
|
||||
"The world point (x, y, z) at (u, v) in the plane (and w along its normal): where a point drawn on this "
|
||||
"workplane is, so it moves with the workplane.")
|
||||
.def(
|
||||
"__enter__",
|
||||
[](Workplane& w) -> Workplane& {
|
||||
|
||||
@@ -790,6 +790,14 @@ void bind_solve_operators(py::module_& m) {
|
||||
},
|
||||
py::arg("sketch"), py::arg("profile") = 0, py::kw_only(), py::arg("require_fully_constrained") = false,
|
||||
py::arg("strict") = true, py::arg("tolerance") = tol::kSketchSolveResidual, py::arg("max_iterations") = 80);
|
||||
m.def(
|
||||
"make_faces_from_sketch_rfacelist",
|
||||
[](const Sketch& sketch, const std::optional<std::vector<SketchProfileId>>& profiles, bool fully, bool strict,
|
||||
double tolerance, int max_iterations) {
|
||||
return make_faces_from_sketch_rfacelist(sketch, profiles, request_of(fully, strict, tolerance, max_iterations));
|
||||
},
|
||||
py::arg("sketch"), py::arg("profiles") = py::none(), py::kw_only(), py::arg("require_fully_constrained") = false,
|
||||
py::arg("strict") = true, py::arg("tolerance") = tol::kSketchSolveResidual, py::arg("max_iterations") = 80);
|
||||
m.def(
|
||||
"make_face_from_sketch_rface",
|
||||
[](const Sketch& sketch, const SketchProfileId& profile, const std::vector<SketchProfileId>& inner, bool fully,
|
||||
|
||||
@@ -223,8 +223,10 @@ Sketch project_rsketch(const Sketch& sketch, const Sketch& source,
|
||||
bool construction = true);
|
||||
|
||||
// The same for the edges of shapes (a Solid, Face, Shell, Wire, Edge or Compound; a Vertex is a point), in world
|
||||
// coordinates. Lines and circles / arcs project as above; any other edge is refused (name the edges to project).
|
||||
// Ids: proj_shape_<n>; the entity of a projections entry is the topo id of the edge.
|
||||
// coordinates. Lines and circles / arcs project as above; any other edge named on its own (an Edge source) is refused,
|
||||
// and one found inside a face, wire, shell, solid or compound is skipped with a note (so the boundary of a face comes
|
||||
// in with all its lines and arcs: a sketch on the face can snap and be constrained to it). Ids: proj_shape_<n>; the
|
||||
// entity of a projections entry is the topo id of the edge.
|
||||
Sketch project_rsketch(const Sketch& sketch, const std::vector<Shape>& source, bool construction = true);
|
||||
|
||||
// Throws the structured project_rsketch error with `reason` (for binding layers that read the source argument).
|
||||
@@ -258,6 +260,15 @@ Value inspect_sketch_rsketchprofiles(const Sketch& sketch, const SketchSolveRequ
|
||||
Wire make_wire_from_sketch_rwire(const Sketch& sketch, const SketchProfileId& profile = 0,
|
||||
const SketchSolveRequest& request = {});
|
||||
|
||||
// One face per region of the sketch: a closed outer loop minus the loops directly inside it (holes come by themselves;
|
||||
// a loop inside a hole is the outer loop of another region). `profiles` names the regions by their outer profile (an
|
||||
// index of inspect_sketch_rsketchprofiles or a profile id); nullopt: every region, in profile order. Each face is
|
||||
// recorded as make_face_from_sketch_rface(sketch, outer, inner_profiles=holes). Refuses an open chain, a hole and an
|
||||
// unknown profile by name.
|
||||
std::vector<Face> make_faces_from_sketch_rfacelist(
|
||||
const Sketch& sketch, const std::optional<std::vector<SketchProfileId>>& profiles = std::nullopt,
|
||||
const SketchSolveRequest& request = {});
|
||||
|
||||
// Promote an outer profile and optional hole profiles to a face.
|
||||
Face make_face_from_sketch_rface(const Sketch& sketch, const SketchProfileId& profile = 0,
|
||||
const std::vector<SketchProfileId>& inner_profiles = {},
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <unordered_map>
|
||||
|
||||
#include <BRepBuilderAPI_Copy.hxx>
|
||||
#include <BRepLib_ToolTriangulatedShape.hxx>
|
||||
#include <BRepMesh_IncrementalMesh.hxx>
|
||||
#include <BRep_Tool.hxx>
|
||||
#include <IMeshTools_Parameters.hxx>
|
||||
@@ -75,6 +76,11 @@ FaceTessellation extract_face(const TopoDS_Face& face) {
|
||||
{static_cast<std::uint32_t>(a - 1), static_cast<std::uint32_t>(b - 1), static_cast<std::uint32_t>(c - 1)});
|
||||
}
|
||||
|
||||
// The surface's own normal at every node (from its UV parameters), so a curved face is shaded smooth and its
|
||||
// triangles share their vertices; without it each triangle would carry its flat normal (a faceted look, and a vertex
|
||||
// per corner).
|
||||
if (!triangulation->HasNormals() && triangulation->HasUVNodes())
|
||||
BRepLib_ToolTriangulatedShape::ComputeNormals(face, triangulation);
|
||||
if (triangulation->HasNormals()) {
|
||||
out.node_normals.reserve(static_cast<std::size_t>(node_count));
|
||||
for (int i = 1; i <= node_count; ++i) {
|
||||
|
||||
@@ -122,6 +122,11 @@ std::vector<std::pair<std::string, std::string>> targets_of(const TagBinding& bi
|
||||
return out;
|
||||
}
|
||||
|
||||
// Whether the assignment named one entity (not a set of them).
|
||||
bool names_one(const TagBinding& binding) {
|
||||
return targets_of(binding).size() <= 1;
|
||||
}
|
||||
|
||||
// The view of `node`, given the views of its inputs.
|
||||
TagView build_view(const OperationNode& node,
|
||||
const std::unordered_map<const OperationNode*, std::shared_ptr<const TagView>>& done) {
|
||||
@@ -225,7 +230,10 @@ TagView build_view(const OperationNode& node,
|
||||
CarriedTag next = *tag;
|
||||
next.derivation = *derivation;
|
||||
next.op = node.op;
|
||||
if (piece) {
|
||||
// A tag that names one entity follows it as a reference does: split, the pieces are named <tag>.split<i>. A
|
||||
// tag given to several entities at once names a set (every side face of an extrusion): a piece of a member is
|
||||
// still a member, so it keeps the tag and nothing is reported.
|
||||
if (piece && names_one(tag->binding)) {
|
||||
next.binding = piece_binding(tag->binding, node.node_id, *piece);
|
||||
note_split(view, splits, *tag, parent, entry, node, next.binding.tag.str());
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
#include "finalize.hpp"
|
||||
#include "promotion.hpp"
|
||||
#include "regions.hpp"
|
||||
#include "scad/core/error.hpp"
|
||||
#include "scad/kernel/features.hpp"
|
||||
#include "scad/sketch/operators.hpp"
|
||||
@@ -72,10 +73,31 @@ Value inspect_sketch_rsketchprofiles(const Sketch& sketch, const SketchSolveRequ
|
||||
};
|
||||
Value::Array profiles;
|
||||
Value::Array components;
|
||||
Value::Array regions;
|
||||
if (!result.solved_points.empty()) {
|
||||
const std::vector<SketchProfile> listed = sketch_profiles(working, result);
|
||||
std::vector<ProfileNesting> nesting(listed.size());
|
||||
try {
|
||||
nesting = profile_nesting(working, result, listed);
|
||||
} catch (const std::exception&) { // geometry the solve left unusable: no nesting, the profiles still list
|
||||
}
|
||||
const auto number_or_null = [](int value) { return value < 0 ? Value() : Value(value); };
|
||||
int index = 0;
|
||||
for (const SketchProfile& profile : sketch_profiles(working, result)) {
|
||||
for (const SketchProfile& profile : listed) {
|
||||
const ProfileNesting& nest = nesting[static_cast<std::size_t>(index)];
|
||||
if (profile.closed && nest.depth >= 0 && nest.depth % 2 == 0) {
|
||||
Value region = Value::object();
|
||||
region.set("outer", index);
|
||||
Value::Array holes;
|
||||
for (std::size_t j = 0; j < listed.size(); ++j)
|
||||
if (nesting[j].parent == index)
|
||||
holes.emplace_back(static_cast<int>(j));
|
||||
region.set("holes", Value(std::move(holes)));
|
||||
regions.push_back(std::move(region));
|
||||
}
|
||||
Value item = Value::object();
|
||||
item.set("parent", number_or_null(nest.parent));
|
||||
item.set("depth", number_or_null(nest.depth));
|
||||
item.set("index", index++);
|
||||
item.set("id", profile.id);
|
||||
item.set("kind", profile.kind);
|
||||
@@ -96,6 +118,7 @@ Value inspect_sketch_rsketchprofiles(const Sketch& sketch, const SketchSolveRequ
|
||||
Value out = Value::object();
|
||||
out.set("profiles", Value(std::move(profiles)));
|
||||
out.set("unusable", Value(std::move(components)));
|
||||
out.set("regions", Value(std::move(regions)));
|
||||
return out;
|
||||
});
|
||||
}
|
||||
@@ -154,6 +177,67 @@ Face make_face_from_sketch_rface(const Sketch& sketch, const SketchProfileId& pr
|
||||
});
|
||||
}
|
||||
|
||||
std::vector<Face> make_faces_from_sketch_rfacelist(const Sketch& sketch,
|
||||
const std::optional<std::vector<SketchProfileId>>& profiles,
|
||||
const SketchSolveRequest& request) {
|
||||
static const ErrorSpec kSpec{
|
||||
"make_faces_from_sketch_rfacelist",
|
||||
"Failed to create the faces of the sketch's regions.",
|
||||
{"The sketch has no closed profile.",
|
||||
"A requested profile does not exist, is an open chain, or is a hole "
|
||||
"(a loop inside another loop).",
|
||||
"The sketch constraints are conflicting or invalid."},
|
||||
{"List the regions with inspect_sketch_rsketchprofiles(...)['regions'] and pass their outer profiles.",
|
||||
"Leave profiles out to make every region.", "Add constraints until the profile can solve cleanly."}};
|
||||
return guarded(kSpec, [&] {
|
||||
Sketch working = sketch.clone(/*include_solve=*/false);
|
||||
const SketchSolveResult result = working.solve(request);
|
||||
const std::vector<SketchProfile> listed = sketch_profiles(working, result);
|
||||
const std::vector<ProfileNesting> nesting = profile_nesting(working, result, listed);
|
||||
const auto is_outer = [&](std::size_t i) { return listed[i].closed && nesting[i].depth % 2 == 0; };
|
||||
std::vector<std::size_t> outers;
|
||||
if (!profiles) {
|
||||
for (std::size_t i = 0; i < listed.size(); ++i)
|
||||
if (is_outer(i))
|
||||
outers.push_back(i);
|
||||
if (outers.empty())
|
||||
throw ValueError("Sketch contains no closed profile; a region needs a closed loop. Components: " + [&] {
|
||||
std::string text;
|
||||
for (const std::string& part : describe_edge_components(working))
|
||||
text += (text.empty() ? "" : "; ") + part;
|
||||
return text;
|
||||
}());
|
||||
} else {
|
||||
for (const SketchProfileId& wanted : *profiles) {
|
||||
std::size_t found = listed.size();
|
||||
for (std::size_t i = 0; i < listed.size(); ++i)
|
||||
if (wanted.is_index() ? static_cast<int>(i) == wanted.index() : listed[i].id == wanted.id())
|
||||
found = i;
|
||||
const std::string name = wanted.to_value().dump();
|
||||
if (found == listed.size())
|
||||
throw ValueError("there is no sketch profile " + name + " (inspect_sketch_rsketchprofiles lists them)");
|
||||
if (!listed[found].closed)
|
||||
throw ValueError("sketch profile " + name + " is an open chain: a region needs a closed loop");
|
||||
if (!is_outer(found))
|
||||
throw ValueError("sketch profile " + name + " is a hole of profile " + std::to_string(nesting[found].parent) +
|
||||
": pick the region's outer loop (its holes come with it)");
|
||||
if (std::find(outers.begin(), outers.end(), found) == outers.end())
|
||||
outers.push_back(found);
|
||||
}
|
||||
}
|
||||
// Each region is one recorded face: its outer loop, and the loops directly inside it as holes.
|
||||
std::vector<Face> faces;
|
||||
for (const std::size_t outer : outers) {
|
||||
std::vector<SketchProfileId> holes;
|
||||
for (std::size_t j = 0; j < listed.size(); ++j)
|
||||
if (nesting[j].parent == static_cast<int>(outer))
|
||||
holes.emplace_back(listed[j].id);
|
||||
faces.push_back(make_face_from_sketch_rface(sketch, SketchProfileId(listed[outer].id), holes, request));
|
||||
}
|
||||
return faces;
|
||||
});
|
||||
}
|
||||
|
||||
std::vector<Face> sketch_to_faces(const Sketch& sketch) {
|
||||
if (!sketch.entities().empty())
|
||||
return {make_face_from_sketch_rface(sketch)};
|
||||
|
||||
@@ -280,18 +280,13 @@ std::vector<SketchProfile> sketch_profiles(const Sketch& sketch, const SketchSol
|
||||
|
||||
SketchProfile select_sketch_profile(const Sketch& sketch, const SketchProfileId& profile,
|
||||
const SketchSolveResult& result, bool require_closed) {
|
||||
// The index is the one inspect_sketch_rsketchprofiles lists (open chains included), for a face as for a wire.
|
||||
std::vector<SketchProfile> profiles = sketch_profiles(sketch, result);
|
||||
if (require_closed) {
|
||||
std::vector<SketchProfile> closed;
|
||||
for (SketchProfile& item : profiles) {
|
||||
if (item.closed)
|
||||
closed.push_back(std::move(item));
|
||||
}
|
||||
if (closed.empty()) {
|
||||
throw ValueError("Sketch contains no closed profile; face promotion requires a closed loop. Components: " +
|
||||
join(describe_edge_components(sketch), "; "));
|
||||
}
|
||||
profiles = std::move(closed);
|
||||
const bool any_closed =
|
||||
std::any_of(profiles.begin(), profiles.end(), [](const SketchProfile& p) { return p.closed; });
|
||||
if (require_closed && !any_closed) {
|
||||
throw ValueError("Sketch contains no closed profile; face promotion requires a closed loop. Components: " +
|
||||
join(describe_edge_components(sketch), "; "));
|
||||
}
|
||||
if (profiles.empty()) {
|
||||
const std::vector<std::string> descriptions = describe_edge_components(sketch);
|
||||
@@ -299,18 +294,29 @@ SketchProfile select_sketch_profile(const Sketch& sketch, const SketchProfileId&
|
||||
: "Components: " + join(descriptions, "; ");
|
||||
throw ValueError("Sketch contains no promotable closed loop or open chain. " + detail);
|
||||
}
|
||||
std::size_t chosen = profiles.size();
|
||||
if (!profile.is_index()) {
|
||||
for (SketchProfile& item : profiles) {
|
||||
if (item.id == profile.id())
|
||||
return std::move(item);
|
||||
}
|
||||
throw ValueError("Unknown sketch profile '" + profile.id() + "'");
|
||||
for (std::size_t i = 0; i < profiles.size(); ++i)
|
||||
if (profiles[i].id == profile.id())
|
||||
chosen = i;
|
||||
if (chosen == profiles.size())
|
||||
throw ValueError("Unknown sketch profile '" + profile.id() + "'");
|
||||
} else {
|
||||
const int index = profile.index();
|
||||
if (index < 0 || index >= static_cast<int>(profiles.size()))
|
||||
throw ValueError("Sketch profile index " + std::to_string(index) + " is out of range (the sketch has " +
|
||||
std::to_string(profiles.size()) + " profiles, inspect_sketch_rsketchprofiles lists them)");
|
||||
chosen = static_cast<std::size_t>(index);
|
||||
}
|
||||
const int index = profile.index();
|
||||
if (index < 0 || index >= static_cast<int>(profiles.size())) {
|
||||
throw ValueError("Sketch profile index " + std::to_string(index) + " is out of range");
|
||||
if (require_closed && !profiles[chosen].closed) {
|
||||
std::vector<std::string> closed;
|
||||
for (std::size_t i = 0; i < profiles.size(); ++i)
|
||||
if (profiles[i].closed)
|
||||
closed.push_back(std::to_string(i));
|
||||
throw ValueError("Sketch profile " + profile.to_value().dump() + " ('" + profiles[chosen].id +
|
||||
"') is an open chain: a face needs a closed one (closed profiles: " + join(closed, ", ") + ")");
|
||||
}
|
||||
return std::move(profiles[static_cast<std::size_t>(index)]);
|
||||
return std::move(profiles[chosen]);
|
||||
}
|
||||
|
||||
} // namespace scad
|
||||
|
||||
@@ -298,15 +298,18 @@ class SketchProjection {
|
||||
TopExp::MapShapes(shape.wrapped(), TopAbs_EDGE, edges);
|
||||
if (edges.Extent() == 0)
|
||||
throw ValueError("a " + std::string(kind_name(shape.kind())) + " source has no edges to project");
|
||||
// An edge named on its own must project; the edges of a face (a solid, a wire ...) that do not are skipped with
|
||||
// a note, so a face's boundary comes in with every line and arc it has.
|
||||
const bool named = shape.kind() == Kind::Edge;
|
||||
for (int i = 1; i <= edges.Extent(); ++i)
|
||||
project_edge(shape.sub(edges(i)), prims);
|
||||
project_edge(shape.sub(edges(i)), prims, named);
|
||||
});
|
||||
}
|
||||
return emit(prims, "shape", construction, "shapes");
|
||||
}
|
||||
|
||||
private:
|
||||
void project_edge(const Shape& edge_shape, std::vector<Prim>& out) {
|
||||
void project_edge(const Shape& edge_shape, std::vector<Prim>& out, bool named) {
|
||||
const TopoDS_Edge edge = TopoDS::Edge(edge_shape.wrapped());
|
||||
const std::string id = edge_shape.topo_id();
|
||||
if (BRep_Tool::Degenerated(edge)) {
|
||||
@@ -332,6 +335,9 @@ class SketchProjection {
|
||||
round.end = vec_of(curve.Value(last));
|
||||
}
|
||||
out.push_back(project_round(frame_, round, id, "edge"));
|
||||
} else if (!named) {
|
||||
notes_.push_back("skipped " + id + " (a " + std::string(curve_name(curve.GetType())) +
|
||||
" curve): only lines and circles / arcs project");
|
||||
} else {
|
||||
throw ValueError("edge '" + id + "' is a " + curve_name(curve.GetType()) +
|
||||
" curve: only lines and circles / arcs project (pass the line and circle edges you need, for "
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
#include "regions.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
|
||||
#include "edit_curves.hpp"
|
||||
#include "scad/core/vec.hpp"
|
||||
|
||||
namespace scad::sketch_detail {
|
||||
|
||||
namespace {
|
||||
|
||||
using Pt = SketchPoint2;
|
||||
constexpr int kArcSteps = 24;
|
||||
constexpr int kCurveSteps = 32;
|
||||
|
||||
Pt solved(const SketchSolveResult& result, const std::string& id) {
|
||||
return result.solved_points.at(id);
|
||||
}
|
||||
|
||||
// Points along an edge entity from its start to its end, in sketch coordinates.
|
||||
std::vector<Pt> edge_points(const SketchEntity& entity, const SketchSolveResult& result) {
|
||||
const Pt s = solved(result, entity.point_id("start"));
|
||||
const Pt e = solved(result, entity.point_id("end"));
|
||||
if (entity.kind == kLineKind)
|
||||
return {s, e};
|
||||
std::vector<Pt> out;
|
||||
if (entity.kind == kArcKind) {
|
||||
const Pt c = solved(result, entity.point_id("center"));
|
||||
const double r = std::hypot(s.first - c.first, s.second - c.second);
|
||||
const double a0 = std::atan2(s.second - c.second, s.first - c.first);
|
||||
double sweep = std::atan2(e.second - c.second, e.first - c.first) - a0;
|
||||
while (sweep <= 1e-12)
|
||||
sweep += 2.0 * kPi;
|
||||
for (int i = 0; i <= kArcSteps; ++i) {
|
||||
const double a = a0 + sweep * i / kArcSteps;
|
||||
out.emplace_back(c.first + r * std::cos(a), c.second + r * std::sin(a));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// a B-spline: its solved control points
|
||||
const SketchBSpline definition = entity.bspline();
|
||||
Spline2 spline;
|
||||
spline.degree = definition.degree;
|
||||
for (std::size_t i = 0; i < definition.poles.size(); ++i)
|
||||
spline.poles.push_back(solved(result, "bspline:" + entity.id + ":pole:" + std::to_string(i)));
|
||||
spline.knots = definition.knots;
|
||||
spline.multiplicities = definition.multiplicities;
|
||||
if (definition.weights)
|
||||
spline.weights = *definition.weights;
|
||||
spline.periodic = definition.periodic;
|
||||
const auto curve = make_spline2(spline);
|
||||
const double u0 = curve->FirstParameter();
|
||||
const double u1 = curve->LastParameter();
|
||||
for (int i = 0; i <= kCurveSteps; ++i)
|
||||
out.push_back(value_at(curve, u0 + (u1 - u0) * i / kCurveSteps));
|
||||
return out;
|
||||
}
|
||||
|
||||
// The closed profile as a polygon (sketch coordinates); empty for an open chain.
|
||||
std::vector<Pt> polygon_of(const Sketch& sketch, const SketchSolveResult& result, const SketchProfile& profile) {
|
||||
std::vector<Pt> out;
|
||||
if (!profile.closed)
|
||||
return out;
|
||||
const SketchEntity& first = sketch.entities().at(profile.entity_ids.front());
|
||||
if (profile.kind == "circle" || profile.kind == "ellipse") {
|
||||
const Pt c = solved(result, first.point_id("center"));
|
||||
Pt u{0, 0};
|
||||
Pt v{0, 0};
|
||||
if (profile.kind == "circle") {
|
||||
const double r = result.solved_scalars.at("circle:" + first.id + ":radius");
|
||||
u = {r, 0};
|
||||
v = {0, r};
|
||||
} else {
|
||||
const Pt major = solved(result, first.point_id("major"));
|
||||
const Pt minor = solved(result, first.point_id("minor"));
|
||||
u = {major.first - c.first, major.second - c.second};
|
||||
v = {minor.first - c.first, minor.second - c.second};
|
||||
}
|
||||
for (int i = 0; i < 2 * kArcSteps; ++i) {
|
||||
const double a = kPi * i / kArcSteps;
|
||||
out.emplace_back(c.first + u.first * std::cos(a) + v.first * std::sin(a),
|
||||
c.second + u.second * std::cos(a) + v.second * std::sin(a));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
for (std::size_t i = 0; i < profile.entity_ids.size(); ++i) {
|
||||
std::vector<Pt> points = edge_points(sketch.entities().at(profile.entity_ids[i]), result);
|
||||
if (profile.reversed[i])
|
||||
std::reverse(points.begin(), points.end());
|
||||
out.insert(out.end(), points.begin(), points.end() - 1); // the last point is the next edge's first
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
double area(const std::vector<Pt>& polygon) {
|
||||
double sum = 0.0;
|
||||
for (std::size_t i = 0; i < polygon.size(); ++i) {
|
||||
const Pt& a = polygon[i];
|
||||
const Pt& b = polygon[(i + 1) % polygon.size()];
|
||||
sum += a.first * b.second - b.first * a.second;
|
||||
}
|
||||
return std::abs(sum) / 2.0;
|
||||
}
|
||||
|
||||
bool inside(const Pt& p, const std::vector<Pt>& polygon) {
|
||||
bool in = false;
|
||||
for (std::size_t i = 0, j = polygon.size() - 1; i < polygon.size(); j = i++) {
|
||||
const Pt& a = polygon[i];
|
||||
const Pt& b = polygon[j];
|
||||
if ((a.second > p.second) != (b.second > p.second) &&
|
||||
p.first < (b.first - a.first) * (p.second - a.second) / (b.second - a.second) + a.first)
|
||||
in = !in;
|
||||
}
|
||||
return in;
|
||||
}
|
||||
|
||||
// Is `inner` inside `outer`: the smaller one, with most of its points inside (a shared corner or a touching edge is
|
||||
// on the boundary and may count either way).
|
||||
bool contains(const std::vector<Pt>& outer, double outer_area, const std::vector<Pt>& inner, double inner_area) {
|
||||
if (outer.size() < 3 || inner.empty() || inner_area >= outer_area)
|
||||
return false;
|
||||
std::size_t hits = 0;
|
||||
for (const Pt& p : inner)
|
||||
hits += inside(p, outer) ? 1 : 0;
|
||||
return 2 * hits > inner.size();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::vector<ProfileNesting> profile_nesting(const Sketch& sketch, const SketchSolveResult& result,
|
||||
const std::vector<SketchProfile>& profiles) {
|
||||
std::vector<std::vector<Pt>> polygons;
|
||||
std::vector<double> areas;
|
||||
for (const SketchProfile& profile : profiles) {
|
||||
polygons.push_back(polygon_of(sketch, result, profile));
|
||||
areas.push_back(polygons.back().size() >= 3 ? area(polygons.back()) : 0.0);
|
||||
}
|
||||
std::vector<ProfileNesting> out(profiles.size());
|
||||
for (std::size_t i = 0; i < profiles.size(); ++i) {
|
||||
if (!profiles[i].closed)
|
||||
continue;
|
||||
int parent = -1;
|
||||
for (std::size_t j = 0; j < profiles.size(); ++j) {
|
||||
if (j == i || !profiles[j].closed || !contains(polygons[j], areas[j], polygons[i], areas[i]))
|
||||
continue;
|
||||
if (parent < 0 || areas[j] < areas[static_cast<std::size_t>(parent)])
|
||||
parent = static_cast<int>(j); // the smallest loop around it is the one it lies directly inside
|
||||
}
|
||||
out[i].parent = parent;
|
||||
}
|
||||
for (std::size_t i = 0; i < profiles.size(); ++i) {
|
||||
if (!profiles[i].closed)
|
||||
continue;
|
||||
int depth = 0;
|
||||
for (int at = out[i].parent; at >= 0 && depth <= static_cast<int>(profiles.size());
|
||||
at = out[static_cast<std::size_t>(at)].parent)
|
||||
++depth;
|
||||
out[i].depth = depth;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace scad::sketch_detail
|
||||
@@ -0,0 +1,23 @@
|
||||
// Which closed profile of a solved sketch lies inside which: the nesting that makes regions (an outer loop minus the
|
||||
// loops directly inside it). Internal to the sketch library; inspect_sketch_rsketchprofiles reports it and
|
||||
// make_faces_from_sketch_rfacelist builds faces from it.
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "scad/sketch/profile.hpp"
|
||||
|
||||
namespace scad::sketch_detail {
|
||||
|
||||
// Per profile (same order as `profiles`): the index of the closed profile it lies directly inside (-1: none, and for
|
||||
// every open chain), and its depth (0: outside every loop; -1 for an open chain). Even depth: an outer loop of a
|
||||
// region; odd: a hole of the region of its parent. A loop is inside another when most of its points are and it is the
|
||||
// smaller one; crossing loops are not regions and are nested by that test only.
|
||||
struct ProfileNesting {
|
||||
int parent = -1;
|
||||
int depth = -1;
|
||||
};
|
||||
std::vector<ProfileNesting> profile_nesting(const Sketch& sketch, const SketchSolveResult& result,
|
||||
const std::vector<SketchProfile>& profiles);
|
||||
|
||||
} // namespace scad::sketch_detail
|
||||
@@ -0,0 +1,84 @@
|
||||
// Regions of a sketch: which closed profile lies inside which (inspect_sketch_rsketchprofiles), one face per region
|
||||
// (make_faces_from_sketch_rfacelist), and the profile index faces and wires share.
|
||||
#include "doctest.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "scad/core/error.hpp"
|
||||
#include "scad/sketch/operators.hpp"
|
||||
|
||||
using namespace scad;
|
||||
|
||||
namespace {
|
||||
|
||||
// A 40 x 20 plate with a circle in it, a second 20 x 20 square apart, and an open chain drawn first.
|
||||
Sketch plate_and_square() {
|
||||
Sketch s = make_sketch_rsketch("regions");
|
||||
const std::vector<std::pair<std::string, std::pair<double, double>>> points{
|
||||
{"z1", {-20, 0}}, {"z2", {-10, 0}}, {"a", {0, 0}}, {"b", {40, 0}}, {"c", {40, 20}}, {"d", {0, 20}},
|
||||
{"e", {60, 0}}, {"f", {80, 0}}, {"g", {80, 20}}, {"h", {60, 20}}, {"o", {10, 10}}};
|
||||
for (const auto& [id, xy] : points)
|
||||
s = add_point_rsketch(s, id, xy.first, xy.second);
|
||||
s = add_line_rsketch(s, "zz", "z1", "z2");
|
||||
s = add_line_rsketch(s, "l0", "a", "b");
|
||||
s = add_line_rsketch(s, "l1", "b", "c");
|
||||
s = add_line_rsketch(s, "l2", "c", "d");
|
||||
s = add_line_rsketch(s, "l3", "d", "a");
|
||||
s = add_line_rsketch(s, "m0", "e", "f");
|
||||
s = add_line_rsketch(s, "m1", "f", "g");
|
||||
s = add_line_rsketch(s, "m2", "g", "h");
|
||||
s = add_line_rsketch(s, "m3", "h", "e");
|
||||
return add_circle_rsketch(s, "k", "o", 4.0);
|
||||
}
|
||||
|
||||
std::string failure_text(const std::function<void()>& call) {
|
||||
try {
|
||||
call();
|
||||
} catch (const Error& e) {
|
||||
return e.guidance().technical_details;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("profiles report their nesting and the regions") {
|
||||
const Value info = inspect_sketch_rsketchprofiles(plate_and_square());
|
||||
const Value::Array& profiles = info.find("profiles")->as_array();
|
||||
// circles first (k: 0), then the edge components in entity order (zz: 1, l0: 2, m0: 3)
|
||||
REQUIRE(profiles.size() == 4);
|
||||
CHECK(profiles[0].find("parent")->as_int() == 2);
|
||||
CHECK(profiles[0].find("depth")->as_int() == 1);
|
||||
CHECK(profiles[1].find("parent")->is_null()); // the open chain
|
||||
CHECK(profiles[2].find("depth")->as_int() == 0);
|
||||
const Value::Array& regions = info.find("regions")->as_array();
|
||||
REQUIRE(regions.size() == 2);
|
||||
CHECK(regions[0].find("outer")->as_int() == 2);
|
||||
CHECK(regions[0].find("holes")->as_array().size() == 1);
|
||||
CHECK(regions[1].find("outer")->as_int() == 3);
|
||||
}
|
||||
|
||||
TEST_CASE("one face per region, with its holes; a hole or an open chain is refused") {
|
||||
const Sketch s = plate_and_square();
|
||||
const std::vector<Face> faces = make_faces_from_sketch_rfacelist(s);
|
||||
REQUIRE(faces.size() == 2);
|
||||
CHECK(std::abs(faces[0].area() - (800.0 - kPi * 16.0)) < 1e-3);
|
||||
CHECK(std::abs(faces[1].area() - 400.0) < 1e-6);
|
||||
const std::vector<Face> one =
|
||||
make_faces_from_sketch_rfacelist(s, std::vector<SketchProfileId>{SketchProfileId("m0")});
|
||||
CHECK(one.size() == 1);
|
||||
CHECK(failure_text([&] { make_faces_from_sketch_rfacelist(s, std::vector<SketchProfileId>{0}); }).find("is a hole") !=
|
||||
std::string::npos);
|
||||
CHECK(failure_text([&] {
|
||||
make_faces_from_sketch_rfacelist(s, std::vector<SketchProfileId>{1});
|
||||
}).find("open chain") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST_CASE("a face takes the index inspect_sketch_rsketchprofiles lists, open chains counted") {
|
||||
const Sketch s = plate_and_square();
|
||||
CHECK(std::abs(make_face_from_sketch_rface(s, 3).area() - 400.0) < 1e-6);
|
||||
CHECK(failure_text([&] { make_face_from_sketch_rface(s, 1); }).find("is an open chain") != std::string::npos);
|
||||
}
|
||||
@@ -338,6 +338,7 @@ from simplecadapi._cpp import (
|
||||
project_rsketch,
|
||||
trim_rsketch,
|
||||
insert_spline_anchor_rsketch,
|
||||
make_faces_from_sketch_rfacelist,
|
||||
remove_spline_anchor_rsketch,
|
||||
convert_spline_to_anchors_rsketch,
|
||||
constrain_mirror_rsketch,
|
||||
@@ -711,6 +712,7 @@ __all__ = [
|
||||
"trim_rsketch",
|
||||
"extend_rsketch",
|
||||
"insert_spline_anchor_rsketch",
|
||||
"make_faces_from_sketch_rfacelist",
|
||||
"remove_spline_anchor_rsketch",
|
||||
"convert_spline_to_anchors_rsketch",
|
||||
"diff_sketch_rsketchdiff",
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -557,7 +557,7 @@ def signature_of(obj: Any) -> Any:
|
||||
|
||||
|
||||
_WITH_SIGNATURE: Dict[int, Any] = {}
|
||||
_OP_SUFFIXES = ("_rsolid", "_rsolidlist", "_rshell", "_rface", "_rpart", "_rworkplane")
|
||||
_OP_SUFFIXES = ("_rsolid", "_rsolidlist", "_rshell", "_rface", "_rfacelist", "_rpart", "_rworkplane")
|
||||
_SHAPE_FUNCTIONS = frozenset({"translate_shape", "rotate_shape", "mirror_shape", "scale_shape"})
|
||||
"""Operations that may receive the pieces of a split body (see :mod:`.pieces`)."""
|
||||
|
||||
|
||||
@@ -216,6 +216,7 @@
|
||||
"make_ellipse_rwire": "Create an elliptical wire.",
|
||||
"make_face_connector_rconnector": "Create a connector anchored to a Face.\n\nZ axis follows the face normal; origin is the face center.\nSet flip=True to negate the Z axis (point it opposite to the normal).",
|
||||
"make_face_from_sketch_rface": "Promote one outer and optional inner sketch profiles to a face.",
|
||||
"make_faces_from_sketch_rfacelist": "Make one face per region of the sketch: a closed outer loop minus the loops directly inside it.\n\nHoles come by themselves: a loop inside an outer loop is a hole of that region, and a loop inside a hole is the\nouter loop of another region (``inspect_sketch_rsketchprofiles`` reports each closed profile's ``parent`` and\n``depth`` and the ``regions`` as ``{\"outer\": i, \"holes\": [...]}``). ``profiles`` names the regions to make by their\nouter profile (an index of ``inspect_sketch_rsketchprofiles`` or a profile id); leave it out for every region, in\nprofile order. An open chain, a hole or an unknown profile is refused by name.\n\nReturns the faces as ``scad.Pieces`` (a list) in that order: a one-shape operation such as ``extrude_rsolid`` runs on\nevery face and returns ``Pieces`` (one solid per region; ``union_rsolid`` joins them, ``make_part_rpart`` makes them\nbodies). Each face is recorded as ``make_face_from_sketch_rface(sketch, outer, inner_profiles=holes)`` and replays\nfrom model JSON.",
|
||||
"make_face_from_wire_rface": "Create a face from a closed wire.",
|
||||
"make_face_from_wires_rface": "Create a face from one outer closed wire and optional inner closed wires.",
|
||||
"make_gordon_surface_rface": "Create a Gordon Face from intersecting profile and guide edge networks.",
|
||||
@@ -275,7 +276,7 @@
|
||||
"placement_frame_mm": "Return a millimetre float frame from a tick (or legacy float) frame.",
|
||||
"placement_from_canonical": "Rebuild a runtime Placement from a tick frame (or a legacy float frame).",
|
||||
"placement_ticks": "Return the integer-tick identity form of a placement frame.\n\nTick frames are the only representation that is hashed or persisted:\nthey are exact integers, so canonical JSON bytes and content hashes are\nstable across save/load cycles regardless of floating-point noise. The\nstored ``z_axis`` is authoritative (derived once from ``x_axis ×\ny_axis`` by :class:`Placement` at write time) and is never recomputed.",
|
||||
"project_rsketch": "Bring geometry from another sketch, or from the edges of shapes, into the sketch as reference geometry.\n\n``source`` is a Sketch (any plane; it is solved first), a Solid / Face / Shell / Wire / Edge / Compound or a list\nof shapes (what ``ql.edges().resolve(shape)`` returns). Points go through the plane frames: u = (P - origin) .\nx_axis, v = (P - origin) . y_axis. Points, lines, circles and arcs in a parallel plane are copied (an arc keeps its\ncounter-clockwise sense); a circle or arc seen edge on becomes a line, a line along the sketch normal a point, an\noblique full circle an ellipse; an oblique arc, and edges that are not lines or circles, are refused by name.\n``entities`` limits the source sketch entities (default: all lines, circles, arcs and free points; ellipses and\nB-splines are skipped and listed in ``get_metadata(\"last_edit\")``); it is not used with shapes. The copies are\n``construction`` (default True) and fixed at their projected coordinates. Ids are ``proj_<source sketch id>_<n>``\n(``proj_shape_<n>`` for shapes); ``get_metadata(\"projections\")`` lists {source, entity, projected} and projecting\nthe same source again reuses the entities already there.",
|
||||
"project_rsketch": "Bring geometry from another sketch, or from the edges of shapes, into the sketch as reference geometry.\n\n``source`` is a Sketch (any plane; it is solved first), a Solid / Face / Shell / Wire / Edge / Compound or a list\nof shapes (what ``ql.edges().resolve(shape)`` returns). Points go through the plane frames: u = (P - origin) .\nx_axis, v = (P - origin) . y_axis. Points, lines, circles and arcs in a parallel plane are copied (an arc keeps its\ncounter-clockwise sense); a circle or arc seen edge on becomes a line, a line along the sketch normal a point, an\noblique full circle an ellipse; an oblique arc is refused by name, and so is an edge that is not a line or a circle when\nit is passed on its own (an Edge); inside a face, wire, shell, solid or compound such an edge is skipped and noted, so\n``project_rsketch(sketch, face)`` brings the face's boundary in (its lines and arcs) for a sketch on that face to snap\nand constrain to; in a cell the face comes from the model, so the projection follows it.\n``entities`` limits the source sketch entities (default: all lines, circles, arcs and free points; ellipses and\nB-splines are skipped and listed in ``get_metadata(\"last_edit\")``); it is not used with shapes. The copies are\n``construction`` (default True) and fixed at their projected coordinates. Ids are ``proj_<source sketch id>_<n>``\n(``proj_shape_<n>`` for shapes); ``get_metadata(\"projections\")`` lists {source, entity, projected} and projecting\nthe same source again reuses the entities already there.",
|
||||
"projected_tag_binding": "Project one source binding through a proven feature-generation witness.",
|
||||
"radial_pattern_rsolidlist": "Create a radial pattern of solids.",
|
||||
"raise_loft_failure_if_diagnosed": "Diagnose a kernel loft failure from section facts; raise when explained.\n\nThe kernel reports loft failures as a bare \"build did not complete\"\nnaming nothing. This probe re-reads the sections the agent passed and\nreports the computable compatibility verdicts: coincident consecutive\nsections, edge-count mismatches, open section wires, and non-monotonic\nstation order. Raises the structured error when any verdict lands;\nreturns silently when nothing diagnosable is found (the caller then\napplies the generic wrap).",
|
||||
|
||||
@@ -486,6 +486,7 @@
|
||||
"translate_z_placement": "simplecadapi.product.placement",
|
||||
"trim_rsketch": "simplecadapi.operators.sketch",
|
||||
"insert_spline_anchor_rsketch": "simplecadapi.operators.sketch",
|
||||
"make_faces_from_sketch_rfacelist": "simplecadapi.operators.sketch",
|
||||
"remove_spline_anchor_rsketch": "simplecadapi.operators.sketch",
|
||||
"convert_spline_to_anchors_rsketch": "simplecadapi.operators.sketch",
|
||||
"trim_surface_face": "simplecadapi.kernel.ocp_surfaces",
|
||||
|
||||
@@ -17,8 +17,8 @@ from typing import Any, Callable
|
||||
TAKES_PIECES = frozenset({"make_part_rpart", "fillet_rsolid", "chamfer_rsolid", "union_rsolid", "boolean_rsolidlist"})
|
||||
"""Operations that read a list of pieces as such (all of them together), not one piece at a time."""
|
||||
|
||||
SPLITS = frozenset({"cut_rsolid", "fillet_rsolid", "chamfer_rsolid"})
|
||||
"""Operations whose list result is the pieces of one body."""
|
||||
SPLITS = frozenset({"cut_rsolid", "fillet_rsolid", "chamfer_rsolid", "make_faces_from_sketch_rfacelist"})
|
||||
"""Operations whose list result flows on as :class:`Pieces`: the pieces of one body, and the region faces of a sketch."""
|
||||
|
||||
|
||||
class TagSplitWarning(UserWarning):
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
"""A 3D curve the editor draws in space, and the cell code it becomes.
|
||||
|
||||
A sketch lies in one plane; a 3D curve does not: each of its points is in world space, on a workplane, or at a vertex
|
||||
of the model, so one path can run between planes and through the model (a sweep path, a rail, a loft guide). The
|
||||
document is plain data::
|
||||
|
||||
{"points": [{"id": "p1", "at": [0, 0, 0]}, # world mm
|
||||
{"id": "p2", "on": "wp_2", "uv": [10, 5]}, # on a workplane variable: follows it
|
||||
{"id": "p3", "vertex": {<scad.ref record>}, "at": [20, 0, 10]}], # a vertex of the model: follows it
|
||||
"curves": [{"id": "c1", "kind": "line", "points": ["p1", "p2"]},
|
||||
{"id": "c2", "kind": "arc", "points": ["p2", "p4", "p3"]}, # start, a point on it, end
|
||||
{"id": "c3", "kind": "spline", "points": ["p3", "p5", "p6"]}]} # through the points
|
||||
|
||||
The curves follow one another (each starts where the last ended) and become one wire. :func:`render` writes the cell:
|
||||
one name per point (a vertex resolves through its stable reference in the body, a workplane point through
|
||||
``wp.point(u, v)``), one SDK edge per curve, and ``make_wire_from_edges_rwire`` joining them. Nothing here is
|
||||
geometry: the code is the SDK's, the document only says which points and curves.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import re
|
||||
from typing import Any, Mapping
|
||||
|
||||
from .. import ref as _ref
|
||||
|
||||
KINDS = {"line": 2, "arc": 3, "spline": 2}
|
||||
"""Each kind and how many points it takes (a spline takes this many or more)."""
|
||||
|
||||
_ID = re.compile(r"[a-z][a-z0-9_]{0,30}")
|
||||
_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
|
||||
|
||||
|
||||
class CurveError(ValueError):
|
||||
"""A 3D curve document the editor cannot turn into code."""
|
||||
|
||||
|
||||
def _number(value: Any, what: str) -> float:
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(float(value)):
|
||||
raise CurveError(f"{what} must be a finite number")
|
||||
return round(float(value), 6) + 0.0
|
||||
|
||||
|
||||
def _vector(value: Any, size: int, what: str) -> list[float]:
|
||||
if not isinstance(value, (list, tuple)) or len(value) != size:
|
||||
raise CurveError(f"{what} needs {size} numbers")
|
||||
return [_number(v, what) for v in value]
|
||||
|
||||
|
||||
def validate(doc: Mapping[str, Any]) -> dict[str, Any]:
|
||||
"""The document checked and cleaned; :class:`CurveError` names what is wrong."""
|
||||
if not isinstance(doc, Mapping):
|
||||
raise CurveError("a 3D curve is an object with points and curves")
|
||||
points: list[dict[str, Any]] = []
|
||||
ids: set[str] = set()
|
||||
for raw in doc.get("points") or []:
|
||||
if not isinstance(raw, Mapping) or not _ID.fullmatch(str(raw.get("id", ""))):
|
||||
raise CurveError("every point needs an id (a lower-case name)")
|
||||
pid = str(raw["id"])
|
||||
if pid in ids:
|
||||
raise CurveError(f"point {pid!r} is listed twice")
|
||||
ids.add(pid)
|
||||
point: dict[str, Any] = {"id": pid}
|
||||
if raw.get("on") is not None:
|
||||
if not _NAME.fullmatch(str(raw["on"])):
|
||||
raise CurveError(f"point {pid!r}: {raw['on']!r} is not a workplane name")
|
||||
point["on"] = str(raw["on"])
|
||||
point["uv"] = _vector(raw.get("uv"), 2, f"point {pid!r} on {raw['on']}")
|
||||
if raw.get("vertex") is not None:
|
||||
try:
|
||||
reference = _ref.coerce(raw["vertex"])
|
||||
except (ValueError, TypeError) as exc:
|
||||
raise CurveError(f"point {pid!r}: {exc}") from exc
|
||||
if reference.kind != "vertex":
|
||||
raise CurveError(f"point {pid!r}: a point is snapped to a vertex, not a {reference.kind}")
|
||||
point["vertex"] = reference.to_dict()
|
||||
if raw.get("at") is not None or ("on" not in point and "vertex" not in point):
|
||||
point["at"] = _vector(raw.get("at"), 3, f"point {pid!r}")
|
||||
if "on" in point and "vertex" in point:
|
||||
raise CurveError(f"point {pid!r} is either on a workplane or at a vertex, not both")
|
||||
points.append(point)
|
||||
curves: list[dict[str, Any]] = []
|
||||
for raw in doc.get("curves") or []:
|
||||
if not isinstance(raw, Mapping) or not _ID.fullmatch(str(raw.get("id", ""))):
|
||||
raise CurveError("every curve needs an id (a lower-case name)")
|
||||
kind = str(raw.get("kind", ""))
|
||||
if kind not in KINDS:
|
||||
raise CurveError(f"curve {raw['id']!r}: a curve is a line, an arc or a spline")
|
||||
names = [str(p) for p in raw.get("points") or []]
|
||||
if any(p not in ids for p in names):
|
||||
raise CurveError(f"curve {raw['id']!r} names a point the document does not have")
|
||||
if (kind == "spline" and len(names) < 2) or (kind != "spline" and len(names) != KINDS[kind]):
|
||||
article = "an" if kind == "arc" else "a"
|
||||
raise CurveError(f"curve {raw['id']!r}: {article} {kind} takes {'at least 2' if kind == 'spline' else KINDS[kind]} points")
|
||||
curves.append({"id": str(raw["id"]), "kind": kind, "points": names})
|
||||
if not curves:
|
||||
raise CurveError("draw at least one line, arc or spline")
|
||||
for before, after in zip(curves, curves[1:]):
|
||||
if before["points"][-1] != after["points"][0]:
|
||||
raise CurveError(f"curve {after['id']!r} must start where {before['id']!r} ends: the curves make one path")
|
||||
return {"points": points, "curves": curves}
|
||||
|
||||
|
||||
def workplanes_of(doc: Mapping[str, Any]) -> list[str]:
|
||||
"""The workplane variables the document's points are on (the cell reads them)."""
|
||||
return sorted({p["on"] for p in doc.get("points") or [] if p.get("on")})
|
||||
|
||||
|
||||
def needs_body(doc: Mapping[str, Any]) -> bool:
|
||||
"""Whether a point is at a vertex of the model (resolved in the body)."""
|
||||
return any(p.get("vertex") for p in doc.get("points") or [])
|
||||
|
||||
|
||||
def _literal(values: list[float]) -> str:
|
||||
return "(" + ", ".join(repr(v) for v in values) + ")"
|
||||
|
||||
|
||||
def render(slug: str, doc: Mapping[str, Any], body: str | None) -> list[str]:
|
||||
"""The lines of the feature cell for a validated *doc*; the wire is bound to *slug*, model vertices resolve in *body*."""
|
||||
lines: list[str] = []
|
||||
used = {p for curve in doc["curves"] for p in curve["points"]}
|
||||
for point in doc["points"]:
|
||||
if point["id"] not in used:
|
||||
continue
|
||||
name = f"_{point['id']}"
|
||||
if point.get("vertex"):
|
||||
if body is None:
|
||||
raise CurveError(f"point {point['id']!r} is at a vertex of the model, and there is no body to find it in")
|
||||
code = _ref.ElementRef.from_dict(point["vertex"]).code()
|
||||
lines.append(f"{name} = {code}.one({body}).get_coordinates()")
|
||||
elif point.get("on"):
|
||||
u, v = point["uv"]
|
||||
lines.append(f"{name} = {point['on']}.point({u!r}, {v!r})")
|
||||
else:
|
||||
lines.append(f"{name} = {_literal(point['at'])}")
|
||||
edges = []
|
||||
for curve in doc["curves"]:
|
||||
names = [f"_{p}" for p in curve["points"]]
|
||||
if curve["kind"] == "line":
|
||||
edges.append(f"scad.make_segment_redge({names[0]}, {names[1]})")
|
||||
elif curve["kind"] == "arc":
|
||||
edges.append(f"scad.make_three_point_arc_redge({names[0]}, {names[1]}, {names[2]})")
|
||||
else:
|
||||
edges.append(f"scad.make_interpolated_spline_redge(points=[{', '.join(names)}])")
|
||||
lines.append(f"{slug} = scad.make_wire_from_edges_rwire([")
|
||||
lines.extend(f" {edge}," for edge in edges)
|
||||
lines.append("])")
|
||||
return lines
|
||||
|
||||
|
||||
__all__ = ["KINDS", "CurveError", "needs_body", "render", "validate", "workplanes_of"]
|
||||
@@ -33,7 +33,7 @@ from dataclasses import dataclass, field
|
||||
from typing import Any, Callable, Mapping, Sequence
|
||||
|
||||
from .. import ref as _ref
|
||||
from . import assembly_doc, sketch_doc
|
||||
from . import assembly_doc, curve_doc, sketch_doc
|
||||
from .selection import selector_conditions
|
||||
|
||||
GUI_MARKER = "# gui:"
|
||||
@@ -405,6 +405,22 @@ def _sketch(c: Context) -> list[str]:
|
||||
return lines
|
||||
|
||||
|
||||
def _curve(c: Context) -> list[str]:
|
||||
"""A 3D path: points in space, on workplanes, at model vertices; lines, arcs and splines joined into one wire."""
|
||||
doc = c.values["curve"]
|
||||
for workplane in curve_doc.workplanes_of(doc):
|
||||
c.body_named(workplane)
|
||||
body = None
|
||||
if curve_doc.needs_body(doc):
|
||||
if not c.values.get("body"):
|
||||
raise FeatureError("a point is at a vertex of the model, and there is no body yet")
|
||||
body = c.body("body")
|
||||
try:
|
||||
return curve_doc.render(c.slug, doc, body)
|
||||
except curve_doc.CurveError as exc:
|
||||
raise FeatureError(str(exc)) from exc
|
||||
|
||||
|
||||
def _assembly(c: Context) -> list[str]:
|
||||
cells = assembly_doc.render(c.slug, str(c.env.get("name") or c.slug), c.values["assembly"], c.env.get("notebook_dir"), c.env.get("workspace"))
|
||||
c.raw_params(cells["params"])
|
||||
@@ -684,6 +700,11 @@ SPECS: tuple[Spec, ...] = (
|
||||
(_BODY(), Slot("angle", "Angle", "angle", default=45.0, unit="deg", min=-360.0, max=360.0), _AXIS("axis", "Axis"), _point("origin", "Axis point")), _rotate),
|
||||
Spec("scale", "Scale", "Transform", "build", "solid", "Scale a body uniformly about a point.",
|
||||
(_BODY(), Slot("factor", "Factor", "float", default=1.5, min=0.01, max=100.0), _point("origin", "Centre")), _scale),
|
||||
Spec("curve", "3D curve", "Sketch", "datum", "wire",
|
||||
"A path in space: lines, arcs and splines through points in space, on workplanes or at vertices of the model, "
|
||||
"joined into one wire (a sweep path, a rail). Drawn in the viewport with snapping.",
|
||||
(dataclasses.replace(_BODY(), optional=True),
|
||||
Slot("curve", "Curve", "curve", default={"points": [], "curves": []})), _curve),
|
||||
Spec("workplane", "Workplane", "Datums", "datum", "workplane",
|
||||
"A workplane from picked geometry: on a planar face (x along an edge if one is picked, an offset along the normal), "
|
||||
"halfway between two parallel faces, through three vertices, or through an edge turned about it; or placed by hand "
|
||||
@@ -892,6 +913,11 @@ def check_values(spec: Spec, values: Mapping[str, Any], bodies: Mapping[str, str
|
||||
clean[slot.name] = sketch_doc.validate(raw)
|
||||
except sketch_doc.SketchError as exc:
|
||||
raise FeatureError(f"{slot.label}: {exc}") from exc
|
||||
elif slot.kind == "curve":
|
||||
try:
|
||||
clean[slot.name] = curve_doc.validate(raw)
|
||||
except curve_doc.CurveError as exc:
|
||||
raise FeatureError(f"{slot.label}: {exc}") from exc
|
||||
elif slot.kind == "assembly":
|
||||
try:
|
||||
clean[slot.name] = assembly_doc.validate(raw)
|
||||
|
||||
@@ -109,7 +109,9 @@ class FeatureService:
|
||||
if gui and gui["spec"] == "sketch": # a sketch makes a face or a wire, as its document says
|
||||
produces = sketch_doc.output_of(gui.get("values", {}).get("sketch") or {})
|
||||
part_of = head.slug[: -len("_parts")] if head.slug.endswith("_parts") and head.slug[: -len("_parts")] in assembly_slugs else None
|
||||
made = defined if head.role in _ROLES_WITH_BODIES and not part_of else []
|
||||
# a datum that is not a workplane (a 3D curve) is a value later features take (a sweep path), not a body
|
||||
makes_value = head.role == "datum" and produces not in ("workplane",)
|
||||
made = defined if (head.role in _ROLES_WITH_BODIES or makes_value) and not part_of else []
|
||||
for name in made:
|
||||
bodies[name] = produces
|
||||
order.append(name)
|
||||
@@ -228,6 +230,7 @@ class FeatureService:
|
||||
raise GuiError(str(exc)) from exc
|
||||
bodies = {b["name"]: b["produces"] for b in snap["bodies"]}
|
||||
values = self._with_defaults(spec_id, dict(request.get("values") or {}), snap)
|
||||
values = self._name_curve_points(spec_id, values)
|
||||
rendered = self._render(spec_id, slug, values, bodies, request.get("selections"), snap)
|
||||
self._check_param_names(rendered, taken)
|
||||
steps: list[dict] = []
|
||||
@@ -261,6 +264,7 @@ class FeatureService:
|
||||
spec_id = feature["gui"]["spec"]
|
||||
spec = F.BY_ID[spec_id]
|
||||
values = {**feature["gui"]["values"], **dict(request.get("values") or {})}
|
||||
values = self._name_curve_points(spec_id, values)
|
||||
bodies = {b["name"]: b["produces"] for b in snap["bodies"] if b["name"] != feature["slug"]}
|
||||
keep = {slot.name: F.extract_recipe(cell["code"], slot.name) for slot in spec.slots if slot.kind == "select"}
|
||||
rendered = self._render(spec_id, feature["slug"], values, bodies, request.get("selections"), snap, keep={k: v for k, v in keep.items() if v})
|
||||
@@ -431,6 +435,28 @@ class FeatureService:
|
||||
except Exception as exc: # noqa: BLE001 - the kernel's words are the message
|
||||
raise GuiError(str(exc)) from exc
|
||||
|
||||
def _name_curve_points(self, spec_id: str, values: dict[str, Any]) -> dict[str, Any]:
|
||||
"""A 3D curve's points snapped to a model vertex (``entity_id``) named by their stable reference (``vertex``),
|
||||
as a pick is; a vertex the kernel cannot name keeps its coordinates (``at``) only."""
|
||||
doc = values.get("curve") if spec_id == "curve" else None
|
||||
if not isinstance(doc, Mapping):
|
||||
return values
|
||||
points = [dict(p) for p in doc.get("points") or [] if isinstance(p, Mapping)]
|
||||
ids = [str(p["entity_id"]) for p in points if p.get("entity_id") and not p.get("vertex")]
|
||||
named: dict[str, Any] = {}
|
||||
kernel = getattr(self.state, "kernel", None)
|
||||
if ids and kernel is not None:
|
||||
try:
|
||||
answers = kernel.references("entity_refs", ids)
|
||||
except Exception: # noqa: BLE001 - no kernel answer: the coordinates
|
||||
answers = []
|
||||
named = {entity_id: answer.get("record") for entity_id, answer in zip(ids, answers or []) if isinstance(answer, Mapping)}
|
||||
for point in points:
|
||||
record = named.get(str(point.pop("entity_id", "")))
|
||||
if record:
|
||||
point["vertex"] = record
|
||||
return {**values, "curve": {**doc, "points": points}}
|
||||
|
||||
def _name_picks(self, picked: dict[str, list]) -> dict[str, list]:
|
||||
"""Each picked entity with its stable reference (``ref``: a record), named in the kernel from the value it
|
||||
was drawn from. An entity the kernel cannot name keeps no ``ref`` (its slot falls back to the older recipe)."""
|
||||
|
||||
@@ -587,6 +587,10 @@ class MarimoKernel:
|
||||
"try:\n"
|
||||
f" _p = _preview({url!r}, step={step!r})\n"
|
||||
" print('SCA-PREVIEWED', _p['nodes'], _p['parts'], _p['bytes'], _p.get('compile_ms', 0), _p.get('encode_ms', 0), _p.get('post_ms', 0))\n"
|
||||
# a cell failed: the model is the one before it (what failed, what is shown)
|
||||
" if _p.get('partial') is not None:\n"
|
||||
" import json as _pjson\n"
|
||||
" print('SCA-PARTIAL', _pjson.dumps(_p['partial']))\n"
|
||||
"except Exception as _e:\n"
|
||||
" print('SCA-PREVIEW-ERROR', type(_e).__name__ + ':', str(_e).splitlines()[0] if str(_e) else '')\n"
|
||||
# the workplanes ride along, product or not (a notebook mid-edit has workplanes before it has a product)
|
||||
@@ -596,6 +600,13 @@ class MarimoKernel:
|
||||
" print('SCA-WORKPLANES', _wjson.dumps(_workplanes()))\n"
|
||||
"except Exception:\n"
|
||||
" pass\n"
|
||||
# the notebook's wires and edges (3D paths, rails), sampled by the SDK: the viewport draws them
|
||||
"try:\n"
|
||||
" from simplecadapi.runtime.live_curves import live_curves as _curves\n"
|
||||
" import json as _cjson\n"
|
||||
" print('SCA-CURVES', _cjson.dumps(_curves()))\n"
|
||||
"except Exception:\n"
|
||||
" pass\n"
|
||||
# the tagged entities the model's operations split, with the entities of their pieces (a diagnostic)
|
||||
"try:\n"
|
||||
" from simplecadapi.runtime.live import live_tag_splits as _splits\n"
|
||||
@@ -614,11 +625,21 @@ class MarimoKernel:
|
||||
out["workplanes"] = json.loads(line[len("SCA-WORKPLANES "):])
|
||||
except ValueError:
|
||||
pass
|
||||
elif line.startswith("SCA-CURVES "):
|
||||
try:
|
||||
out["curves"] = json.loads(line[len("SCA-CURVES "):])
|
||||
except ValueError:
|
||||
pass
|
||||
elif line.startswith("SCA-TAGSPLITS "):
|
||||
try:
|
||||
out["tag_splits"] = json.loads(line[len("SCA-TAGSPLITS "):])
|
||||
except ValueError:
|
||||
pass
|
||||
elif line.startswith("SCA-PARTIAL "):
|
||||
try:
|
||||
out["partial"] = json.loads(line[len("SCA-PARTIAL "):])
|
||||
except ValueError:
|
||||
pass
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -123,6 +123,7 @@ class WorkspaceState:
|
||||
"selection",
|
||||
"workplanes",
|
||||
"tag_splits",
|
||||
"curves",
|
||||
)
|
||||
|
||||
def __init__(self, workspace: Path, notebook: Path | None = None) -> None:
|
||||
@@ -135,6 +136,9 @@ class WorkspaceState:
|
||||
self.latest: dict[str, dict] = {}
|
||||
self._workplanes: list[dict] | None = None # the frames last sent (see _push_workplanes)
|
||||
self._tag_splits: list[dict] | None = None # the tag splits last sent (see _push_tag_splits)
|
||||
self._curves: list[dict] | None = None # the curves last sent (see _push_curves)
|
||||
# A cell failed and the model shown is the one before it: {failed, skipped, shown} (see runtime.live.preview_product)
|
||||
self.partial: dict | None = None
|
||||
self.latest_package_bytes: bytes | None = None # a full package, made on demand (export)
|
||||
# The latest preview (replaced as a whole, so a reader on another thread never sees half of one) and the
|
||||
# parts of it by key: a page is sent only the parts it lacks.
|
||||
@@ -272,6 +276,8 @@ class WorkspaceState:
|
||||
restored = self._restore(notebook, generation)
|
||||
self._workplanes = None # a new notebook: its workplanes are sent on its first settle, whatever they are
|
||||
self._tag_splits = None
|
||||
self._curves = None
|
||||
self.partial = None
|
||||
kernel = MarimoKernel(
|
||||
notebook,
|
||||
server_port=self.port,
|
||||
@@ -428,6 +434,7 @@ class WorkspaceState:
|
||||
"name": notebook.stem,
|
||||
"size": len(data),
|
||||
"cached": True,
|
||||
"partial": None, # only a whole model is filed
|
||||
}
|
||||
)
|
||||
self.hub.broadcast({"type": "status", "info": "restored from the last run; the kernel is starting…"})
|
||||
@@ -1144,6 +1151,7 @@ class WorkspaceState:
|
||||
published = time.perf_counter()
|
||||
self.push_cells()
|
||||
self._push_workplanes(result.get("workplanes"))
|
||||
self._push_curves(result.get("curves"))
|
||||
if result.get("ok"): # a failed preview keeps what was last shown
|
||||
self._push_tag_splits(result.get("tag_splits"))
|
||||
if os.environ.get("SCA_EDITOR_TRACE"):
|
||||
@@ -1174,6 +1182,14 @@ class WorkspaceState:
|
||||
self._last_publish_error = message
|
||||
self.hub.broadcast({"type": "status", "error": message[-300:]})
|
||||
|
||||
def _push_curves(self, curves: Any) -> None:
|
||||
"""The notebook's wires and edges, sampled by the kernel (3D paths are not solids: the preview does not draw
|
||||
them): sent when they change."""
|
||||
if not isinstance(curves, list) or curves == (self._curves or []):
|
||||
return
|
||||
self._curves = curves
|
||||
self.emit({"type": "curves", "curves": curves})
|
||||
|
||||
def _push_tag_splits(self, splits: Any) -> None:
|
||||
"""The tagged entities the model's operations split, and the entities of their pieces: sent when they change."""
|
||||
if not isinstance(splits, list) or splits == (self._tag_splits or []):
|
||||
@@ -1495,8 +1511,9 @@ class WorkspaceState:
|
||||
saved = read_saved_params(config)
|
||||
# A drag that pauses and is then released sends its value twice (the pause, the release): the second is
|
||||
# what the model already shows. Rebuilding for it would run the cells that depend on child notebooks
|
||||
# again for nothing -- unless the last run failed, when the person may be asking for a retry.
|
||||
if not self._last_publish_error:
|
||||
# again for nothing -- unless the last run failed (no model, or the model before a failing step), when the person
|
||||
# may be asking for a retry.
|
||||
if not self._last_publish_error and self.partial is None:
|
||||
values = {name: value for name, value in values.items() if saved.get(name, self.specs[name].default) != value}
|
||||
if not values:
|
||||
self.emit_params() # keep the page's controls in step
|
||||
@@ -1673,6 +1690,9 @@ class WorkspaceState:
|
||||
},
|
||||
"modified_parameters": sorted(saved),
|
||||
"model_revision": self.preview_revision,
|
||||
# a cell failed: the model shown is the one before it -- failed: [{cell, name, status, error}], skipped: the
|
||||
# cells after it that did not run, shown: the bodies (or product) on screen; null when the model is whole
|
||||
"partial": self.partial,
|
||||
# tagged entities the model's operations split: the pieces carry <tag>.split<i>, highlighted in the viewport
|
||||
"tag_splits": [
|
||||
{"tag": row.get("tag"), "into": row.get("into"), "op": row.get("op")} for row in self._tag_splits or []
|
||||
@@ -1931,6 +1951,17 @@ def _is_function_cell(code: str) -> bool:
|
||||
return len(body) == 1 and isinstance(body[0], (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))
|
||||
|
||||
|
||||
def _partial_header(text: str | None) -> dict | None:
|
||||
"""The ``X-Preview-Partial`` header of a published preview: what failed and what the model shown is (else ``None``)."""
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
partial = json.loads(text)
|
||||
except ValueError:
|
||||
return None
|
||||
return partial if isinstance(partial, dict) else None
|
||||
|
||||
|
||||
def create_app(state: WorkspaceState) -> Starlette:
|
||||
hub = state.hub
|
||||
|
||||
@@ -1962,6 +1993,8 @@ def create_app(state: WorkspaceState) -> Starlette:
|
||||
except KeyError as missing:
|
||||
# Parts the kernel left out are not here (the server was given another model since): it sends them all.
|
||||
return JSONResponse({"ok": False, "missing": missing.args[0]}, status_code=409)
|
||||
partial = _partial_header(request.headers.get("X-Preview-Partial"))
|
||||
state.partial = partial
|
||||
state.preview_revision += 1
|
||||
state.emit(
|
||||
{
|
||||
@@ -1972,6 +2005,8 @@ def create_app(state: WorkspaceState) -> Starlette:
|
||||
"size": len(state.latest_preview_bytes or b""),
|
||||
# The model on screen is this model: nothing to reload.
|
||||
"unchanged": unchanged,
|
||||
# A cell failed: this is the model before it ({failed, skipped, shown}); None for the whole product.
|
||||
"partial": partial,
|
||||
}
|
||||
)
|
||||
# The pages have the model. Filing it on disk (and the snapshot an agent reads) wait for nothing: the kernel
|
||||
@@ -1979,7 +2014,8 @@ def create_app(state: WorkspaceState) -> Starlette:
|
||||
hub.broadcast({"type": "status", "error": ""}) # the model is fine again: clear a stale "no product yet"
|
||||
threading.Thread(
|
||||
target=state.after_publish,
|
||||
args=(arrived, len(body), state.take_signing(), state.latest_preview_bytes),
|
||||
# the model before a failing step is not filed: a restart restores only a whole model
|
||||
args=(arrived, len(body), state.take_signing(), None if partial else state.latest_preview_bytes),
|
||||
name="after-publish",
|
||||
daemon=True,
|
||||
).start()
|
||||
|
||||
@@ -145,6 +145,7 @@ from simplecadapi._cpp import (
|
||||
project_rsketch,
|
||||
trim_rsketch,
|
||||
insert_spline_anchor_rsketch,
|
||||
make_faces_from_sketch_rfacelist,
|
||||
remove_spline_anchor_rsketch,
|
||||
convert_spline_to_anchors_rsketch,
|
||||
constrain_mirror_rsketch,
|
||||
@@ -454,6 +455,7 @@ __all__ = [
|
||||
"translate_shape",
|
||||
"trim_rsketch",
|
||||
"insert_spline_anchor_rsketch",
|
||||
"make_faces_from_sketch_rfacelist",
|
||||
"remove_spline_anchor_rsketch",
|
||||
"convert_spline_to_anchors_rsketch",
|
||||
"trim_surface_rface",
|
||||
|
||||
@@ -35,6 +35,7 @@ from simplecadapi._cpp import (
|
||||
inspect_sketch_rsketchprofiles,
|
||||
inspect_sketch_rsketchcrossings,
|
||||
make_face_from_sketch_rface,
|
||||
make_faces_from_sketch_rfacelist,
|
||||
make_sketch_rsketch,
|
||||
make_wire_from_sketch_rwire,
|
||||
project_rsketch,
|
||||
@@ -124,6 +125,7 @@ __all__ = [
|
||||
"inspect_sketch_rsketchprofiles",
|
||||
"inspect_sketch_rsketchcrossings",
|
||||
"make_face_from_sketch_rface",
|
||||
"make_faces_from_sketch_rfacelist",
|
||||
"make_sketch_rsketch",
|
||||
"make_wire_from_sketch_rwire",
|
||||
"project_rsketch",
|
||||
|
||||
@@ -8,6 +8,12 @@ same product wherever it runs.
|
||||
|
||||
The editor's bridge calls :func:`publish_live` from a snippet it executes
|
||||
in the kernel once the cells have settled.
|
||||
|
||||
A cell that fails leaves no values, and the cells after it that read them do
|
||||
not run: the product is not made. The preview then shows what the notebook
|
||||
does have, the model as it is before the failing step, and says so
|
||||
(:func:`preview_product`): a changed parameter that breaks a feature shows the
|
||||
body that feature was applied to, not the last model that built.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,6 +23,7 @@ import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from dataclasses import dataclass
|
||||
from collections.abc import Iterable, Mapping, Set as AbstractSet
|
||||
from typing import Any
|
||||
|
||||
from ..artifacts.assembly_io import attached_definition
|
||||
@@ -24,9 +31,10 @@ from ..product.packages import build_product_package, encode_product_package
|
||||
from ..scene.preview import PreviewScene, compile_preview, encode_preview, entity_info
|
||||
from ._marimo import safe_get_context
|
||||
from .cells import NotebookCells
|
||||
from .config import read_notebook_config
|
||||
from .config import NotebookConfig, read_notebook_config
|
||||
from .executor import finish_kernel_cache
|
||||
from .projection import find_product, product_reads, project_product
|
||||
from .projection import Product, ProductNotFoundError, find_product, open_bodies, product_reads, project_product
|
||||
from .workspace import features_in_cell
|
||||
|
||||
PACKAGE_MEDIA_TYPE = "application/vnd.simplecad.scadpkg"
|
||||
PREVIEW_MEDIA_TYPE = "application/vnd.simplecad.preview"
|
||||
@@ -50,31 +58,27 @@ def live_package(*, validate: bool = False) -> LivePackage:
|
||||
|
||||
Call from inside the marimo kernel. Raises :class:`LiveUnavailableError`
|
||||
outside one, and :class:`~.projection.ProductNotFoundError` while no
|
||||
cell has produced the product yet (or a cell failed). ``validate``
|
||||
cell has produced the product yet, or a cell it is built from failed. ``validate``
|
||||
runs the package's full contract validation; the live path skips it.
|
||||
"""
|
||||
|
||||
context = safe_get_context()
|
||||
if context is None or context.filename is None:
|
||||
raise LiveUnavailableError("not running inside a marimo kernel")
|
||||
config = read_notebook_config(context.filename)
|
||||
if config is None:
|
||||
raise LiveUnavailableError(
|
||||
f"{context.filename}: not a SimpleCAD notebook (no [tool.simplecadapi])"
|
||||
)
|
||||
scope = live_scope()
|
||||
config = scope.config
|
||||
finish_kernel_cache(config) # the product is modified below: let the cache finish pickling it
|
||||
glbls = context.globals
|
||||
ordered = list(context.graph.cells.values())
|
||||
cells = NotebookCells(config.path, ordered)
|
||||
values = {
|
||||
name: glbls[name] for cell in ordered for name in cell.defs if name in glbls
|
||||
}
|
||||
read = product_reads(ordered, values)
|
||||
found, partial = preview_product(
|
||||
config, scope.cells, scope.values, failed=scope.failed, skipped=scope.skipped, lost_reads=scope.lost_reads
|
||||
)
|
||||
if partial is not None:
|
||||
# a package is the whole product: the model before a failing step is only previewed
|
||||
first = scope.failed[0]
|
||||
raise ProductNotFoundError(
|
||||
f"{config.path.name}: {first.name} failed ({first.error or first.status}); fix it to make the product"
|
||||
)
|
||||
product = project_product(
|
||||
find_product(config, values, read),
|
||||
found,
|
||||
config=config,
|
||||
cells=cells,
|
||||
values=values.values(),
|
||||
cells=NotebookCells(config.path, list(scope.ordered)),
|
||||
values=scope.values.values(),
|
||||
)
|
||||
definition = attached_definition(product)
|
||||
# project_product attaches one to every product it returns.
|
||||
@@ -95,11 +99,87 @@ last_timings: dict[str, float] = {}
|
||||
"""Milliseconds the last :func:`live_preview` / :func:`publish_preview` spent: ``compile_ms``, ``encode_ms``, ``post_ms``."""
|
||||
|
||||
|
||||
def _live_scene() -> PreviewScene:
|
||||
"""The preview scene of the running notebook's product (not yet encoded)."""
|
||||
_FAILED = frozenset({"exception", "interrupted", "marimo-error"})
|
||||
"""The marimo run states of a cell that did not finish: it raised, was stopped, or could not run (a syntax error, a name
|
||||
defined twice)."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FailedCell:
|
||||
"""A cell of the notebook that did not finish, as a preview reports it."""
|
||||
|
||||
cell_id: str
|
||||
name: str
|
||||
"""The feature the cell makes (its ``# ---- feature:`` header), else the cell's name, else what it defines."""
|
||||
status: str
|
||||
"""marimo's run state: ``exception``, ``interrupted`` or ``marimo-error``."""
|
||||
error: str
|
||||
"""``Type: message`` (cut short), empty when marimo kept no exception."""
|
||||
|
||||
def to_dict(self) -> dict[str, str]:
|
||||
return {"cell": self.cell_id, "name": self.name, "status": self.status, "error": self.error}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LiveScope:
|
||||
"""The values of the running notebook that a preview can be made from.
|
||||
|
||||
The cells that failed, and every cell downstream of one, are left out: in lazy mode marimo does not clear the values a
|
||||
blocked descendant made in an earlier run, and a failed cell may have bound some names before it raised.
|
||||
"""
|
||||
|
||||
config: NotebookConfig
|
||||
cells: list[Any]
|
||||
"""The marimo cells that are left (not failed, not downstream of a failed cell)."""
|
||||
values: dict[str, object]
|
||||
"""Their top-level values."""
|
||||
failed: tuple[FailedCell, ...] = ()
|
||||
"""The cells that failed and are downstream of no other failed cell (the failing steps), in notebook order."""
|
||||
skipped: tuple[str, ...] = ()
|
||||
"""The ids of the cells left out because a cell upstream of them failed."""
|
||||
lost_reads: frozenset[str] = frozenset()
|
||||
"""The names the failed and skipped cells read: what they would have built on."""
|
||||
ordered: tuple[Any, ...] = ()
|
||||
"""Every marimo cell of the notebook (the source positions of a projection are looked up in all of them)."""
|
||||
|
||||
|
||||
def _cell_name(cell: Any) -> str:
|
||||
found = features_in_cell(getattr(cell, "code", "") or "")
|
||||
if found:
|
||||
return found[0].slug
|
||||
name = getattr(cell, "name", "") or ""
|
||||
if name and name != "_":
|
||||
return name
|
||||
defs = sorted(name for name in getattr(cell, "defs", ()) if not name.startswith("_"))
|
||||
return ", ".join(defs) if defs else f"cell {cell.cell_id}"
|
||||
|
||||
|
||||
def _cell_error(cell: Any) -> str:
|
||||
"""``Type: message`` of the exception a failed cell raised, short: an SDK error by its operation and what happened."""
|
||||
|
||||
error = getattr(cell, "exception", None)
|
||||
if error is None:
|
||||
return ""
|
||||
text = ""
|
||||
try:
|
||||
details = error.to_dict() if callable(getattr(error, "to_dict", None)) else None
|
||||
except Exception: # noqa: BLE001 - the message is a courtesy, never a second failure
|
||||
details = None
|
||||
if isinstance(details, dict) and details.get("what_happened"):
|
||||
operation = details.get("operation") or getattr(error, "operation", "")
|
||||
text = f"{operation}: {details['what_happened']}" if operation else str(details["what_happened"])
|
||||
else:
|
||||
text = next((line.strip() for line in str(error).splitlines() if line.strip()), "")
|
||||
text = " ".join(text.split())
|
||||
return f"{type(error).__name__}: {text}"[:400] if text else type(error).__name__
|
||||
|
||||
|
||||
def live_scope() -> LiveScope:
|
||||
"""The values the running notebook's cells hold, without the failed cells and those downstream of them.
|
||||
|
||||
Call from inside the marimo kernel; raises :class:`LiveUnavailableError` outside one.
|
||||
"""
|
||||
|
||||
global _last_preview
|
||||
started = time.perf_counter()
|
||||
context = safe_get_context()
|
||||
if context is None or context.filename is None:
|
||||
raise LiveUnavailableError("not running inside a marimo kernel")
|
||||
@@ -108,13 +188,94 @@ def _live_scene() -> PreviewScene:
|
||||
raise LiveUnavailableError(
|
||||
f"{context.filename}: not a SimpleCAD notebook (no [tool.simplecadapi])"
|
||||
)
|
||||
graph = context.graph
|
||||
ordered = list(graph.cells.values())
|
||||
failed = [cell for cell in ordered if getattr(cell, "run_result_status", None) in _FAILED]
|
||||
lost: set[str] = set()
|
||||
for cell in failed:
|
||||
lost |= graph.descendants(cell.cell_id)
|
||||
roots = [cell for cell in failed if cell.cell_id not in lost]
|
||||
failed_ids = {cell.cell_id for cell in failed}
|
||||
lost |= failed_ids
|
||||
kept = [cell for cell in ordered if cell.cell_id not in lost]
|
||||
glbls = context.globals
|
||||
ordered = list(context.graph.cells.values())
|
||||
values = {name: glbls[name] for cell in ordered for name in cell.defs if name in glbls}
|
||||
read = product_reads(ordered, values)
|
||||
scene = compile_preview(find_product(config, values, read))
|
||||
return LiveScope(
|
||||
config=config,
|
||||
cells=kept,
|
||||
values={name: glbls[name] for cell in kept for name in cell.defs if name in glbls},
|
||||
failed=tuple(
|
||||
FailedCell(cell.cell_id, _cell_name(cell), str(cell.run_result_status), _cell_error(cell)) for cell in roots
|
||||
),
|
||||
skipped=tuple(cell.cell_id for cell in ordered if cell.cell_id in lost and cell.cell_id not in failed_ids),
|
||||
lost_reads=frozenset(name for cell in ordered if cell.cell_id in lost for name in cell.refs),
|
||||
ordered=tuple(ordered),
|
||||
)
|
||||
|
||||
|
||||
def preview_product(
|
||||
config: NotebookConfig,
|
||||
cells: Iterable[Any],
|
||||
values: Mapping[str, object],
|
||||
*,
|
||||
failed: Iterable[FailedCell] = (),
|
||||
skipped: Iterable[str] = (),
|
||||
lost_reads: AbstractSet[str] = frozenset(),
|
||||
) -> tuple[Product, dict[str, Any] | None]:
|
||||
"""The product to preview from *values* (the cells that are left, see :class:`LiveScope`), and whether it is partial.
|
||||
|
||||
With no failed cell this is :func:`~.projection.find_product`. With one, the product is found the same way among the
|
||||
values that are left, the cells read by the failed and skipped cells no longer counting: a part notebook's open bodies
|
||||
are then the bodies the failing feature was applied to, an assembly built up over cells is the assembly before the
|
||||
failing step. The second item says what is shown (``None`` when the product is whole): ``{"failed": [...], "skipped":
|
||||
[cell ids], "shown": [names]}``. A product no failed cell would have built on (an explicit product upstream of none of
|
||||
them) is whole. Raises :class:`~.projection.ProductNotFoundError` when nothing is left to show, naming the failed cell.
|
||||
"""
|
||||
|
||||
failed = tuple(failed)
|
||||
cells = list(cells)
|
||||
read = product_reads(cells, values)
|
||||
try:
|
||||
product = find_product(config, values, read)
|
||||
except ProductNotFoundError as error:
|
||||
if not failed:
|
||||
raise
|
||||
first = failed[0]
|
||||
raise ProductNotFoundError(
|
||||
f"{config.path.name}: {first.name} failed ({first.error or first.status}); the cells before it make no model"
|
||||
) from error
|
||||
if not failed:
|
||||
return product, None
|
||||
names = [name for name, value in values.items() if value is product or getattr(value, "value", None) is product]
|
||||
if names and not set(names) & lost_reads:
|
||||
return product, None
|
||||
return product, {
|
||||
"failed": [cell.to_dict() for cell in failed],
|
||||
"skipped": list(skipped),
|
||||
"shown": names or open_bodies(values, read),
|
||||
}
|
||||
|
||||
|
||||
_last_partial: dict[str, Any] | None = None
|
||||
"""What :func:`preview_product` said of the scene last previewed: ``None`` when it is the whole product."""
|
||||
|
||||
|
||||
def _live_scene() -> PreviewScene:
|
||||
"""The preview scene of the running notebook's product (not yet encoded); partial when a cell failed."""
|
||||
|
||||
global _last_preview, _last_partial
|
||||
started = time.perf_counter()
|
||||
scope = live_scope()
|
||||
product, partial = preview_product(
|
||||
scope.config,
|
||||
scope.cells,
|
||||
scope.values,
|
||||
failed=scope.failed,
|
||||
skipped=scope.skipped,
|
||||
lost_reads=scope.lost_reads,
|
||||
)
|
||||
scene = compile_preview(product)
|
||||
last_timings["compile_ms"] = round((time.perf_counter() - started) * 1000, 1)
|
||||
_last_preview = scene
|
||||
_last_preview, _last_partial = scene, partial
|
||||
return scene
|
||||
|
||||
|
||||
@@ -138,12 +299,11 @@ _posted: set[str] = set()
|
||||
|
||||
|
||||
def _post(url: str, data: bytes, step: str, delta: bool, timeout: float) -> None:
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={"Content-Type": PREVIEW_MEDIA_TYPE, "X-Live-Step": step, "X-Preview-Delta": "1" if delta else "0"},
|
||||
method="POST",
|
||||
)
|
||||
headers = {"Content-Type": PREVIEW_MEDIA_TYPE, "X-Live-Step": step, "X-Preview-Delta": "1" if delta else "0"}
|
||||
if _last_partial is not None:
|
||||
# the scene is the model before a failing step: the server tells the pages with the model itself (ASCII JSON)
|
||||
headers["X-Preview-Partial"] = json.dumps(_last_partial)
|
||||
request = urllib.request.Request(url, data=data, headers=headers, method="POST")
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
response.read()
|
||||
|
||||
@@ -161,7 +321,8 @@ def _server_words(error: urllib.error.HTTPError) -> str:
|
||||
def publish_preview(url: str, *, step: str = "", timeout: float = 60.0) -> dict[str, Any]:
|
||||
""":func:`live_preview`, then POST it to *url*; returns a short summary.
|
||||
|
||||
Only the parts the server does not hold are sent: it keeps the parts of the model it was last given, so after a
|
||||
When a cell failed the preview is of the model before it (see :func:`preview_product`): the post says so (its
|
||||
``X-Preview-Partial`` header) and so does the summary (``partial``). Only the parts the server does not hold are sent: it keeps the parts of the model it was last given, so after a
|
||||
joint angle changed nothing but the nodes travel. When the server answers that it lacks a part (it was given
|
||||
another model meanwhile) the whole preview is sent.
|
||||
"""
|
||||
@@ -186,7 +347,7 @@ def publish_preview(url: str, *, step: str = "", timeout: float = 60.0) -> dict[
|
||||
raise RuntimeError(f"publishing the preview to {url} failed: {error}") from error
|
||||
_posted = set(scene.parts)
|
||||
last_timings["post_ms"] = round((time.perf_counter() - posted) * 1000, 1)
|
||||
return {"nodes": len(scene.nodes), "parts": len(scene.parts), "bytes": len(data), **last_timings}
|
||||
return {"nodes": len(scene.nodes), "parts": len(scene.parts), "bytes": len(data), **last_timings, "partial": _last_partial}
|
||||
|
||||
|
||||
def workplane_frames(values: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
@@ -297,6 +458,10 @@ def publish_live(url: str, *, step: str = "", timeout: float = 60.0) -> LivePack
|
||||
|
||||
|
||||
__all__ = [
|
||||
"FailedCell",
|
||||
"LiveScope",
|
||||
"live_scope",
|
||||
"preview_product",
|
||||
"live_tag_splits",
|
||||
"live_workplanes",
|
||||
"scene_tag_splits",
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
"""The curves of a running notebook, for a viewer: every top-level wire and edge value, sampled by the SDK.
|
||||
|
||||
A part's preview draws its solids; a 3D path, a sweep rail or a sketch made into a wire is not a solid, so it would not
|
||||
be seen. :func:`curve_samples` gives each such value as polylines (one per edge, world mm), sampled with the SDK's own
|
||||
``sample_curve_rcurvature`` along the curve's parameter, so what the viewer draws is the kernel's curve, not a guess.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from typing import Any, Mapping
|
||||
|
||||
from .._cpp import Edge, Wire, ql, sample_curve_rcurvature
|
||||
from ._marimo import safe_get_context
|
||||
|
||||
_SAMPLES = 48
|
||||
"""Points per edge: an arc or a spline reads smooth; a straight edge needs two, and gets them."""
|
||||
|
||||
|
||||
def _edge_points(edge: Any) -> list[list[float]]:
|
||||
if edge._geom_type() == "LINE":
|
||||
start, end = edge.get_start_vertex().get_coordinates(), edge.get_end_vertex().get_coordinates()
|
||||
return [list(start), list(end)]
|
||||
samples = sample_curve_rcurvature(edge, _SAMPLES)
|
||||
return [list(point) for point in samples["points"]]
|
||||
|
||||
|
||||
def curve_samples(values: Mapping[str, object]) -> list[dict[str, Any]]:
|
||||
"""``{name, kind, edges: [[[x, y, z], ...], ...]}`` for each top-level wire or edge among *values* (private names
|
||||
left out); a value that cannot be sampled is left out rather than failing the preview."""
|
||||
out: list[dict[str, Any]] = []
|
||||
for name, value in values.items():
|
||||
if name.startswith("_") or not isinstance(value, (Wire, Edge)):
|
||||
continue
|
||||
try:
|
||||
edges = ql.edges().resolve(value) if isinstance(value, Wire) else [value]
|
||||
polylines = [_edge_points(edge) for edge in edges]
|
||||
except Exception: # noqa: BLE001 - a curve the sampler refuses is not drawn
|
||||
continue
|
||||
if all(all(math.isfinite(c) for p in line for c in p) for line in polylines):
|
||||
out.append({"name": name, "kind": "wire" if isinstance(value, Wire) else "edge", "edges": polylines})
|
||||
return out
|
||||
|
||||
|
||||
def live_curves() -> list[dict[str, Any]]:
|
||||
""":func:`curve_samples` of the running notebook's values; empty outside a kernel."""
|
||||
context = safe_get_context()
|
||||
if context is None:
|
||||
return []
|
||||
glbls = context.globals
|
||||
values = {name: glbls[name] for cell in context.graph.cells.values() for name in cell.defs if name in glbls}
|
||||
return curve_samples(values)
|
||||
|
||||
|
||||
__all__ = ["curve_samples", "live_curves"]
|
||||
@@ -39,7 +39,7 @@ from ..build.results import AssemblyBuildResult, PartBuildResult
|
||||
import weakref
|
||||
from typing import Any
|
||||
|
||||
from simplecadapi._cpp import Assembly, find_registered_node, isolated_recording, Part, SimpleWorkplane, Solid
|
||||
from simplecadapi._cpp import Assembly, Edge, find_registered_node, isolated_recording, Part, SimpleWorkplane, Solid, Wire
|
||||
from simplecadapi._glue.session import lineage_of
|
||||
from ..product.bodies import part_from_bodies
|
||||
from simplecadapi._glue.session import GraphSession
|
||||
@@ -66,17 +66,21 @@ def _as_product(value: object) -> Product | None:
|
||||
return None
|
||||
|
||||
|
||||
_CONSTRUCTION = (SimpleWorkplane, Wire, Edge)
|
||||
"""Values that are construction geometry, not bodies: a cell making only these does not build on what it reads."""
|
||||
|
||||
|
||||
def product_reads(cells: Iterable[Any], values: Mapping[str, object]) -> frozenset[str]:
|
||||
"""The names the cells read, as :func:`find_product` and :func:`open_bodies` take them (*read*).
|
||||
|
||||
A cell whose values are all workplanes reads a body without building on it (a workplane on the top face of ``base``
|
||||
is a datum, not a feature of the body): its reads leave the body open.
|
||||
A cell whose values are all construction geometry -- workplanes, wires, edges -- reads a body without building on it
|
||||
(a workplane on the top face of ``base``, a 3D path drawn through its vertices): its reads leave the body open.
|
||||
"""
|
||||
|
||||
out: set[str] = set()
|
||||
for cell in cells:
|
||||
made = [values[name] for name in cell.defs if name in values]
|
||||
if made and all(isinstance(value, SimpleWorkplane) for value in made):
|
||||
if made and all(isinstance(value, _CONSTRUCTION) for value in made):
|
||||
continue
|
||||
out.update(cell.refs)
|
||||
return frozenset(out)
|
||||
|
||||
@@ -167,11 +167,16 @@ def anchors_for_role(shape: Any, role: str) -> List[Dict[str, Any]]:
|
||||
def _size(entity: Any) -> float:
|
||||
if type(entity).__name__ == "Solid":
|
||||
return float(entity.get_volume())
|
||||
if type(entity).__name__ == "Vertex":
|
||||
return 0.0 # a point has no size: its centre is all there is to it
|
||||
return float(entity.get_area()) if hasattr(entity, "get_area") else float(entity.get_length())
|
||||
|
||||
|
||||
def _geom_type(entity: Any) -> str:
|
||||
return "SOLID" if type(entity).__name__ == "Solid" else entity._geom_type()
|
||||
kind = type(entity).__name__
|
||||
if kind in ("Solid", "Vertex"):
|
||||
return kind.upper()
|
||||
return entity._geom_type()
|
||||
|
||||
|
||||
def guard_of(entity: Any) -> Dict[str, Any]:
|
||||
@@ -211,7 +216,7 @@ def _geometric_order(candidates: List[Candidate]) -> List[Candidate]:
|
||||
def _ranked_lookalikes(shape: Any, guard: Dict[str, Any], kind: str, limit: int = 5) -> List[Candidate]:
|
||||
from .. import ql
|
||||
|
||||
factory = {"face": ql.faces, "edge": ql.edges, "solid": ql.solids}.get(kind)
|
||||
factory = {"face": ql.faces, "edge": ql.edges, "vertex": ql.vertices, "solid": ql.solids}.get(kind)
|
||||
if factory is None:
|
||||
return []
|
||||
out: List[Candidate] = []
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""A 3D curve drawn in the editor: its document, the cell it becomes, and that the cell runs to one wire that follows the
|
||||
workplanes and model vertices it was drawn on."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
import simplecadapi as scad
|
||||
from simplecadapi.editor import curve_doc
|
||||
from simplecadapi.editor import features as F
|
||||
from simplecadapi.runtime.live_curves import curve_samples
|
||||
from simplecadapi.runtime.projection import product_reads
|
||||
|
||||
|
||||
def _doc(vertex: dict | None = None) -> dict:
|
||||
first = {"id": "p1", "vertex": vertex, "at": [0, 0, 0]} if vertex else {"id": "p1", "at": [0, 0, 0]}
|
||||
return {
|
||||
"points": [first, {"id": "p2", "on": "wp", "uv": [10, 0]}, {"id": "p3", "at": [20, 5, 30]}, {"id": "p4", "at": [30, 0, 40]}],
|
||||
"curves": [
|
||||
{"id": "c1", "kind": "line", "points": ["p1", "p2"]},
|
||||
{"id": "c2", "kind": "arc", "points": ["p2", "p3", "p4"]},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _run(code: str, **names) -> dict:
|
||||
scope = {"scad": scad, **names}
|
||||
exec(code, scope)
|
||||
return scope
|
||||
|
||||
|
||||
def test_a_curve_is_one_wire_through_a_workplane_and_a_model_vertex():
|
||||
with scad.GraphSession():
|
||||
base = scad.make_box_rsolid(20.0, 20.0, 10.0)
|
||||
corner = scad.ql.vertices().where(scad.ql.prop("geom.center.z", ">=", 9.9)).resolve(base)[0]
|
||||
record = scad.ref.of(corner, base).to_dict()
|
||||
wp = scad.make_workplane_offset_rworkplane("XY", offset=(0.0, 0.0, 20.0))
|
||||
rendered = F.render_feature("curve", "path", {"curve": _doc(record), "body": "base"}, bodies={"base": "solid"})
|
||||
assert rendered.produces == "wire" and set(rendered.reads) == {"wp", "base"}
|
||||
body = "\n".join(line for line in rendered.feature.splitlines() if not line.startswith("#"))
|
||||
assert "wp.point(10.0, 0.0)" in body and "scad.ref.vertex(" in body
|
||||
path = _run(body, base=base, wp=wp)["path"]
|
||||
start, end = path.get_edges(0).get_start_vertex().get_coordinates(), path.get_edges(1).get_end_vertex().get_coordinates()
|
||||
assert start == pytest.approx(tuple(corner.get_coordinates()))
|
||||
assert end == pytest.approx((30.0, 0.0, 40.0))
|
||||
# the workplane moves: the point drawn on it moves with it
|
||||
higher = scad.make_workplane_offset_rworkplane("XY", offset=(0.0, 0.0, 25.0))
|
||||
moved = _run(body, base=base, wp=higher)["path"]
|
||||
assert moved.get_edges(0).get_end_vertex().get_coordinates() == pytest.approx((10.0, 0.0, 25.0))
|
||||
samples = curve_samples({"path": path, "_hidden": path})
|
||||
assert [s["name"] for s in samples] == ["path"] and [len(e) for e in samples[0]["edges"]] == [2, 48]
|
||||
|
||||
|
||||
def test_a_curve_document_is_checked():
|
||||
with pytest.raises(curve_doc.CurveError, match="must start where"):
|
||||
curve_doc.validate({"points": [{"id": "a", "at": [0, 0, 0]}, {"id": "b", "at": [1, 0, 0]}, {"id": "c", "at": [2, 0, 0]}],
|
||||
"curves": [{"id": "c1", "kind": "line", "points": ["a", "b"]}, {"id": "c2", "kind": "line", "points": ["a", "c"]}]})
|
||||
with pytest.raises(curve_doc.CurveError, match="an arc takes 3"):
|
||||
curve_doc.validate({"points": [{"id": "a", "at": [0, 0, 0]}, {"id": "b", "at": [1, 0, 0]}], "curves": [{"id": "c1", "kind": "arc", "points": ["a", "b"]}]})
|
||||
with pytest.raises(F.FeatureError, match="no body yet"):
|
||||
F.render_feature("curve", "path", {"curve": _doc({"kind": "vertex", "feature": "", "op": "make_box_rsolid", "topo": "vertex_0"})}, bodies={})
|
||||
|
||||
|
||||
def test_a_cell_that_only_draws_a_curve_through_the_body_leaves_it_the_product():
|
||||
class Cell:
|
||||
def __init__(self, defs, refs):
|
||||
self.defs, self.refs = defs, refs
|
||||
|
||||
with scad.GraphSession():
|
||||
base = scad.make_box_rsolid(10.0, 10.0, 10.0)
|
||||
path = scad.make_wire_from_edges_rwire([scad.make_segment_redge((0, 0, 0), (0, 0, 20))])
|
||||
values = {"base": base, "path": path}
|
||||
assert "base" not in product_reads([Cell({"base"}, set()), Cell({"path"}, {"base"})], values)
|
||||
@@ -59,7 +59,7 @@ def test_the_catalog_lists_every_operation_with_typed_slots():
|
||||
assert len(ids) == len(set(ids)) >= 24
|
||||
for spec in data["specs"]:
|
||||
assert spec["slots"], spec["id"]
|
||||
assert {slot["kind"] for slot in spec["slots"]} <= {"length", "angle", "float", "count", "bool", "enum", "point", "body", "select", "points2d", "points3d", "profile", "sketch", "assembly", "value", "text", "grid", "color"} # value, text, grid, color: forms made from the SDK catalog
|
||||
assert {slot["kind"] for slot in spec["slots"]} <= {"length", "angle", "float", "count", "bool", "enum", "point", "body", "select", "points2d", "points3d", "profile", "sketch", "assembly", "value", "text", "grid", "color", "curve"} # value, text, grid, color: forms made from the SDK catalog
|
||||
|
||||
|
||||
@pytest.mark.parametrize("spec", F.SPECS, ids=lambda s: s.id)
|
||||
@@ -75,6 +75,8 @@ def test_every_template_uses_real_sdk_functions_and_parameters(spec):
|
||||
values[slot.name] = "prof"
|
||||
elif slot.kind == "sketch":
|
||||
values[slot.name] = RECT_SKETCH
|
||||
elif slot.kind == "curve":
|
||||
values[slot.name] = {"points": [{"id": "p1", "at": [0, 0, 0]}, {"id": "p2", "at": [10, 0, 5]}], "curves": [{"id": "c1", "kind": "line", "points": ["p1", "p2"]}]}
|
||||
rendered = F.render_feature(spec.id, "probe", values, bodies=bodies, selections=picks, env={"profile_normals": {"prof": (0.0, 0.0, 1.0)}})
|
||||
seen = 0
|
||||
for call in _calls(rendered.feature):
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
"""A failing step: the preview shows the model before it, and says so.
|
||||
|
||||
When a cell fails, the product is not made; the editor's preview is then of what
|
||||
the cells before it made (the body the failing feature was applied to), flagged
|
||||
partial with the failing cell, instead of the last model that built.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
import simplecadapi as scad
|
||||
from simplecadapi.runtime.config import read_notebook_config
|
||||
from simplecadapi.runtime.live import FailedCell, preview_product
|
||||
from simplecadapi.runtime.projection import ProductNotFoundError
|
||||
|
||||
NOTEBOOK = '''# /// script
|
||||
# [tool.simplecadapi]
|
||||
# kind = "part"
|
||||
# id = "plate"
|
||||
# ///
|
||||
import marimo
|
||||
|
||||
app = marimo.App()
|
||||
|
||||
with app.setup:
|
||||
import simplecadapi as scad
|
||||
|
||||
|
||||
@app.cell
|
||||
def _():
|
||||
# ---- params ----
|
||||
SIZE = scad.var("size", 40.0, comment="Size", unit="mm") # ui: slider(10, 80, step=1, label="Size")
|
||||
FILLET = scad.var("fillet", 2.0, comment="Fillet", unit="mm") # ui: slider(0.5, 40, step=0.5, label="Fillet")
|
||||
return FILLET, SIZE
|
||||
|
||||
|
||||
@app.cell
|
||||
def _(SIZE):
|
||||
# ---- feature: base (build) ----
|
||||
base = scad.make_box_rsolid(SIZE, SIZE, 10.0)
|
||||
return (base,)
|
||||
|
||||
|
||||
@app.cell
|
||||
def _(base):
|
||||
# ---- feature: bore (subtract) ----
|
||||
_tool = scad.make_cylinder_rsolid(radius=5.0, height=40.0, bottom_face_center=(0.0, 0.0, -10.0), axis=(0.0, 0.0, 1.0))
|
||||
bore = scad.cut_rsolid(base, _tool)
|
||||
return (bore,)
|
||||
|
||||
|
||||
@app.cell
|
||||
def _(FILLET, bore):
|
||||
# ---- feature: rounded (modify) ----
|
||||
rounded = scad.fillet_rsolid(bore, scad.ql.edges().resolve(bore), FILLET)
|
||||
return (rounded,)
|
||||
|
||||
|
||||
@app.cell
|
||||
def _(rounded):
|
||||
# ---- feature: top (subtract) ----
|
||||
_pin = scad.make_cylinder_rsolid(radius=2.0, height=40.0, bottom_face_center=(12.0, 12.0, -10.0), axis=(0.0, 0.0, 1.0))
|
||||
top = scad.cut_rsolid(rounded, _pin)
|
||||
return (top,)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run()
|
||||
'''
|
||||
|
||||
|
||||
def _cell(defs, refs=()):
|
||||
return SimpleNamespace(defs=set(defs), refs=set(refs))
|
||||
|
||||
|
||||
ROUNDED = FailedCell("r1", "rounded", "exception", "SimpleCADError: fillet_rsolid: too large")
|
||||
|
||||
|
||||
def test_the_body_the_failing_feature_was_applied_to_is_previewed_and_flagged(tmp_path):
|
||||
path = tmp_path / "plate.py"
|
||||
path.write_text(NOTEBOOK)
|
||||
config = read_notebook_config(path)
|
||||
with scad.GraphSession(graph_id="partial-unit"):
|
||||
base = scad.make_box_rsolid(40.0, 40.0, 10.0)
|
||||
bore = scad.cut_rsolid(base, scad.make_cylinder_rsolid(radius=5.0, height=40.0, bottom_face_center=(0.0, 0.0, -10.0)))
|
||||
cells = [_cell({"SIZE"}), _cell({"base"}, {"SIZE"}), _cell({"bore"}, {"base"})]
|
||||
values = {"SIZE": 40.0, "base": base, "bore": bore}
|
||||
# the cells that are left: whole, as before
|
||||
product, partial = preview_product(config, cells, values)
|
||||
assert partial is None and product.part_id == "plate"
|
||||
# rounded (reads bore) failed and top did not run: bore is the open body, and the preview says why
|
||||
product, partial = preview_product(
|
||||
config, cells, values, failed=[ROUNDED], skipped=["t1"], lost_reads=frozenset({"bore", "FILLET", "rounded"})
|
||||
)
|
||||
assert abs(product.body.get_volume() - bore.get_volume()) < 1e-6
|
||||
assert partial == {"failed": [ROUNDED.to_dict()], "skipped": ["t1"], "shown": ["bore"]}
|
||||
# nothing before the failing step makes a model: an error that names the step
|
||||
with pytest.raises(ProductNotFoundError, match="rounded failed"):
|
||||
preview_product(config, [_cell({"SIZE"})], {"SIZE": 40.0}, failed=[ROUNDED])
|
||||
|
||||
|
||||
def test_an_explicit_product_no_failed_cell_builds_on_is_whole(tmp_path):
|
||||
path = tmp_path / "plate.py"
|
||||
path.write_text(NOTEBOOK)
|
||||
config = read_notebook_config(path)
|
||||
with scad.GraphSession(graph_id="partial-explicit"):
|
||||
body = scad.make_box_rsolid(10.0, 10.0, 10.0)
|
||||
part = scad.Part(part_id="plate", body=body)
|
||||
cells = [_cell({"body"}), _cell({"part"}, {"body"})]
|
||||
values = {"body": body, "part": part}
|
||||
probe = FailedCell("p1", "probe", "exception", "ValueError: x")
|
||||
product, partial = preview_product(config, cells, values, failed=[probe], lost_reads=frozenset({"body"}))
|
||||
assert product is part and partial is None
|
||||
# a failed cell that would have built on the product: the product shown is the one before it
|
||||
product, partial = preview_product(config, cells, values, failed=[probe], lost_reads=frozenset({"part"}))
|
||||
assert product is part and partial is not None and partial["shown"] == ["part"]
|
||||
|
||||
|
||||
def _wait(predicate, timeout=90.0):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if predicate():
|
||||
return True
|
||||
time.sleep(0.3)
|
||||
return False
|
||||
|
||||
|
||||
def test_the_editor_previews_the_model_before_a_failing_parameter_change(tmp_path):
|
||||
pytest.importorskip("uvicorn")
|
||||
import uvicorn
|
||||
|
||||
from simplecadapi.editor.server import WorkspaceState, create_app
|
||||
|
||||
root = tmp_path.resolve()
|
||||
path = root / "plate.py"
|
||||
path.write_text(NOTEBOOK)
|
||||
state = WorkspaceState(root)
|
||||
state.port = 17753
|
||||
server = uvicorn.Server(uvicorn.Config(create_app(state), port=state.port, log_level="error"))
|
||||
threading.Thread(target=server.run, daemon=True).start()
|
||||
state.hub.attach_loop(asyncio.new_event_loop())
|
||||
sent: list[dict] = []
|
||||
emit = state.emit
|
||||
state.emit = lambda envelope: (sent.append(envelope), emit(envelope))[1] # type: ignore[method-assign]
|
||||
try:
|
||||
state.start_kernel(path)
|
||||
whole = state.latest_preview_bytes
|
||||
assert whole and state.partial is None
|
||||
# a fillet too large for the plate: the preview is the bored plate, flagged with the failing step
|
||||
state.dispatch_command({"type": "param.set", "values": {"FILLET": 20}})
|
||||
assert _wait(lambda: state.partial is not None), state._last_publish_error
|
||||
failed = state.partial["failed"]
|
||||
assert [cell["name"] for cell in failed] == ["rounded"] and failed[0]["status"] == "exception"
|
||||
assert "fillet_rsolid" in failed[0]["error"]
|
||||
assert state.partial["shown"] == ["bore"] and len(state.partial["skipped"]) == 1
|
||||
assert state.latest_preview_bytes != whole
|
||||
assert state.snapshot()["partial"] == state.partial
|
||||
last = [envelope for envelope in sent if envelope.get("type") == "preview"][-1]
|
||||
assert last["partial"] == state.partial and not state._last_publish_error
|
||||
# fixed: the whole model replaces it
|
||||
state.dispatch_command({"type": "param.set", "values": {"FILLET": 2.5}})
|
||||
assert _wait(lambda: state.partial is None)
|
||||
last = [envelope for envelope in sent if envelope.get("type") == "preview"][-1]
|
||||
assert last["partial"] is None and state.snapshot()["partial"] is None
|
||||
finally:
|
||||
if state.kernel is not None:
|
||||
state.kernel.stop()
|
||||
server.should_exit = True
|
||||
@@ -155,3 +155,15 @@ def test_the_preview_scene_lists_the_entities_of_each_piece():
|
||||
assert row["into"] == ["mount.top.split1", "mount.top.split2"]
|
||||
assert sorted(p["piece"] for p in row["pieces"]) == [0, 1]
|
||||
assert all(p["entity_id"].startswith("entity/grooved/face/") for p in row["pieces"])
|
||||
|
||||
|
||||
def test_a_tag_given_to_several_entities_names_a_set_and_keeps_its_pieces():
|
||||
with scad.GraphSession():
|
||||
profile = scad.make_rectangle_rface(40.0, 10.0)
|
||||
solid = scad.extrude_rsolid(profile=profile, direction=(0.0, 0.0, 1.0), distance=10.0, side_faces_tag="ex.side", end_face_tag="ex.end")
|
||||
# a slot through the whole bar splits the end face and the two long side faces
|
||||
halves = scad.cut_rsolid(solid, scad.make_box_rsolid(2.0, 20.0, 20.0, bottom_face_center=(0.0, 0.0, -5.0)))
|
||||
sides = [len(ql.faces().where(ql.tag("ex.side")).resolve(half)) for half in halves]
|
||||
assert sides == [3, 3] # every piece of a side face is still a side face
|
||||
assert [_tags(half, "ex.end") for half in halves] == [["ex.end.split1"], ["ex.end.split2"]]
|
||||
assert [row["tag"] for row in scad.list_tag_splits(halves[0])] == ["ex.end"]
|
||||
|
||||
Reference in New Issue
Block a user