editor: a 3D curve is one edge: a path drawn in one go becomes one curve feature per line, arc or spline (path, path_2 ...), each starting at the end of the one before (a point end_of another curve: path.get_end_vertex().get_coordinates(), so it follows that curve), a path closed on its start ends at the first curve's start, and a point snapped to an end of another curve is kept at it; all of them are added or none. An older curve cell of several segments is still one wire. The feature list takes each value's kind from the kernel for every feature (a curve is an edge, a sketch a face or a wire)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -64,11 +64,15 @@ HOLE_DIAMETER = scad.var(name="hole_diameter", default=6.0, unit="mm", comment="
|
||||
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`).
|
||||
and edge midpoints, the workplanes' origins, the ends of other curves and the plane's grid. Enter makes one `curve`
|
||||
feature per line, arc or spline (`path`, `path_2` ...; `# ---- feature: path (datum) ----`), each an **edge**: 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), one at an end of another curve (the next
|
||||
curve of the path, or a snapped end) is `path.get_end_vertex().get_coordinates()` (it follows that curve), others are
|
||||
numbers. A wire is made where one is needed, from the curves picked (`make_wire_from_edges_rwire([path, path_2])`); an
|
||||
older curve cell of several segments is still one wire. The kernel reports every top-level value's kind, so a curve
|
||||
or face written as code is a value, not a body. Every wire or edge value is drawn in the viewport from the kernel's
|
||||
samples (`runtime/live_curves.py`) and picked with the "sketch / curve" selection mode.
|
||||
- Connectors of the part are placed like workplanes: pick one flat face, then "Connector" (selection bar, command bar,
|
||||
or the assembly tab's "on picked face"): a frame with move arrows and turn rings sits on the face; name it and Add.
|
||||
It is written into the product cell (`add_connector_rpart(...)`, `# gui-connectors:`); the assembly tab lists, edits
|
||||
|
||||
+17
-8
@@ -28,7 +28,7 @@ import { describePartial, parsePartial, samePartial, type PartialModel } from "@
|
||||
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 { splitPath, type CurveDoc, type DrawPlane } from "@/lib/curve3d";
|
||||
import { NAMED_FRAMES, ZERO_PLACE, cleanValues, faceFrame, placedFrame, type PlaceFrame, type PlaceValues } from "@/lib/workplane-place";
|
||||
import { parseWorkplanes, resolvePlane, workplanePlane, workplaneRequest, type WorkplaneFrame } from "@/lib/workplanes";
|
||||
import { fitDistanceMm } from "@/lib/sketch-view";
|
||||
@@ -54,7 +54,7 @@ import { describeSketch, nextSketchSelection, readHidden, sketchCentre, sketchIn
|
||||
import { useSketchShapes } from "@/lib/useSketchShapes";
|
||||
import type { Vec3 } from "@/lib/sketch-plane";
|
||||
import { PALETTES } from "@/scene/theme";
|
||||
import { assertCellRan, cellFailure, isCellCommand, pickedPayload, type FeatureCommand, type FeatureRow, type SelectionPayload, type Spec } from "@/lib/features";
|
||||
import { assertCellRan, cellFailure, isCellCommand, pickedPayload, suggestName, type FeatureCommand, type FeatureRow, type SelectionPayload, type Spec } from "@/lib/features";
|
||||
import { useRunLog } from "@/lib/runlog";
|
||||
import { useTheme } from "@/lib/theme";
|
||||
import { selectionPayload, variableNames, type SelectionItem } from "@/lib/selection";
|
||||
@@ -999,22 +999,31 @@ export function App() {
|
||||
setPicked([]);
|
||||
setDrawing({ plane: active && workplanesRef.current.some((wp) => wp.name === active) ? active : "XY", error: null });
|
||||
}, [noNotebook]);
|
||||
/** The path drawn becomes one curve feature per line, arc or spline (each an edge: path, path_2 ...), each starting at
|
||||
* the end of the one before; all of them or none (a failing one takes back the ones added before it). */
|
||||
const commitCurve = useCallback(
|
||||
async (doc: CurveDoc, name: string) => {
|
||||
setGuiBusy(true);
|
||||
const names: string[] = [];
|
||||
while (names.length < doc.curves.length) names.push(names.length ? suggestName(name, [...gui.state.taken, ...names]) : name);
|
||||
let added = 0;
|
||||
try {
|
||||
const result = await gui.run({ op: "add", spec: "curve", name, values: { curve: doc } });
|
||||
assertCellRan(result);
|
||||
log.push("ok", `add ${result.name}`);
|
||||
for (const [index, part] of splitPath(doc, names).entries()) {
|
||||
const result = await gui.run({ op: "add", spec: "curve", name: names[index], values: { curve: part } });
|
||||
added += 1;
|
||||
assertCellRan(result);
|
||||
log.push("ok", `add ${result.name}`);
|
||||
}
|
||||
setDrawing(null);
|
||||
} catch (error) {
|
||||
for (; added > 0; added -= 1) await gui.run({ op: "undo" }).catch(() => undefined);
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
setDrawing((d) => (d ? { ...d, error: message } : d));
|
||||
} finally {
|
||||
setGuiBusy(false);
|
||||
}
|
||||
},
|
||||
[gui.run, log.push],
|
||||
[gui.run, gui.state.taken, log.push],
|
||||
);
|
||||
// W: draw a 3D curve (not while typing, sketching or placing a workplane).
|
||||
useEffect(() => {
|
||||
@@ -1258,8 +1267,8 @@ export function App() {
|
||||
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,
|
||||
description: "Draw curves in space (W): lines, arcs and splines on workplanes, snapped to the model; each is an edge, one after another joined end to end (pick several to sweep along them, or to make a surface).",
|
||||
icon: FEATURE_ICONS.curve,
|
||||
run: () => startDrawing(),
|
||||
},
|
||||
{
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
rayOnPlane,
|
||||
segmentPoints,
|
||||
type CurveDoc,
|
||||
type CurveEnd,
|
||||
type CurveKind,
|
||||
type DrawPlane,
|
||||
type SnapCandidate,
|
||||
@@ -116,7 +117,7 @@ export function CurveDrawer({
|
||||
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 }[];
|
||||
others?: { at: Vec3; label: string; endOf?: CurveEnd }[];
|
||||
plane: string;
|
||||
busy: boolean;
|
||||
error: string | null;
|
||||
@@ -158,7 +159,8 @@ export function CurveDrawer({
|
||||
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 });
|
||||
// an end of another curve is kept as one (the new curve follows it): it wins over a point of the same place
|
||||
for (const other of others) offer({ kind: "point", at: other.at, label: other.label, priority: other.endOf ? 0.5 : 1, ...(other.endOf ? { endOf: other.endOf } : {}) });
|
||||
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;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef } from "react";
|
||||
import * as THREE from "three";
|
||||
|
||||
import { SceneLabel } from "@/components/scene/SceneLabel";
|
||||
import type { CurveEnd } from "@/lib/curve3d";
|
||||
import type { Vec3 } from "@/lib/sketch-plane";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { LineMaterial, LineSegments2, LineSegmentsGeometry } from "@/scene/fat-lines";
|
||||
@@ -23,9 +24,17 @@ export function parseCurves(raw: unknown): CurveSample[] {
|
||||
);
|
||||
}
|
||||
|
||||
/** 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 ends of the curves' edges: where a new path can join one (snap targets). The two ends of a curve that is one
|
||||
* edge say which they are (`endOf`): a point drawn there is kept at it. */
|
||||
export function curveEnds(curves: readonly CurveSample[]): { at: Vec3; label: string; endOf?: CurveEnd }[] {
|
||||
return curves.flatMap((curve) =>
|
||||
curve.kind === "edge" && curve.edges.length === 1
|
||||
? [
|
||||
{ at: curve.edges[0][0], label: `${curve.name} start`, endOf: { curve: curve.name, end: "start" as const } },
|
||||
{ at: curve.edges[0][curve.edges[0].length - 1], label: `${curve.name} end`, endOf: { curve: curve.name, end: "end" as const } },
|
||||
]
|
||||
: curve.edges.flatMap((edge, i) => [{ at: edge[0], label: `${curve.name} ${i}` }, { at: edge[edge.length - 1], label: `${curve.name} ${i}` }]),
|
||||
);
|
||||
}
|
||||
|
||||
/** The curve whose drawn line passes within `reach` pixels of a screen point (the nearest), or null. */
|
||||
|
||||
@@ -299,7 +299,7 @@
|
||||
"Draft planar, cylindrical or conical faces by a signed angle in degrees.": "按带符号的角度(度)对平面、圆柱面或圆锥面拔模。",
|
||||
"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.": "拖动锚点(控制柄跟随)或控制柄:两侧各有自己的方向和力度。拖动控制柄时按住 Shift 让另一侧与之共线(光滑);S 让选中的锚点变光滑。Shift+A:锚点模式(点击添加/删除锚点);Delete 删除选中的锚点。",
|
||||
"Draw a chain of lines, arcs or splines, or a closed loop: the wire is made of one.": "画一条由直线、圆弧或样条组成的链,或一个闭环:线框由其中一条构成。",
|
||||
"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.": "在空间中绘制路径(W):在工作平面上画直线、圆弧和样条,并吸附到模型;生成的线框可用于扫掠或放样。",
|
||||
"Draw curves in space (W): lines, arcs and splines on workplanes, snapped to the model; each is an edge, one after another joined end to end (pick several to sweep along them, or to make a surface).": "在空间中绘制曲线(W):在工作平面上画直线、圆弧和样条,可吸附到模型;每条都是一个 edge,首尾相接(选中多条可以沿它们扫掠,或者构造曲面)。",
|
||||
"Drive angle degrees": "驱动角度(度)",
|
||||
"Drive depth": "驱动深度",
|
||||
"Drive distance": "驱动距离",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { addSegment, arcPoints, dropLast, gridStep, onGrid, pathEnd, pickSnap, pointFor, rayOnPlane, type CurveDoc, type DrawPlane, type SnapCandidate } from "./curve3d";
|
||||
import { addSegment, arcPoints, dropLast, gridStep, onGrid, pathEnd, pickSnap, pointFor, rayOnPlane, splitPath, 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] };
|
||||
@@ -38,3 +38,30 @@ describe("drawing a 3D curve", () => {
|
||||
expect(dropLast(doc)).toEqual({ points: [doc.points[0]], curves: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("a path drawn in one go becomes one curve per segment", () => {
|
||||
const doc: CurveDoc = {
|
||||
points: [
|
||||
{ id: "p1", at: [0, 0, 0] },
|
||||
{ id: "p2", at: [10, 0, 0] },
|
||||
{ id: "p3", at: [10, 5, 0] },
|
||||
{ id: "p4", at: [0, 10, 0] },
|
||||
],
|
||||
curves: [
|
||||
{ id: "c1", kind: "line", points: ["p1", "p2"] },
|
||||
{ id: "c2", kind: "arc", points: ["p2", "p3", "p4"] },
|
||||
{ id: "c3", kind: "line", points: ["p4", "p1"] },
|
||||
],
|
||||
};
|
||||
|
||||
it("starts each at the end of the one before, and closes on the first's start", () => {
|
||||
const [a, b, c] = splitPath(doc, ["path", "path_2", "path_3"]);
|
||||
expect(a).toEqual({ points: [doc.points[0], doc.points[1]], curves: [{ id: "c1", kind: "line", points: ["p1", "p2"] }] });
|
||||
expect(b.points[0]).toEqual({ id: "p2", at: [10, 0, 0], end_of: { curve: "path", end: "end" } });
|
||||
expect(b.curves).toEqual([{ id: "c1", kind: "arc", points: ["p2", "p3", "p4"] }]);
|
||||
expect(c.points).toEqual([
|
||||
{ id: "p4", at: [0, 10, 0], end_of: { curve: "path_2", end: "end" } },
|
||||
{ id: "p1", at: [0, 0, 0], end_of: { curve: "path", end: "start" } },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
/** 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. */
|
||||
/** Drawing a 3D curve in the viewport: the document the `curve` feature takes (points in space, on workplanes, at model
|
||||
* vertices or at the ends of other curves; lines, arcs and splines that follow one another), what the pointer snaps to,
|
||||
* and the shape drawn while drawing. A path drawn in one go becomes one curve feature per line, arc or spline (each an
|
||||
* edge), each starting at the end of the one before (see splitPath). 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";
|
||||
|
||||
/** Where another curve of the notebook starts or ends (a point there follows it). */
|
||||
export type CurveEnd = { curve: string; end: "start" | "end" };
|
||||
|
||||
/** 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 };
|
||||
* drawn on a workplane variable, `entity_id` for one snapped to a model vertex (the server names it by its reference),
|
||||
* `end_of` for one at an end of another curve. */
|
||||
export type CurvePoint = { id: string; at: Vec3; on?: string; uv?: [number, number]; entity_id?: string; end_of?: CurveEnd };
|
||||
export type CurveSegment = { id: string; kind: CurveKind; points: string[] };
|
||||
export type CurveDoc = { points: CurvePoint[]; curves: CurveSegment[] };
|
||||
|
||||
@@ -24,6 +30,8 @@ export type SnapCandidate = {
|
||||
pointId?: string;
|
||||
/** For a workplane's origin: the workplane, so the point is kept on it. */
|
||||
workplane?: string;
|
||||
/** For an end of another curve: which, so the point is kept at it. */
|
||||
endOf?: CurveEnd;
|
||||
label: string;
|
||||
priority: number;
|
||||
};
|
||||
@@ -160,6 +168,7 @@ export function pointFor(doc: CurveDoc, plane: DrawPlane, at: Vec3, snap: SnapCa
|
||||
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 (snap?.endOf) point = { id, at, end_of: snap.endOf };
|
||||
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 };
|
||||
}
|
||||
@@ -181,3 +190,21 @@ export function dropLast(doc: CurveDoc): CurveDoc {
|
||||
if (curves.length === 0 && first) used.add(first);
|
||||
return { points: doc.points.filter((p) => used.has(p.id)), curves };
|
||||
}
|
||||
|
||||
/** The documents of a path drawn in one go, one per line, arc or spline (each feature is one edge), named `names` in order:
|
||||
* a curve that starts where the one before it ends starts at its end (`end_of`), and a path closed on its first point
|
||||
* ends at the first curve's start, so the curves stay joined when one of them changes. */
|
||||
export function splitPath(doc: CurveDoc, names: readonly string[]): CurveDoc[] {
|
||||
const first = doc.curves[0]?.points[0];
|
||||
return doc.curves.map((curve, index) => {
|
||||
const previous = doc.curves[index - 1];
|
||||
const points = curve.points.map((id, at) => {
|
||||
const point = doc.points.find((p) => p.id === id) as CurvePoint;
|
||||
if (at === 0 && previous && previous.points.at(-1) === id) return { id, at: point.at, end_of: { curve: names[index - 1], end: "end" as const } };
|
||||
if (at === curve.points.length - 1 && index > 0 && id === first) return { id, at: point.at, end_of: { curve: names[0], end: "start" as const } };
|
||||
return point;
|
||||
});
|
||||
const unique = points.filter((point, at) => points.findIndex((p) => p.id === point.id) === at);
|
||||
return { points: unique, curves: [{ ...curve, id: "c1" }] };
|
||||
});
|
||||
}
|
||||
|
||||
@@ -6,15 +6,19 @@ 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
|
||||
{"id": "p3", "vertex": {<scad.ref record>}, "at": [20, 0, 10]}, # a vertex of the model: follows it
|
||||
{"id": "p7", "end_of": {"curve": "path", "end": "end"}, "at": [..]}], # where another curve ends: 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.
|
||||
A curve the editor draws now is one line, arc or spline: :func:`render` binds the feature's name to that SDK **edge**. A
|
||||
path of several is several features, each starting at the end of the one before (``end_of``); a wire is made where one
|
||||
is needed, from the curves picked. A document of several curves that follow one another (each starts where the last
|
||||
ended: how the editor drew paths before) is still one wire, ``make_wire_from_edges_rwire`` of its edges. The cell has one
|
||||
name per point (a vertex resolves through its stable reference in the body, a workplane point through
|
||||
``wp.point(u, v)``, the end of another curve through its vertex). Nothing here is geometry: the code is the SDK's, the
|
||||
document only says which points and curves.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -75,10 +79,15 @@ def validate(doc: Mapping[str, Any]) -> dict[str, Any]:
|
||||
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):
|
||||
if raw.get("end_of") is not None:
|
||||
end_of = raw["end_of"]
|
||||
if not isinstance(end_of, Mapping) or not _NAME.fullmatch(str(end_of.get("curve", ""))) or end_of.get("end") not in ("start", "end"):
|
||||
raise CurveError(f"point {pid!r}: end_of names a curve and its end (start or end)")
|
||||
point["end_of"] = {"curve": str(end_of["curve"]), "end": str(end_of["end"])}
|
||||
if raw.get("at") is not None or ("on" not in point and "vertex" not in point and "end_of" 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")
|
||||
if sum(key in point for key in ("on", "vertex", "end_of")) > 1:
|
||||
raise CurveError(f"point {pid!r} is on a workplane, at a vertex or at the end of a curve: one of them")
|
||||
points.append(point)
|
||||
curves: list[dict[str, Any]] = []
|
||||
for raw in doc.get("curves") or []:
|
||||
@@ -107,6 +116,16 @@ def workplanes_of(doc: Mapping[str, Any]) -> list[str]:
|
||||
return sorted({p["on"] for p in doc.get("points") or [] if p.get("on")})
|
||||
|
||||
|
||||
def curves_of(doc: Mapping[str, Any]) -> list[str]:
|
||||
"""The other curves the document's points sit at the ends of (the cell reads them)."""
|
||||
return sorted({p["end_of"]["curve"] for p in doc.get("points") or [] if p.get("end_of")})
|
||||
|
||||
|
||||
def output_of(doc: Mapping[str, Any]) -> str:
|
||||
"""What the cell makes: an ``edge`` for one curve, a ``wire`` for several following one another."""
|
||||
return "edge" if len(doc.get("curves") or []) == 1 else "wire"
|
||||
|
||||
|
||||
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 [])
|
||||
@@ -129,6 +148,9 @@ def render(slug: str, doc: Mapping[str, Any], body: str | None) -> list[str]:
|
||||
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("end_of"):
|
||||
end = point["end_of"]
|
||||
lines.append(f"{name} = {end['curve']}.get_{end['end']}_vertex().get_coordinates()")
|
||||
elif point.get("on"):
|
||||
u, v = point["uv"]
|
||||
lines.append(f"{name} = {point['on']}.point({u!r}, {v!r})")
|
||||
@@ -143,10 +165,13 @@ def render(slug: str, doc: Mapping[str, Any], body: str | None) -> list[str]:
|
||||
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)}])")
|
||||
if len(edges) == 1:
|
||||
lines.append(f"{slug} = {edges[0]}")
|
||||
return lines
|
||||
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"]
|
||||
__all__ = ["KINDS", "CurveError", "curves_of", "needs_body", "output_of", "render", "validate", "workplanes_of"]
|
||||
|
||||
@@ -406,10 +406,13 @@ def _sketch(c: Context) -> list[str]:
|
||||
|
||||
|
||||
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."""
|
||||
"""A 3D curve: one line, arc or spline (an edge) through points in space, on workplanes, at model vertices or at the
|
||||
ends of other curves; an older document of several curves is one wire."""
|
||||
doc = c.values["curve"]
|
||||
for workplane in curve_doc.workplanes_of(doc):
|
||||
c.body_named(workplane)
|
||||
for other in curve_doc.curves_of(doc):
|
||||
c.body_named(other)
|
||||
body = None
|
||||
if curve_doc.needs_body(doc):
|
||||
if not c.values.get("body"):
|
||||
|
||||
@@ -21,7 +21,7 @@ from ..runtime.config import read_notebook_config
|
||||
from ..runtime.workspace import features_in_cell
|
||||
from . import assembly_doc
|
||||
from . import features as F
|
||||
from . import sketch_doc
|
||||
from . import curve_doc, sketch_doc
|
||||
|
||||
_PARAMS_HEADER = re.compile(r"^#\s*-{3,}\s*params\b[^\n]*", re.MULTILINE)
|
||||
_PARAMS_FOR = re.compile(r"^#\s*-{3,}\s*params:\s*(?P<slug>[a-z][a-z0-9_]*)\s*-{3,}\s*$")
|
||||
@@ -108,6 +108,8 @@ class FeatureService:
|
||||
produces = F.BY_ID[gui["spec"]].produces if gui else "solid"
|
||||
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 {})
|
||||
if gui and gui["spec"] == "curve": # one curve is an edge, an older path of several a wire
|
||||
produces = curve_doc.output_of(gui.get("values", {}).get("curve") or {})
|
||||
part_of = head.slug[: -len("_parts")] if head.slug.endswith("_parts") and head.slug[: -len("_parts")] in assembly_slugs else None
|
||||
# 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",)
|
||||
@@ -115,7 +117,7 @@ class FeatureService:
|
||||
# a cell written as code does not say what it makes: the kernel does (a path is a wire, not a body)
|
||||
kinds = getattr(self.state, "value_kinds", None) or {}
|
||||
for name in made:
|
||||
bodies[name] = produces if gui else kinds.get(name, produces)
|
||||
bodies[name] = kinds.get(name, produces)
|
||||
order.append(name)
|
||||
if head.role == "datum" and produces == "workplane":
|
||||
made = sorted(defined)
|
||||
|
||||
@@ -71,3 +71,27 @@ def test_a_cell_that_only_draws_a_curve_through_the_body_leaves_it_the_product()
|
||||
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)
|
||||
|
||||
|
||||
def test_one_curve_is_an_edge_and_the_next_starts_where_it_ends():
|
||||
"""A curve the editor draws is one edge; the next one of a path starts at its end through ``end_of``, so it follows
|
||||
when the first is changed, and the two make a wire where one is needed."""
|
||||
first = {"points": [{"id": "p1", "at": [0, 0, 0]}, {"id": "p2", "at": [10, 0, 0]}], "curves": [{"id": "c1", "kind": "line", "points": ["p1", "p2"]}]}
|
||||
second = {
|
||||
"points": [{"id": "p1", "end_of": {"curve": "path", "end": "end"}, "at": [10, 0, 0]}, {"id": "p2", "at": [10, 10, 5]}, {"id": "p3", "at": [0, 20, 5]}],
|
||||
"curves": [{"id": "c1", "kind": "spline", "points": ["p1", "p2", "p3"]}],
|
||||
}
|
||||
assert curve_doc.output_of(first) == "edge" and curve_doc.output_of(_doc()) == "wire"
|
||||
one = F.render_feature("curve", "path", {"curve": first}, bodies={})
|
||||
two = F.render_feature("curve", "path_2", {"curve": second}, bodies={"path": "edge"})
|
||||
assert "path_2" not in one.reads and two.reads == ["path"]
|
||||
assert "_p1 = path.get_end_vertex().get_coordinates()" in two.feature
|
||||
scope = _run("\n".join(one.feature.splitlines()[1:]))
|
||||
assert isinstance(scope["path"], scad.Edge)
|
||||
scope = _run("\n".join(two.feature.splitlines()[1:]), path=scope["path"])
|
||||
start = scope["path_2"].get_start_vertex().get_coordinates()
|
||||
assert isinstance(scope["path_2"], scad.Edge) and tuple(round(c, 6) for c in start) == (10.0, 0.0, 0.0)
|
||||
wire = scad.make_wire_from_edges_rwire([scope["path"], scope["path_2"]])
|
||||
assert len(scad.ql.edges().resolve(wire)) == 2
|
||||
with pytest.raises(curve_doc.CurveError, match="one of them"):
|
||||
curve_doc.validate({**second, "points": [{**second["points"][0], "on": "wp", "uv": [0, 0]}, *second["points"][1:]]})
|
||||
|
||||
Reference in New Issue
Block a user