tags follow their entity as references do: a split names the pieces <tag>.split<i> (numbered when recorded), reported by TagSplitWarning, sca run and the editor's highlight; solids have history (boolean solid witnesses, union merge, one-solid continuation) and scad.ref.solid; references resolve over the pieces of a split body; an ambiguous anchor is told apart by its history
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,7 +3,7 @@
|
||||
## Class Definition
|
||||
|
||||
```python
|
||||
class CellReport(name: str, key: str, status: CellStatus)
|
||||
class CellReport(name: str, key: str, status: CellStatus, tag_splits: tuple[dict, ...] = ())
|
||||
```
|
||||
|
||||
*Source: runtime/runner.py*
|
||||
|
||||
@@ -14,7 +14,7 @@ class ElementRef(kind: str, feature: str = '', op: str = '', role: Optional[str]
|
||||
|
||||
## Description
|
||||
|
||||
A stable reference to one face, edge or vertex; ``repr()`` is the code that makes it.
|
||||
A stable reference to one face, edge, vertex or solid; ``repr()`` is the code that makes it.
|
||||
|
||||
Fields: ``kind``; ``feature`` and ``op`` (where the entity was born); then exactly one of ``role`` (its kernel
|
||||
role, with ``ordinal`` saying which of the entities with that role), ``topo`` (its position in that output, for an
|
||||
|
||||
@@ -419,6 +419,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi
|
||||
- [inspect_surface_rsurfacedata](inspect_surface_rsurfacedata.md) *(from operators/geometry.py)* `top-level`
|
||||
- [key](key.md) *(from ql.py)* `submodule:ql`
|
||||
- [linear_pattern_rsolidlist](linear_pattern_rsolidlist.md) *(from operators/transform.py)* `top-level`
|
||||
- [list_tag_splits](list_tag_splits.md) *(from operators/selection.py)* `top-level`
|
||||
- [load_brep_region_rshell](load_brep_region_rshell.md) *(from operators/geometry.py)* `top-level`
|
||||
- [load_brep_region_rsolid](load_brep_region_rsolid.md) *(from operators/geometry.py)* `top-level`
|
||||
- [measure_constraint_residual_rconstraintresidual](measure_constraint_residual_rconstraintresidual.md) *(from operators/product.py)* `top-level`
|
||||
|
||||
@@ -50,7 +50,7 @@ later. A body of a Part is named with ``set_body_appearance_rpart(part, body_id,
|
||||
|
||||
### (default ``"continuation_fragment"``
|
||||
|
||||
- **Description**: kept on continued faces and on the fragments of a split face).
|
||||
- **Description**: kept on continued faces; the pieces of a split face carry ``<tag>.split1`` .. ``<tag>.split<n>`` instead, see ``list_tag_splits``).
|
||||
|
||||
## Returns
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# list_tag_splits
|
||||
|
||||
## API Definition
|
||||
|
||||
```python
|
||||
def list_tag_splits(shape)
|
||||
```
|
||||
|
||||
*Source: operators/selection.py*
|
||||
|
||||
## Import Surface
|
||||
|
||||
- top-level: `from simplecadapi import list_tag_splits`
|
||||
|
||||
## Description
|
||||
|
||||
The tagged entities that the operations behind a shape split into pieces.
|
||||
|
||||
A tag follows its entity the way a reference does: while the entity stays one entity it keeps the tag; when an
|
||||
operation splits it (a slot cut across a tagged face, a cut through a tagged body), the tag does not go to every
|
||||
piece. Each piece carries ``<tag>.split1`` .. ``<tag>.split<n>`` instead, numbered as the operation recorded them (by
|
||||
centre, then size), and ``ql.tag("<tag>")`` finds none of them. Name the pieces you mean with tags of your own after the
|
||||
split, or select them with ``ql.tag("<tag>.split1")`` / ``ql.tag("<tag>.*")``.
|
||||
|
||||
## Parameters
|
||||
|
||||
### shape
|
||||
|
||||
- **Description**: A shape made in a recording session (its history is read).
|
||||
|
||||
## Returns
|
||||
|
||||
list[dict]: One row per split, upstream first: ``tag`` (the tag the entity had), ``into`` (the tags of the pieces,
|
||||
in piece order), ``node_id`` and ``op`` (the operation that split it), ``source_topo_id`` and ``pieces``
|
||||
(``output_slot``, ``kind``, ``topo_id`` of each piece in that operation's output). Empty for a shape without
|
||||
recorded history.
|
||||
|
||||
## Examples
|
||||
|
||||
```python
|
||||
>>> top = scad.apply_tag_rselection(box, scad.ql.faces().where(scad.ql.prop("geom.center.z", ">=", 9.9)), "mount.top")
|
||||
>>> halves = scad.cut_rsolid(top, slot) # the slot splits the top face (and the body)
|
||||
>>> [row["into"] for row in scad.list_tag_splits(halves[0])]
|
||||
[['mount.top.split1', 'mount.top.split2']]
|
||||
```
|
||||
@@ -18,8 +18,10 @@ Build a tag predicate for QL filtering.
|
||||
|
||||
Tags are a view over the recorded history: a tag assigned in a
|
||||
``GraphSession`` reaches every entity its target became through later
|
||||
operations (a face cut in two keeps it on both pieces), as its lineage
|
||||
policy allows. ``local`` is what the entity itself stores, ``inherited``
|
||||
operations as its lineage policy allows. A tag follows its entity as a
|
||||
reference does: an entity an operation splits keeps it on none of its
|
||||
pieces, which carry ``<tag>.split1`` .. ``<tag>.split<n>`` instead
|
||||
(``list_tag_splits``); ``ql.tag("<tag>.*")`` finds them all. ``local`` is what the entity itself stores, ``inherited``
|
||||
what containing entities pass down, ``lineage`` what the history carries,
|
||||
and ``effective`` (the default) all three.
|
||||
|
||||
|
||||
@@ -143,7 +143,9 @@ sca run bracket.py --no-cache # run every cell
|
||||
`--set` values are Python literals, else strings; the option may repeat. The
|
||||
report lists the definition id, kind, revision, `content_hash`, and every
|
||||
cell's status: `ran`, `cached` (restored from the cell cache), or `skipped`
|
||||
(replaced by an override).
|
||||
(replaced by an override). A cell whose operations split a tagged entity also
|
||||
lists `tag_splits` (`{tag, into, op}`: the pieces carry `<tag>.split1` ..), ran or
|
||||
restored; a cell that runs prints a `TagSplitWarning` at its place in the file.
|
||||
|
||||
From Python:
|
||||
|
||||
|
||||
@@ -65,6 +65,10 @@ HOLE_DIAMETER = scad.var(name="hole_diameter", default=6.0, unit="mm", comment="
|
||||
- A sketch on a workplane has `plane={"workplane": "wp", origin, x_axis, y_axis}` in its `# gui:` document and
|
||||
`plane=wp` in its code: the frame in the document is only for drawing before the cell runs; the cell follows `wp`.
|
||||
A workplane cell reads the body without consuming it (the body stays the open body / product).
|
||||
- A split tag is shown, not hidden: when an operation splits a tagged entity (its pieces carry `<tag>.split1` ..), the
|
||||
viewport highlights each piece in its own colour and a notice names the tag, the operation and the pieces' tags
|
||||
(hide the highlight or dismiss it there). `sca snapshot` lists the same as `tag_splits`. Read it as a question:
|
||||
was the split meant? If later code needs a piece, tag it after the split.
|
||||
- Unattended: the buttons are not available; write the cells yourself (see `discipline/notebook-cell-design.md`).
|
||||
|
||||
## The same operations from the command line
|
||||
|
||||
@@ -55,8 +55,11 @@ around it as shown.
|
||||
(`apply_tag_rselection`, an op-kwarg tag such as `top_face_tag=`) is a
|
||||
graph node; `ql.tag(...)` on a later shape finds the entities the tagged
|
||||
ones became, through each operation's kernel history, as the tag's
|
||||
lineage policy allows (default `continuation_fragment`: a face cut in two
|
||||
keeps the tag on both pieces). Verified per family in
|
||||
lineage policy allows. A tag follows its entity as a reference does: an
|
||||
entity an operation **splits** keeps it on no piece; the pieces carry
|
||||
`<tag>.split1` .. (by centre, then size), reported by `TagSplitWarning`,
|
||||
`sca run` (`tag_splits`), `scad.list_tag_splits(shape)` and the editor's
|
||||
highlight. Tag the pieces later code needs. Verified per family in
|
||||
`test/test_element_ref_history.py` (audit). For one particular entity,
|
||||
prefer a reference (rule 6) over a tag made only to find it again:
|
||||
|
||||
@@ -68,22 +71,19 @@ around it as shown.
|
||||
| `origin_role("body"/"tool")` | parent argument of a boolean | single-step only | no |
|
||||
| `output_role("<slot>")` | `extrusion.end`, `box.top`, `fillet.patch` | single-step only | own op only |
|
||||
|
||||
"Single-step" means the metadata describes the last operation that touched
|
||||
the shape; the next tracked operation overwrites it. A tag ends where the
|
||||
history says the entity ends: a face a cut removes, a face a feature
|
||||
replaces by a generated one (a fillet's patch is a new face, not the
|
||||
edge), or an operation that records no history. `scad.explain_tag(face,
|
||||
tag)` shows the binding and the lineage that carried it. The `lineage`
|
||||
scope is the carried part alone; `effective` (the default) includes it.
|
||||
"Single-step": the next tracked operation overwrites it. A tag ends where the history says
|
||||
the entity ends (a face a cut removes, one a fillet's patch replaces, an op without history).
|
||||
`scad.explain_tag(face, tag)` shows the binding and what carried it; scope `lineage` is
|
||||
the carried part alone, `effective` (default) includes it.
|
||||
|
||||
6. **A rule is a query; a particular entity is a reference.** `ql` picks
|
||||
whatever matches a rule; `scad.ref` means *this* face or edge and stays it
|
||||
through booleans, blends, copies and edits, e.g.
|
||||
`scad.ref.faces(scad.ref.face("base", "make_box_rsolid", role="box.top"))`
|
||||
or `scad.ref.edge("base", "make_box_rsolid", between=("box.front", "box.top"))`
|
||||
(`scad.ref.of(face, part)` makes one; `scad.ql.ref(r)` uses one in a query).
|
||||
A split or lost reference raises `ElementRefError` with the candidates;
|
||||
never fall back to a geometric window. See `ql-recipes.md` (stable reference).
|
||||
whatever matches a rule; `scad.ref` means *this* face, edge or solid through booleans,
|
||||
blends, copies and edits, e.g.
|
||||
`scad.ref.faces(scad.ref.face("base", "make_box_rsolid", role="box.top"))` or
|
||||
`scad.ref.edge("base", "make_box_rsolid", between=("box.front", "box.top"))`
|
||||
(`scad.ref.of(face, part)` makes one, of a solid too; `scad.ql.ref(r)` uses one in a query).
|
||||
A split or lost reference raises `ElementRefError` with the candidates; never fall back to a
|
||||
geometric window. See `ql-recipes.md` (stable reference).
|
||||
|
||||
## The selection loop (card before cardinality)
|
||||
|
||||
|
||||
@@ -169,6 +169,11 @@ with scad.GraphSession(namespace="base"): # in a notebook: the cell's "#
|
||||
- Outcomes: `ok`; `merged` (one face that absorbed others: a coplanar union; it runs); `split` (several pieces, listed in
|
||||
a geometric order, until `piece=i` says which); `lost` (where and why; with a guard, the closest look-alikes).
|
||||
`ref.choose(i, part)` writes a choice back: a piece, or a new reference at a look-alike.
|
||||
- A **solid** (a body) has a reference too: `scad.ref.of(piece, piece)` gives `scad.ref.solid("slot", "make_cut_rsolid_list",
|
||||
slot=1, guard=("SOLID", centre, volume))`, its place in the output of the op that made it. A fillet, shell or move
|
||||
continues it, a union merges it, a cut that splits it splits it. Resolve it in a solid or in the pieces of a split
|
||||
body (`r.one(pieces)`); `scad.ref.solids(r)` is the selection. Over pieces, a face or edge reference selects on the
|
||||
piece it lies on (`scad.fillet_rsolid(pieces, scad.ref.edges(rim), 1.0)` blends that piece only).
|
||||
|
||||
Write the printed code into the cell that uses it (not the query that found it): it reads as what it means and the
|
||||
editor reads it back. When a reference fails, read the error, do not widen anything:
|
||||
|
||||
@@ -15,6 +15,7 @@ import { sideStyle, useModeTransition } from "@/lib/useModeTransition";
|
||||
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 { parseWorkplanes, resolvePlane, workplanePlane, workplaneRequest, type WorkplaneFrame } from "@/lib/workplanes";
|
||||
import { fitDistanceMm } from "@/lib/sketch-view";
|
||||
import { viewPose } from "@/lib/sketch-plane";
|
||||
@@ -101,6 +102,7 @@ export function App() {
|
||||
const [picked, setPicked] = useState<Omit<SelectionItem, "variable">[]>([]);
|
||||
// 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[]>([]);
|
||||
const [activeWorkplane, setActiveWorkplane] = useState<string | null>(null);
|
||||
const [selectionMode, setSelectionMode] = useState<SelectionMode>("solid");
|
||||
const [sceneVersion, setSceneVersion] = useState(0);
|
||||
@@ -307,6 +309,7 @@ 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("preview", (envelope) => {
|
||||
setLoading(null);
|
||||
@@ -1093,6 +1096,7 @@ export function App() {
|
||||
onHover={setHoverSketch}
|
||||
/>
|
||||
{viewRef.current && workplanes.length > 0 && <WorkplanePatches view={viewRef.current} workplanes={workplanes} active={activeWorkplane} />}
|
||||
{!sketching && viewRef.current && <TagSplits view={viewRef.current} splits={tagSplits} sceneVersion={sceneVersion} />}
|
||||
{!sketching && viewRef.current && gizmos.length > 0 && (
|
||||
<ConnectorGizmos view={viewRef.current} gizmos={gizmos} components={asm.doc.components} highlighted={gizmoHighlight} onPick={pickGizmo} armed={!!asm.target} />
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Scissors } from "lucide-react";
|
||||
|
||||
import type { SceneView } from "@/scene/scene-view";
|
||||
|
||||
/** A tagged entity an operation split (the server's `tag_splits`, from `scad.list_tag_splits`): the pieces carry
|
||||
* `<tag>.split<i>`, and `pieces` lists the scene entities of each. */
|
||||
export type TagSplit = {
|
||||
tag: string;
|
||||
into: string[];
|
||||
op: string;
|
||||
pieces: { piece: number; node_id: string; entity_id: string }[];
|
||||
};
|
||||
|
||||
/** One colour per piece, told apart at a glance on any body colour. */
|
||||
export const PIECE_COLORS = ["#e4572e", "#17a3b8", "#e8b10c", "#5fa83a", "#8a5cc2", "#d9479a"];
|
||||
|
||||
export function parseTagSplits(value: unknown): TagSplit[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.filter(
|
||||
(row): row is TagSplit =>
|
||||
!!row && typeof row.tag === "string" && Array.isArray(row.into) && typeof row.op === "string" && Array.isArray(row.pieces),
|
||||
);
|
||||
}
|
||||
|
||||
/** Highlights the pieces of every split tag in the viewport, each piece its own colour, and says what was split, so the
|
||||
* person (or an agent reading the viewport image) can judge whether the split was meant. Dismissed until the splits
|
||||
* change; the highlight can be turned off while the notice stays. */
|
||||
export function TagSplits({ view, splits, sceneVersion }: { view: SceneView; splits: TagSplit[]; sceneVersion: number }) {
|
||||
const signature = useMemo(() => JSON.stringify(splits.map((row) => [row.tag, row.into, row.op])), [splits]);
|
||||
const [dismissed, setDismissed] = useState<string | null>(null);
|
||||
const [shown, setShown] = useState(true);
|
||||
const open = splits.length > 0 && dismissed !== signature;
|
||||
const highlight = open && shown;
|
||||
|
||||
useEffect(() => {
|
||||
if (!highlight) return;
|
||||
const keys: string[] = [];
|
||||
for (const row of splits) {
|
||||
for (const piece of row.pieces) {
|
||||
view.addMark(piece.node_id, piece.entity_id, PIECE_COLORS[piece.piece % PIECE_COLORS.length]);
|
||||
keys.push(`${piece.node_id}::${piece.entity_id}`);
|
||||
}
|
||||
}
|
||||
return () => keys.forEach((key) => view.removeMark(key));
|
||||
}, [view, splits, highlight, sceneVersion]);
|
||||
|
||||
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="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>
|
||||
{splits.map((row) => (
|
||||
<div key={`${row.op}:${row.tag}:${row.into.join(",")}`} className="flex flex-col gap-1">
|
||||
<span className="text-muted-foreground">
|
||||
<span className="font-mono text-foreground">{row.op}</span> split <span className="font-mono text-foreground">{row.tag}</span> into {row.into.length}; the tag names none of them:
|
||||
</span>
|
||||
<span className="flex flex-wrap gap-1">
|
||||
{row.into.map((name, index) => (
|
||||
<span key={name} className="flex items-center gap-1 border border-border px-1.5 py-0.5 font-mono">
|
||||
<span className="inline-block size-2.5" style={{ background: PIECE_COLORS[index % PIECE_COLORS.length] }} />
|
||||
{name}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex 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>
|
||||
<button type="button" className="border border-border px-2 py-0.5 hover:bg-accent" onClick={() => setDismissed(signature)}>
|
||||
Dismiss
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -12,6 +12,7 @@
|
||||
#include "scad/core/error.hpp"
|
||||
#include "scad/ql/selector.hpp"
|
||||
#include "scad/semantic/finalize.hpp"
|
||||
#include "scad/reactive/tag_view.hpp"
|
||||
#include "scad/semantic/selection.hpp"
|
||||
#include "scad/topo/tag_factories.hpp"
|
||||
|
||||
@@ -682,6 +683,36 @@ void bind_operators(py::module_& m) {
|
||||
[](const Shape& shape, const std::string& tag, TagScope scope) { return explain_tag(shape, tag, scope); },
|
||||
py::arg("shape"), py::arg("tag"), py::arg("scope") = TagScope::Effective,
|
||||
"Explain every visible binding that produces a tag token.");
|
||||
m.def(
|
||||
"list_tag_splits",
|
||||
[](const Shape& shape) {
|
||||
py::list out;
|
||||
const auto opaque = shape.root().graph_node();
|
||||
if (!opaque)
|
||||
return out;
|
||||
for (const reactive::TagSplit& split :
|
||||
reactive::tag_splits(std::static_pointer_cast<const reactive::OperationNode>(opaque))) {
|
||||
py::list pieces;
|
||||
for (const TopoRef& piece : split.pieces) {
|
||||
py::dict item;
|
||||
item["output_slot"] = piece.output_slot;
|
||||
item["kind"] = std::string(kind_name(piece.kind));
|
||||
item["topo_id"] = piece.topo_id;
|
||||
pieces.append(item);
|
||||
}
|
||||
py::dict row;
|
||||
row["tag"] = split.tag;
|
||||
row["into"] = split.into;
|
||||
row["node_id"] = split.node_id;
|
||||
row["op"] = split.op;
|
||||
row["source_topo_id"] = split.source_topo_id;
|
||||
row["pieces"] = pieces;
|
||||
out.append(row);
|
||||
}
|
||||
return out;
|
||||
},
|
||||
py::arg("shape"),
|
||||
"The tagged entities the operations behind a shape split into pieces (each piece carries <tag>.split<i>).");
|
||||
m.def(
|
||||
"select_faces_by_tag",
|
||||
[](const Solid& solid, const std::string& tag, TagScope scope) { return select_faces_by_tag(solid, tag, scope); },
|
||||
|
||||
@@ -43,14 +43,36 @@ struct CarriedTag {
|
||||
std::string op; // the op of the last step that carried it
|
||||
};
|
||||
|
||||
// "<slot>\x1f<kind>\x1f<recorded topo id>" -> the bindings carried to that entity.
|
||||
using TagView = std::unordered_map<std::string, std::vector<CarriedTag>>;
|
||||
// A tagged entity an operation split into pieces. A tag follows its entity as a reference does: one entity keeps the
|
||||
// tag, several do not. The pieces carry "<tag>.split1" .. "<tag>.split<n>" instead, numbered as the operation
|
||||
// recorded them (the "piece" of their witnesses: by centre, then size), and the split is reported so whoever reads the
|
||||
// model can see it happened and name the pieces it wants by tags of its own.
|
||||
struct TagSplit {
|
||||
std::string tag; // the tag the entity had
|
||||
std::vector<std::string> into; // the tags the pieces carry, in piece order
|
||||
std::vector<TopoRef> pieces; // the pieces in the node's output, in piece order
|
||||
std::string node_id; // the operation that split it
|
||||
std::string op;
|
||||
std::string source_topo_id; // the entity it was (recorded form, in the operation's input)
|
||||
};
|
||||
|
||||
// "<slot>\x1f<kind>\x1f<recorded topo id>" -> the bindings carried to that entity; `splits`: the tagged entities this
|
||||
// node split.
|
||||
struct TagView : std::unordered_map<std::string, std::vector<CarriedTag>> {
|
||||
std::vector<TagSplit> splits;
|
||||
};
|
||||
|
||||
// The tag a piece of a split entity carries: "<tag>.split<piece + 1>".
|
||||
std::string split_tag_name(std::string_view tag, int piece);
|
||||
|
||||
std::string tag_view_key(int output_slot, Kind kind, const std::string& recorded_topo_id);
|
||||
|
||||
// The view of `node` (memoised). Never null for a non-null node.
|
||||
std::shared_ptr<const TagView> tag_view(const NodePtr& node);
|
||||
|
||||
// The tagged entities split by `node` and by every node upstream of it, upstream first.
|
||||
std::vector<TagSplit> tag_splits(const NodePtr& node);
|
||||
|
||||
// The lineage witnesses the history carries to `entity`, a sub-shape of a recorded output (empty otherwise).
|
||||
std::vector<TagLineageWitness> history_witnesses(const Shape& entity);
|
||||
|
||||
|
||||
@@ -161,7 +161,13 @@ ResolvedRef resolve_by_history(const NodePtr& target, const ElementAnchor& ancho
|
||||
|
||||
for (std::size_t order = start + 1; order < closure.size(); ++order) {
|
||||
const OperationNode& node = *closure[order];
|
||||
// The members this node consumed: entities of the outputs of its inputs.
|
||||
// The members this node consumed: entities of the outputs of its inputs it was given (one piece of a split body
|
||||
// is one output of the split; the other pieces go elsewhere).
|
||||
std::set<std::pair<std::string, int>> bound;
|
||||
for (const InputBinding& binding : node.bindings) {
|
||||
if (!binding.external())
|
||||
bound.emplace(binding.node_id, binding.output_slot);
|
||||
}
|
||||
std::vector<TopoRef> consumed;
|
||||
std::unordered_set<std::string> seen_inputs;
|
||||
for (const NodePtr& input : node.inputs) {
|
||||
@@ -170,8 +176,11 @@ ResolvedRef resolve_by_history(const NodePtr& target, const ElementAnchor& ancho
|
||||
const auto found = members.by_node.find(input->node_id);
|
||||
if (found == members.by_node.end())
|
||||
continue;
|
||||
for (const std::string& key : found->second)
|
||||
consumed.push_back(members.by_key.at(key));
|
||||
for (const std::string& key : found->second) {
|
||||
const TopoRef& member = members.by_key.at(key);
|
||||
if (bound.empty() || bound.count({input->node_id, member.output_slot}) != 0)
|
||||
consumed.push_back(member);
|
||||
}
|
||||
}
|
||||
if (consumed.empty())
|
||||
continue;
|
||||
@@ -300,6 +309,16 @@ ResolvedRef resolve_by_history(const NodePtr& target, const ElementAnchor& ancho
|
||||
out.lost_at = target->node_id;
|
||||
out.reason = "not_in_target";
|
||||
}
|
||||
// The lineage reached the target node, in another of its outputs (another piece of a split body): not lost, only
|
||||
// not in this one.
|
||||
for (const std::string& key : members.by_node[target->node_id]) {
|
||||
const TopoRef& ref = members.by_key.at(key);
|
||||
if (ref.output_slot != target_slot && (mode == FollowMode::Derived || ref.kind == anchor.kind)) {
|
||||
out.lost_at = target->node_id;
|
||||
out.reason = "other_output";
|
||||
break;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// Keep the hops on the way to the targets (a branch that leads elsewhere is not this reference's history),
|
||||
@@ -563,10 +582,10 @@ StableAnchor stabilize(const NodePtr& within, const ElementAnchor& picked) {
|
||||
return out;
|
||||
}
|
||||
|
||||
std::optional<ElementAnchor> locate(const NodePtr& within, const StableAnchor& anchor) {
|
||||
const NodePtr node = pick_by_stable_key(within, anchor.node);
|
||||
if (!node)
|
||||
return std::nullopt;
|
||||
namespace {
|
||||
|
||||
// The entity `anchor` names in `node` (a node with the anchor's key).
|
||||
std::optional<ElementAnchor> anchor_in(const NodePtr& node, const StableAnchor& anchor) {
|
||||
if (anchor.role.empty())
|
||||
return ElementAnchor{node->node_id, anchor.output_slot, anchor.kind, anchor.topo_id};
|
||||
std::vector<ElementAnchor> all = anchors_for_role(node, anchor.role);
|
||||
@@ -577,6 +596,29 @@ std::optional<ElementAnchor> locate(const NodePtr& within, const StableAnchor& a
|
||||
return all[static_cast<std::size_t>(anchor.role_ordinal)];
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::optional<ElementAnchor> locate(const NodePtr& within, const StableAnchor& anchor) {
|
||||
if (const NodePtr node = pick_by_stable_key(within, anchor.node))
|
||||
return anchor_in(node, anchor);
|
||||
// Several nodes share the key and the parameters do not tell them apart (a reference made before a second box of
|
||||
// the cell existed). The history can: the one whose entity still reaches `within` is the one meant (a cut's tool
|
||||
// box is consumed by the cut, its body continues). One survivor is the answer; none or several stay ambiguous.
|
||||
std::optional<ElementAnchor> alive;
|
||||
for (const NodePtr& candidate : find_by_stable_key(within, anchor.node)) {
|
||||
const std::optional<ElementAnchor> found = anchor_in(candidate, anchor);
|
||||
if (!found)
|
||||
continue;
|
||||
const ResolvedRef resolved = resolve_by_history(within, *found, 0);
|
||||
if (resolved.status == RefStatus::Lost && resolved.reason != "other_output")
|
||||
continue;
|
||||
if (alive)
|
||||
return std::nullopt;
|
||||
alive = found;
|
||||
}
|
||||
return alive;
|
||||
}
|
||||
|
||||
Value to_value(const StableAnchor& anchor) {
|
||||
Value out = Value::object();
|
||||
out.set("feature", anchor.node.feature);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "scad/reactive/tag_view.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <cstdio>
|
||||
@@ -14,6 +15,8 @@
|
||||
#include "internal.hpp"
|
||||
#include "scad/core/coordinate_system.hpp"
|
||||
#include "scad/core/error.hpp"
|
||||
#include "scad/kernel/properties.hpp"
|
||||
#include "scad/reactive/element_ref.hpp"
|
||||
#include "scad/reactive/digest.hpp"
|
||||
#include "scad/reactive/geo_selection.hpp"
|
||||
#include "scad/reactive/lineage.hpp"
|
||||
@@ -324,6 +327,109 @@ struct RefResolver {
|
||||
}
|
||||
};
|
||||
|
||||
// The pieces an operation split an entity into, numbered. An entity of the inputs that continues as several entities
|
||||
// of its kind (a face cut in two by a slot, a solid by a through cut) gives each of them "piece" (0-based) and "pieces"
|
||||
// in its witness's metadata, in a geometric order that does not depend on OCCT's numbering: by centre, then size (the
|
||||
// order a split reference lists its candidates in). Tag lineage names the pieces after it (<tag>.split1 ..), so the
|
||||
// number is a recorded fact of the operation, not something a later reader re-derives.
|
||||
void number_pieces(TopoDelta& delta, const std::vector<Shape>& outputs) {
|
||||
std::map<std::string, std::vector<std::size_t>> children; // parent key -> entries continuing it
|
||||
for (std::size_t i = 0; i < delta.entries.size(); ++i) {
|
||||
const TopoEntry& entry = delta.entries[i];
|
||||
if (entry.event == TopoEvent::Deleted || entry.event == TopoEvent::Generated)
|
||||
continue;
|
||||
const TopoRef* parent = nullptr;
|
||||
int same_kind = 0;
|
||||
for (const TopoRef& candidate : entry.parent_refs) {
|
||||
if (candidate.kind == entry.ref.kind) {
|
||||
parent = &candidate;
|
||||
++same_kind;
|
||||
}
|
||||
}
|
||||
if (same_kind != 1)
|
||||
continue; // a merge (or no parent of its kind) continues no single entity
|
||||
children[ref_key(*parent)].push_back(i);
|
||||
}
|
||||
for (const auto& [parent, indices] : children) {
|
||||
if (indices.size() < 2)
|
||||
continue;
|
||||
struct Piece {
|
||||
std::size_t entry;
|
||||
std::tuple<double, double, double, double> key;
|
||||
};
|
||||
std::vector<Piece> pieces;
|
||||
for (const std::size_t i : indices) {
|
||||
const TopoRef& ref = delta.entries[i].ref;
|
||||
if (ref.output_slot < 0 || static_cast<std::size_t>(ref.output_slot) >= outputs.size())
|
||||
return; // an entity this node does not output: leave the split unnumbered rather than half-numbered
|
||||
Shape sub = outputs[static_cast<std::size_t>(ref.output_slot)];
|
||||
try {
|
||||
sub = subshapes_by_recorded_id(sub, ref.kind, {ref.topo_id}).front();
|
||||
} catch (const ValueError&) {
|
||||
return;
|
||||
}
|
||||
const auto round6 = [](double v) { return std::round(v * 1e6) / 1e6; };
|
||||
const Vec3 c = kernel::center_of_mass(sub.wrapped());
|
||||
double size = 0.0;
|
||||
if (ref.kind == Kind::Face || ref.kind == Kind::Shell)
|
||||
size = kernel::surface_area(sub.wrapped());
|
||||
else if (ref.kind == Kind::Edge || ref.kind == Kind::Wire)
|
||||
size = kernel::linear_length(sub.wrapped());
|
||||
else if (ref.kind == Kind::Solid)
|
||||
size = kernel::volume(sub.wrapped());
|
||||
pieces.push_back({i, {round6(c.x), round6(c.y), round6(c.z), round6(size)}});
|
||||
}
|
||||
std::stable_sort(pieces.begin(), pieces.end(), [](const Piece& a, const Piece& b) { return a.key < b.key; });
|
||||
for (std::size_t n = 0; n < pieces.size(); ++n) {
|
||||
Value& metadata = delta.entries[pieces[n].entry].metadata;
|
||||
if (!metadata.is_object())
|
||||
metadata = Value::object();
|
||||
metadata.set("piece", static_cast<std::int64_t>(n));
|
||||
metadata.set("pieces", static_cast<std::int64_t>(pieces.size()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An operation that takes one solid and gives one solid back (a fillet, a shell, a move) makes that solid's
|
||||
// continuation: the kernel's history speaks of faces and edges only, so the solid itself is continued here, as the one
|
||||
// thing the operation can have made of it. Booleans and splits say what became of their solids themselves.
|
||||
void continue_single_solid(TopoDelta& delta, const std::string& graph_id, const std::string& node_id,
|
||||
const std::vector<Shape>& outputs, const std::vector<OpInput>& inputs) {
|
||||
if (delta.entries.empty() || outputs.size() != 1 || outputs.front().kind() != Kind::Solid)
|
||||
return;
|
||||
const OpInput* solid = nullptr;
|
||||
for (const OpInput& input : inputs) {
|
||||
if (input.shape.kind() != Kind::Solid)
|
||||
continue;
|
||||
if (solid != nullptr)
|
||||
return; // several solids: not this rule's to say
|
||||
solid = &input;
|
||||
}
|
||||
if (solid == nullptr)
|
||||
return;
|
||||
for (const TopoEntry& entry : delta.entries) {
|
||||
if (entry.ref.kind == Kind::Solid)
|
||||
return;
|
||||
}
|
||||
const std::optional<TopoRef> source = topo_ref_of(solid->shape);
|
||||
if (!source)
|
||||
return;
|
||||
TopoRef parent = *source;
|
||||
parent.topo_id = "solid_" + parent.topo_id;
|
||||
TopoEntry entry;
|
||||
entry.ref = TopoRef{graph_id, node_id, 0, Kind::Solid, "solid_" + outputs.front().topo_id()};
|
||||
entry.event = TopoEvent::Modified;
|
||||
entry.origin_role = solid->role.empty() ? std::string("body") : solid->role;
|
||||
entry.parent_refs = {parent};
|
||||
entry.metadata = Value::object();
|
||||
entry.metadata.set("derivation", "continuation");
|
||||
entry.metadata.set("coverage", "complete");
|
||||
entry.metadata.set("status", "proven");
|
||||
entry.metadata.set("evidence_kind", "operation_rule");
|
||||
entry.metadata.set("source_kind", "SOLID");
|
||||
delta.entries.push_back(std::move(entry));
|
||||
}
|
||||
|
||||
TopoDelta resolve_recorded_delta(const TopoDelta& raw, const std::string& graph_id, const std::string& node_id,
|
||||
const std::vector<Shape>& outputs, const std::vector<OpInput>& inputs,
|
||||
const OperationGraph& graph) {
|
||||
@@ -365,6 +471,8 @@ TopoDelta resolve_recorded_delta(const TopoDelta& raw, const std::string& graph_
|
||||
}
|
||||
out.section_edges = refs.resolve_many(raw.section_edges, false);
|
||||
out.raw_event = raw.raw_event;
|
||||
number_pieces(out, outputs);
|
||||
continue_single_solid(out, graph_id, node_id, outputs, inputs);
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <unordered_set>
|
||||
|
||||
@@ -62,6 +63,46 @@ void carry(std::vector<CarriedTag>& into, CarriedTag tag) {
|
||||
into.push_back(std::move(tag));
|
||||
}
|
||||
|
||||
// Which piece of a split the witness's entity is (the operation numbered them when it was recorded), if it is one.
|
||||
std::optional<int> piece_of(const TopoEntry& entry) {
|
||||
const Value* piece = member(entry.metadata, "piece");
|
||||
const Value* pieces = member(entry.metadata, "pieces");
|
||||
if (piece == nullptr || pieces == nullptr || !piece->is_number() || !pieces->is_number() || pieces->as_double() < 2)
|
||||
return std::nullopt;
|
||||
return static_cast<int>(piece->as_double());
|
||||
}
|
||||
|
||||
// The binding a piece carries: the same assignment under the piece's tag, with an id of its own (bindings are told
|
||||
// apart by id), derived from the original, the operation and the piece so a replay names it alike.
|
||||
TagBinding piece_binding(const TagBinding& binding, const std::string& node_id, int piece) {
|
||||
TagBinding out = binding;
|
||||
out.tag = Symbol(split_tag_name(binding.tag.str(), piece));
|
||||
out.binding_id =
|
||||
BindingId("tag_binding_" + uuid5_url_hex("simplecad:split-tag:" + std::string(binding.binding_id.str()) + ":" +
|
||||
node_id + ":" + std::to_string(piece)));
|
||||
return out;
|
||||
}
|
||||
|
||||
void note_split(const TagView& view, std::map<std::pair<std::string, std::string>, TagSplit>& splits,
|
||||
const CarriedTag& tag, const TopoRef& parent, const TopoEntry& entry, const OperationNode& node,
|
||||
const std::string& piece_tag) {
|
||||
(void)view;
|
||||
TagSplit& split = splits[{std::string(tag.binding.binding_id.str()), parent.node_id + '\x1f' + parent.topo_id}];
|
||||
if (split.node_id.empty()) {
|
||||
split.tag = tag.binding.tag.str();
|
||||
split.node_id = node.node_id;
|
||||
split.op = node.op;
|
||||
split.source_topo_id = parent.topo_id;
|
||||
}
|
||||
const int piece = *piece_of(entry);
|
||||
if (split.into.size() <= static_cast<std::size_t>(piece)) {
|
||||
split.into.resize(static_cast<std::size_t>(piece) + 1);
|
||||
split.pieces.resize(static_cast<std::size_t>(piece) + 1);
|
||||
}
|
||||
split.into[static_cast<std::size_t>(piece)] = piece_tag;
|
||||
split.pieces[static_cast<std::size_t>(piece)] = entry.ref;
|
||||
}
|
||||
|
||||
// The entities a tag assignment targets, as keys of its own output (slot 0).
|
||||
std::vector<std::pair<std::string, std::string>> targets_of(const TagBinding& binding) {
|
||||
std::vector<Value> refs;
|
||||
@@ -163,6 +204,8 @@ TagView build_view(const OperationNode& node,
|
||||
return out;
|
||||
};
|
||||
|
||||
// The splits of this node, by (binding, entity it was), in the order they are met.
|
||||
std::map<std::pair<std::string, std::string>, TagSplit> splits;
|
||||
for (const TopoEntry& entry : node.topo_delta->entries) {
|
||||
if (entry.event == TopoEvent::Deleted)
|
||||
continue;
|
||||
@@ -174,6 +217,7 @@ TagView build_view(const OperationNode& node,
|
||||
if (entry.event == TopoEvent::Generated)
|
||||
continue;
|
||||
const std::string key = tag_view_key(entry.ref.output_slot, entry.ref.kind, entry.ref.topo_id);
|
||||
const std::optional<int> piece = piece_of(entry);
|
||||
for (const TopoRef& parent : entry.parent_refs) {
|
||||
for (const CarriedTag* tag : carried_by(parent)) {
|
||||
if (parent.kind != entry.ref.kind || !lineage_policy_allows(tag->binding.propagation(), *derivation))
|
||||
@@ -181,10 +225,16 @@ TagView build_view(const OperationNode& node,
|
||||
CarriedTag next = *tag;
|
||||
next.derivation = *derivation;
|
||||
next.op = node.op;
|
||||
if (piece) {
|
||||
next.binding = piece_binding(tag->binding, node.node_id, *piece);
|
||||
note_split(view, splits, *tag, parent, entry, node, next.binding.tag.str());
|
||||
}
|
||||
carry(view[key], std::move(next));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (auto& [_, split] : splits)
|
||||
view.splits.push_back(std::move(split));
|
||||
return view;
|
||||
}
|
||||
|
||||
@@ -206,6 +256,30 @@ std::vector<TagLineageWitness> provider(const Shape& entity) {
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string split_tag_name(std::string_view tag, int piece) {
|
||||
return std::string(tag) + ".split" + std::to_string(piece + 1);
|
||||
}
|
||||
|
||||
std::vector<TagSplit> tag_splits(const NodePtr& node) {
|
||||
std::vector<TagSplit> out;
|
||||
if (!node)
|
||||
return out;
|
||||
tag_view(node); // builds (and caches) the views of the whole closure
|
||||
Cache& c = cache();
|
||||
for (const NodePtr& item : upstream_closure({node})) {
|
||||
std::shared_ptr<const TagView> view;
|
||||
{
|
||||
const std::lock_guard<std::mutex> lock(c.mutex);
|
||||
if (const auto found = c.views.find(item.get()); found != c.views.end() && found->second.first.lock() == item)
|
||||
view = found->second.second;
|
||||
}
|
||||
if (!view)
|
||||
view = tag_view(item);
|
||||
out.insert(out.end(), view->splits.begin(), view->splits.end());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string tag_view_key(int output_slot, Kind kind, const std::string& recorded_topo_id) {
|
||||
return std::to_string(output_slot) + '\x1f' + std::string(kind_name(kind)) + '\x1f' + recorded_topo_id;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,8 @@ TrackedBooleanResult to_boolean_result(std::optional<Solid> solid, std::vector<S
|
||||
std::move(finished.delta_entries)};
|
||||
}
|
||||
|
||||
// Face history of one input of a boolean.
|
||||
// Face history of one input of a boolean, and the history of the input solid itself: which solids of the answer
|
||||
// it became (several when a cut splits it), so a body can be followed, and named, like its faces.
|
||||
void query_input_faces(tracking::HistorySource& history, const Solid& input, std::string_view origin_role,
|
||||
kernel::SubShapeIndex& in_result, tracking::DeltaBuilder& delta) {
|
||||
tracking::QuerySpec spec;
|
||||
@@ -34,6 +35,12 @@ void query_input_faces(tracking::HistorySource& history, const Solid& input, std
|
||||
spec.result = &in_result;
|
||||
spec.project_source_tags = true;
|
||||
tracking::query_sub_shape_history(history, input.wrapped(), TopAbs_FACE, spec, delta.witnesses);
|
||||
tracking::QuerySpec solids;
|
||||
solids.origin_role = origin_role;
|
||||
solids.kind = Kind::Solid;
|
||||
solids.result = &in_result;
|
||||
solids.project_source_tags = false;
|
||||
tracking::query_sub_shape_history(history, input.wrapped(), TopAbs_SOLID, solids, delta.witnesses);
|
||||
}
|
||||
|
||||
std::string input_role(std::size_t index) {
|
||||
@@ -114,6 +121,21 @@ TrackedBooleanResult track_union_history(const std::vector<Solid>& solids, const
|
||||
for (std::size_t i = 0; i < solids.size(); ++i) {
|
||||
query_input_faces(retained, solids[i], input_role(i), in_result, delta);
|
||||
}
|
||||
// The fuse reports its input solids deleted: the one solid of the answer is new to it. It is the merge of them
|
||||
// all (that is what a union is), so it continues each of them as a merge, not as nothing.
|
||||
std::erase_if(delta.witnesses,
|
||||
[](const tracking::Witness& w) { return w.kind == Kind::Solid && w.event == TopoEvent::Deleted; });
|
||||
for (std::size_t i = 0; i < solids.size(); ++i) {
|
||||
tracking::Witness merged;
|
||||
merged.topo_id = kernel_topo_id(result_solid.wrapped());
|
||||
merged.event = TopoEvent::Modified;
|
||||
merged.kind = Kind::Solid;
|
||||
merged.source_kind = Kind::Solid;
|
||||
merged.origin_role = input_role(i);
|
||||
merged.input_topo_id = kernel_topo_id(solids[i].wrapped());
|
||||
merged.derivation = "merge";
|
||||
delta.witnesses.push_back(std::move(merged));
|
||||
}
|
||||
}
|
||||
|
||||
// The section edges that survive into the result, each once.
|
||||
|
||||
@@ -251,8 +251,11 @@ TEST_CASE("a stable anchor names the node by feature, op and occurrence upstream
|
||||
// The value form round-trips.
|
||||
CHECK(stable_anchor_from_value(to_value(stable)).node.params_digest == stable.node.params_digest);
|
||||
|
||||
// Same key, same parameters: ambiguous, so nothing is located (never the first one).
|
||||
// Same key, and the parameters do not tell them apart: the history does. Only the plate's box face continues to the
|
||||
// cut (the inserted box's does not), so that one is located: by what happened, never by being first.
|
||||
StableAnchor blind = stable;
|
||||
blind.node.params_digest = "0000000000000000";
|
||||
CHECK_FALSE(locate(cut2, blind));
|
||||
const auto by_history = locate(cut2, blind);
|
||||
REQUIRE(by_history);
|
||||
CHECK(by_history->node_id == "c_node_00000002");
|
||||
}
|
||||
|
||||
@@ -398,13 +398,36 @@ TEST_CASE("a cut that removes everything has no solid, only deletions") {
|
||||
const Solid big = box_solid(10, 10, 10);
|
||||
const TrackedBooleanResult tracked = tracked_cut(tiny, big);
|
||||
CHECK_FALSE(tracked.solid.has_value());
|
||||
CHECK(tracked.delta.deleted.size() == 12); // all six faces of each input
|
||||
CHECK(tracked.delta.deleted.size() == 14); // all six faces of each input, and both input solids
|
||||
std::map<std::string, int> by_role;
|
||||
for (const TopoEntry& entry : tracked.delta.entries) {
|
||||
CHECK(entry.event == TopoEvent::Deleted);
|
||||
++by_role[*entry.origin_role];
|
||||
}
|
||||
CHECK(by_role == std::map<std::string, int>{{"body", 6}, {"tool", 6}});
|
||||
CHECK(by_role == std::map<std::string, int>{{"body", 7}, {"tool", 7}});
|
||||
}
|
||||
|
||||
TEST_CASE("a boolean says what became of its solids: a split cut continues the body in every piece") {
|
||||
const Solid bar = box_solid(40, 10, 10);
|
||||
const Solid slot = box_solid(2, 20, 20, {0, 0, -5});
|
||||
const TrackedBooleanResult tracked = tracked_cut(bar, slot);
|
||||
REQUIRE(tracked.solids.size() == 2);
|
||||
std::map<std::string, int> solids; // "<event>|<origin role>" -> count
|
||||
for (const TopoEntry& entry : tracked.delta.entries) {
|
||||
if (entry.ref.kind == Kind::Solid)
|
||||
++solids[std::string(to_string(entry.event)) + "|" + entry.origin_role.value_or("-")];
|
||||
}
|
||||
// the bar continues as both pieces, the slot is consumed
|
||||
CHECK(solids == std::map<std::string, int>{{"deleted|tool", 1}, {"modified|body", 2}});
|
||||
|
||||
// a fuse reports its inputs deleted; the one solid of the answer merges them
|
||||
const TrackedBooleanResult fused = tracked_union(bar, box_solid(4, 4, 20), false, 0.0);
|
||||
std::map<std::string, int> merged;
|
||||
for (const TopoEntry& entry : fused.delta.entries) {
|
||||
if (entry.ref.kind == Kind::Solid)
|
||||
++merged[std::string(to_string(entry.event)) + "|" + entry.metadata.find("derivation")->as_string()];
|
||||
}
|
||||
CHECK(merged == std::map<std::string, int>{{"modified|merge", 2}});
|
||||
}
|
||||
|
||||
TEST_CASE("the same boolean twice gives the same delta") {
|
||||
|
||||
@@ -100,8 +100,26 @@ inline std::string join(const Value* list) {
|
||||
}
|
||||
|
||||
// counts first, then the sorted E/R/S/D lines of tracking_golden_record.py.
|
||||
inline std::vector<std::string> summarise(const TopoDelta& delta, const DeltaEntries& entries,
|
||||
// The delta without its solid history: the Python reference the goldens were recorded from tracks faces and edges
|
||||
// only (what became of the input solids is SimpleCAD's own, tested in test_tracking_behaviour.cpp).
|
||||
inline TopoDelta without_solids(const TopoDelta& delta) {
|
||||
TopoDelta out = delta;
|
||||
const auto solid = [](const TopoRef& ref) { return ref.kind == Kind::Solid; };
|
||||
for (auto* list : {&out.preserved, &out.modified, &out.generated, &out.deleted})
|
||||
std::erase_if(*list, solid);
|
||||
std::erase_if(out.entries, [&](const TopoEntry& e) { return solid(e.ref); });
|
||||
return out;
|
||||
}
|
||||
|
||||
inline std::vector<std::string> summarise(const TopoDelta& full, const DeltaEntries& all_entries,
|
||||
const std::vector<TopoDS_Shape>& inputs, const TopoDS_Shape& result) {
|
||||
const TopoDelta delta = without_solids(full);
|
||||
DeltaEntries entries;
|
||||
for (const auto& [id, value] : all_entries) {
|
||||
const Value* kind = value.find("kind");
|
||||
if (kind == nullptr || upper(kind->as_string()) != "SOLID")
|
||||
entries.emplace(id, value);
|
||||
}
|
||||
std::vector<TopoDS_Shape> roots = inputs;
|
||||
roots.push_back(result);
|
||||
const ShapeIndex index = index_shapes(roots);
|
||||
|
||||
@@ -308,6 +308,7 @@ from simplecadapi._cpp import (
|
||||
apply_tag,
|
||||
apply_tag_rselection,
|
||||
explain_tag,
|
||||
list_tag_splits,
|
||||
list_tags,
|
||||
select_edges_by_tag,
|
||||
select_faces_by_tag,
|
||||
@@ -462,7 +463,7 @@ __description__ = "Simplified OpenCASCADE-native CAD modeling Python API"
|
||||
|
||||
# Convenience aliases
|
||||
Workplane = SimpleWorkplane
|
||||
from ._glue.pieces import Pieces # noqa: E402 (the pieces of a split body)
|
||||
from ._glue.pieces import Pieces, TagSplitWarning # noqa: E402 (the pieces of a split body; a split tag)
|
||||
|
||||
# Creation-function aliases
|
||||
create_angle_arc = make_angle_arc_redge
|
||||
@@ -536,6 +537,7 @@ __all__ = [
|
||||
# Core classes
|
||||
"CoordinateSystem",
|
||||
"Pieces",
|
||||
"TagSplitWarning",
|
||||
"SimpleWorkplane",
|
||||
"Workplane",
|
||||
"Vertex",
|
||||
@@ -729,6 +731,7 @@ __all__ = [
|
||||
"apply_tag",
|
||||
"apply_tag_rselection",
|
||||
"explain_tag",
|
||||
"list_tag_splits",
|
||||
"list_tags",
|
||||
"select_edges_by_tag",
|
||||
"select_faces_by_tag",
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -581,14 +581,17 @@ def with_signature(function: Any) -> Any:
|
||||
|
||||
name = getattr(function, "__name__", "")
|
||||
if name.endswith(_OP_SUFFIXES) or name in _SHAPE_FUNCTIONS:
|
||||
from .pieces import SPLITS, TAKES_PIECES, Pieces, apply_to_pieces
|
||||
from .pieces import SPLITS, TAKES_PIECES, Pieces, apply_to_pieces, run_on_pieces
|
||||
|
||||
@functools.wraps(function)
|
||||
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
||||
# the pieces of a split body: one operation per piece, unless the operation takes them together
|
||||
if name not in TAKES_PIECES and any(isinstance(a, Pieces) for a in (*args, *kwargs.values())):
|
||||
return apply_to_pieces(name, function, args, kwargs)
|
||||
result = function(*args, **kwargs)
|
||||
if any(isinstance(a, Pieces) for a in (*args, *kwargs.values())):
|
||||
if name not in TAKES_PIECES:
|
||||
return apply_to_pieces(name, function, args, kwargs)
|
||||
result = run_on_pieces(function, args, kwargs)
|
||||
else:
|
||||
result = function(*args, **kwargs)
|
||||
return Pieces(result) if name in SPLITS and isinstance(result, list) else result
|
||||
|
||||
else:
|
||||
|
||||
@@ -96,7 +96,7 @@
|
||||
"add_revolute_constraint_rassembly": "Constrain two connectors as a revolute axis pair.",
|
||||
"and_": "Combine predicates so all of them must match.",
|
||||
"apply_tag": "Attach a local user tag with continuation/fragment lineage policy.",
|
||||
"apply_tag_rselection": "Return a semantic shape view with a canonical tag assignment.\n\nA tag is also how a face, an edge or a vertex gets a name people read: there is no\nsecond naming system. Tags resolve through the recorded history, so a tagged face\nkeeps its name through later features (``ql.tag(...)`` and\n``select_faces_by_tag(...)`` find it again); the editor's \"name a face\" form is this\noperation with the picked faces as ``targets``.\n\nArgs:\n scope: The shape the tag is assigned in (a Solid, usually the body).\n targets: What to tag: a ``ql`` selection (``scad.ql.faces().where(...)``) or a\n list of sub-shapes of ``scope``.\n tag: The name, a normalized token such as ``\"lid_seat\"`` or\n ``\"role.mounting_surface\"``.\n topology_propagation: ``\"local\"`` tags the targets only; ``\"downward\"`` also\n their edges and vertices.\n lineage_policy: How the tag follows the targets through later operations\n (default ``\"continuation_fragment\"``: kept on continued faces and on the\n fragments of a split face).\n\nReturns:\n AnyShape: A view of ``scope`` with the tag assigned (the same geometry).\n\nRaises:\n SimpleCADError: The selection resolved nothing, a target is not inside the\n scope, or the tag is malformed.\n\nUsage:\n ``block = scad.apply_tag_rselection(block, scad.ql.faces().where(scad.ql.prop(\"geom.normal.z\", \">=\", 0.999)), \"lid_seat\")``\n names the top face; ``scad.ql.faces().where(scad.ql.tag(\"lid_seat\"))`` selects it\n later. A body of a Part is named with ``set_body_appearance_rpart(part, body_id, name=...)``.",
|
||||
"apply_tag_rselection": "Return a semantic shape view with a canonical tag assignment.\n\nA tag is also how a face, an edge or a vertex gets a name people read: there is no\nsecond naming system. Tags resolve through the recorded history, so a tagged face\nkeeps its name through later features (``ql.tag(...)`` and\n``select_faces_by_tag(...)`` find it again); the editor's \"name a face\" form is this\noperation with the picked faces as ``targets``.\n\nArgs:\n scope: The shape the tag is assigned in (a Solid, usually the body).\n targets: What to tag: a ``ql`` selection (``scad.ql.faces().where(...)``) or a\n list of sub-shapes of ``scope``.\n tag: The name, a normalized token such as ``\"lid_seat\"`` or\n ``\"role.mounting_surface\"``.\n topology_propagation: ``\"local\"`` tags the targets only; ``\"downward\"`` also\n their edges and vertices.\n lineage_policy: How the tag follows the targets through later operations\n (default ``\"continuation_fragment\"``: kept on continued faces; the\n pieces of a split face carry ``<tag>.split1`` .. ``<tag>.split<n>`` instead,\n see ``list_tag_splits``).\n\nReturns:\n AnyShape: A view of ``scope`` with the tag assigned (the same geometry).\n\nRaises:\n SimpleCADError: The selection resolved nothing, a target is not inside the\n scope, or the tag is malformed.\n\nUsage:\n ``block = scad.apply_tag_rselection(block, scad.ql.faces().where(scad.ql.prop(\"geom.normal.z\", \">=\", 0.999)), \"lid_seat\")``\n names the top face; ``scad.ql.faces().where(scad.ql.tag(\"lid_seat\"))`` selects it\n later. A body of a Part is named with ``set_body_appearance_rpart(part, body_id, name=...)``.",
|
||||
"apply_tracking_tags_to_delta": "Apply evidence-gated tracking projections for one operation result.",
|
||||
"assert_blend_volume_monotonic": "Mechanism E exit check: an all-convex blend may only remove material.\n\nObserved kernel behavior (and the reason this check exists): filleting\nevery edge of a 10 mm cube with r=6 *succeeds* and returns a solid whose\nvolume (1036.35) exceeds the input (1000) — geometrically impossible\noutput that the kernel hands back without a word. Fillet and chamfer\noutputs on convex edges are subsets of the input solid, so a volume\nincrease beyond measurement noise means the kernel silently produced\ngarbage; we name it instead of returning it.\n\nThe increase check only fires for provably all-convex selections:\nblending a *concave* edge legitimately adds material (the corner fill —\ne.g. a bolt's underhead fillet gains exactly the quarter-circle deficit\ntimes its circumference), and undeterminable edges mean the check\ncannot prove impossibility. A non-positive result volume is garbage\nregardless of convexity and always fires.\n\nThe check runs on the success path, so it must stay cheap: two GProp\nvolume evaluations plus one side-probe per selected edge. Raised as a\n``BlendVolumeViolation`` so the caller's ``_wrap_blend_failure`` handler\npromotes the measured facts and layers the standard blend diagnosis\n(probes, evidence render) on top.",
|
||||
"assign_material_rpart": "Assign a Material to a Part and return the updated Part.",
|
||||
@@ -308,7 +308,7 @@
|
||||
"suspend_graph_recording": "Temporarily suspend automatic graph recording for internal API composition.",
|
||||
"sweep_multisection_rsolid": "Sweep through explicit ordered sections along a continuous path.\n\nAt least two ordered sections are needed. Face sections supply their outer\nwire, matching build123d's multi-section sweep contract. ``binormal`` is an\noptional direction vector or an auxiliary spine. The kernel must produce\none valid solid. Every section and the path are recorded as inputs of\n``make_sweep_multisection_rsolid``, so model JSON preserves the\nconstruction.\n\nArgs:\n profiles: Ordered section faces or wires (at least two).\n path: The continuous path wire.\n is_frenet: Use the Frenet frame along the path.\n binormal: A direction, or an auxiliary spine wire, that fixes the\n section orientation.\n\nReturns:\n The swept solid.\n\nRaises:\n TypeError: A section is neither a Face nor a Wire.\n ValueError: Fewer than two sections, a zero ``binormal`` direction, or\n the kernel could not make a solid.",
|
||||
"sweep_rsolid": "Create a swept solid, with optional kernel-role-based tags.",
|
||||
"tag": "Build a tag predicate for QL filtering.\n\nTags are a view over the recorded history: a tag assigned in a\n``GraphSession`` reaches every entity its target became through later\noperations (a face cut in two keeps it on both pieces), as its lineage\npolicy allows. ``local`` is what the entity itself stores, ``inherited``\nwhat containing entities pass down, ``lineage`` what the history carries,\nand ``effective`` (the default) all three.\n\nArgs:\n pattern: Exact tag string or a trailing `*` prefix match.\n scope: One of ``local``, ``inherited``, ``effective``, or ``lineage``.\n\nReturns:\n Serializable predicate that can be used in `Query.where(...)`.",
|
||||
"tag": "Build a tag predicate for QL filtering.\n\nTags are a view over the recorded history: a tag assigned in a\n``GraphSession`` reaches every entity its target became through later\noperations as its lineage policy allows. A tag follows its entity as a\nreference does: an entity an operation splits keeps it on none of its\npieces, which carry ``<tag>.split1`` .. ``<tag>.split<n>`` instead\n(``list_tag_splits``); ``ql.tag(\"<tag>.*\")`` finds them all. ``local`` is what the entity itself stores, ``inherited``\nwhat containing entities pass down, ``lineage`` what the history carries,\nand ``effective`` (the default) all three.\n\nArgs:\n pattern: Exact tag string or a trailing `*` prefix match.\n scope: One of ``local``, ``inherited``, ``effective``, or ``lineage``.\n\nReturns:\n Serializable predicate that can be used in `Query.where(...)`.",
|
||||
"topo_ref_from_dict": "Reconstruct a TopoRef from serialized data.",
|
||||
"topo_ref_to_dict": "Serialize a TopoRef into a JSON-compatible dictionary.",
|
||||
"track_union_history": "Build one face-level union delta from retained N-ary OCC history.",
|
||||
@@ -371,5 +371,6 @@
|
||||
"make_workplane_from_points_rworkplane": "Create a workplane through three points: origin at ``a``, x towards ``b``, normal = (b - a) x (c - a).\n\nRecorded: the node takes the inputs as ordered references, so a model-JSON replay builds the frame again from the\ngeometry as it is then, and a sketch on the workplane (``plane=wp``) or an operation inside ``with wp:`` follows it.\n\nArgs:\n a: A Vertex of the model or a point (current coordinate system): the origin.\n b: A Vertex or a point: x points from ``a`` towards it.\n c: A Vertex or a point on the positive-y side of the plane.\n\nReturns:\n SimpleWorkplane: a frame in world coordinates (``origin``, ``normal``, ``x_dir``, ``y_dir``, ``plane``) that is\n also a context manager: ``with wp:`` makes it the current coordinate system, ``make_sketch_rsketch(plane=wp)``\n draws on it. It is a value: enter it again in later code, pickle it (the notebook cell cache does).\n\nRaises:\n SimpleCADError: The three points lie on one line or two coincide.\n\nUsage:\n ``scad.make_workplane_from_points_rworkplane(v0, v1, v2)`` with three picked vertices; points given as\n numbers are recorded as numbers.\n",
|
||||
"make_workplane_from_axis_rworkplane": "Create a workplane through an axis, turned about it by an angle.\n\nThe axis is a straight edge (from its start, along it) or a circular edge (its centre line: through the centre,\nalong the circle's normal). x = the axis direction. At ``angle=0`` the plane is the plane of ``face`` (a planar face\ncontaining the axis direction, usually one the edge bounds) or, without one, the plane whose normal is global Z\n(global X for an axis along Z) made square to the axis; ``angle`` turns it right-handed about the axis.\n\nRecorded: the node takes the inputs as ordered references, so a model-JSON replay builds the frame again from the\ngeometry as it is then, and a sketch on the workplane (``plane=wp``) or an operation inside ``with wp:`` follows it.\n\nArgs:\n axis: A straight or circular Edge.\n angle: The turn about the axis, in degrees.\n face: The planar Face the plane starts from at angle 0.\n\nReturns:\n SimpleWorkplane: a frame in world coordinates (``origin``, ``normal``, ``x_dir``, ``y_dir``, ``plane``) that is\n also a context manager: ``with wp:`` makes it the current coordinate system, ``make_sketch_rsketch(plane=wp)``\n draws on it. It is a value: enter it again in later code, pickle it (the notebook cell cache does).\n\nRaises:\n SimpleCADError: The edge is neither straight nor circular, the face is not planar, or the face's normal is\n along the axis.\n\nUsage:\n ``scad.make_workplane_from_axis_rworkplane(edge, 30, face=top)``: a plane hinged on an edge of the top\n face, tilted 30 degrees.\n",
|
||||
"make_workplane_midplane_rworkplane": "Create the workplane halfway between two parallel planar faces (a symmetry plane).\n\nnormal and x come from ``face_a``; origin = the middle between the centre of ``face_a`` and its projection onto the\nplane of ``face_b``.\n\nRecorded: the node takes the inputs as ordered references, so a model-JSON replay builds the frame again from the\ngeometry as it is then, and a sketch on the workplane (``plane=wp``) or an operation inside ``with wp:`` follows it.\n\nArgs:\n face_a: A planar Face; it gives the normal and x.\n face_b: A planar Face parallel to it.\n\nReturns:\n SimpleWorkplane: a frame in world coordinates (``origin``, ``normal``, ``x_dir``, ``y_dir``, ``plane``) that is\n also a context manager: ``with wp:`` makes it the current coordinate system, ``make_sketch_rsketch(plane=wp)``\n draws on it. It is a value: enter it again in later code, pickle it (the notebook cell cache does).\n\nRaises:\n SimpleCADError: A face is not planar or the faces are not parallel.\n\nUsage:\n ``mid = scad.make_workplane_midplane_rworkplane(left_wall, right_wall)``; mirror or sketch on it.\n",
|
||||
"make_workplane_normal_to_curve_rworkplane": "Create a workplane normal to a curve: the plane of a sweep profile.\n\norigin = the point at ``at`` (a fraction of the curve's length: 0 = start, 1 = end); normal = the direction of\ntravel there; x = ``x_dir`` projected onto the plane, or global Z made square to the normal (global X when the\ntangent is near Z).\n\nRecorded: the node takes the inputs as ordered references, so a model-JSON replay builds the frame again from the\ngeometry as it is then, and a sketch on the workplane (``plane=wp``) or an operation inside ``with wp:`` follows it.\n\nArgs:\n curve: An Edge or a Wire (the sweep path).\n at: The fraction of the length, in [0, 1].\n x_dir: The direction of x, projected onto the plane.\n\nReturns:\n SimpleWorkplane: a frame in world coordinates (``origin``, ``normal``, ``x_dir``, ``y_dir``, ``plane``) that is\n also a context manager: ``with wp:`` makes it the current coordinate system, ``make_sketch_rsketch(plane=wp)``\n draws on it. It is a value: enter it again in later code, pickle it (the notebook cell cache does).\n\nRaises:\n SimpleCADError: ``at`` is outside [0, 1], the curve has no length, or ``x_dir`` is along the tangent.\n\nUsage:\n ``start = scad.make_workplane_normal_to_curve_rworkplane(path, 0)``;\n ``profile = ... make_sketch_rsketch(\"profile\", plane=start) ...``; ``sweep_rsolid(profile, path)``.\n"
|
||||
"make_workplane_normal_to_curve_rworkplane": "Create a workplane normal to a curve: the plane of a sweep profile.\n\norigin = the point at ``at`` (a fraction of the curve's length: 0 = start, 1 = end); normal = the direction of\ntravel there; x = ``x_dir`` projected onto the plane, or global Z made square to the normal (global X when the\ntangent is near Z).\n\nRecorded: the node takes the inputs as ordered references, so a model-JSON replay builds the frame again from the\ngeometry as it is then, and a sketch on the workplane (``plane=wp``) or an operation inside ``with wp:`` follows it.\n\nArgs:\n curve: An Edge or a Wire (the sweep path).\n at: The fraction of the length, in [0, 1].\n x_dir: The direction of x, projected onto the plane.\n\nReturns:\n SimpleWorkplane: a frame in world coordinates (``origin``, ``normal``, ``x_dir``, ``y_dir``, ``plane``) that is\n also a context manager: ``with wp:`` makes it the current coordinate system, ``make_sketch_rsketch(plane=wp)``\n draws on it. It is a value: enter it again in later code, pickle it (the notebook cell cache does).\n\nRaises:\n SimpleCADError: ``at`` is outside [0, 1], the curve has no length, or ``x_dir`` is along the tangent.\n\nUsage:\n ``start = scad.make_workplane_normal_to_curve_rworkplane(path, 0)``;\n ``profile = ... make_sketch_rsketch(\"profile\", plane=start) ...``; ``sweep_rsolid(profile, path)``.\n",
|
||||
"list_tag_splits": "The tagged entities that the operations behind a shape split into pieces.\n\nA tag follows its entity the way a reference does: while the entity stays one entity it keeps the tag; when an\noperation splits it (a slot cut across a tagged face, a cut through a tagged body), the tag does not go to every\npiece. Each piece carries ``<tag>.split1`` .. ``<tag>.split<n>`` instead, numbered as the operation recorded them (by\ncentre, then size), and ``ql.tag(\"<tag>\")`` finds none of them. Name the pieces you mean with tags of your own after the\nsplit, or select them with ``ql.tag(\"<tag>.split1\")`` / ``ql.tag(\"<tag>.*\")``.\n\nArgs:\n shape: A shape made in a recording session (its history is read).\n\nReturns:\n list[dict]: One row per split, upstream first: ``tag`` (the tag the entity had), ``into`` (the tags of the pieces,\n in piece order), ``node_id`` and ``op`` (the operation that split it), ``source_topo_id`` and ``pieces``\n (``output_slot``, ``kind``, ``topo_id`` of each piece in that operation's output). Empty for a shape without\n recorded history.\n\nExamples:\n >>> top = scad.apply_tag_rselection(box, scad.ql.faces().where(scad.ql.prop(\"geom.center.z\", \">=\", 9.9)), \"mount.top\")\n >>> halves = scad.cut_rsolid(top, slot) # the slot splits the top face (and the body)\n >>> [row[\"into\"] for row in scad.list_tag_splits(halves[0])]\n [['mount.top.split1', 'mount.top.split2']]"
|
||||
}
|
||||
|
||||
@@ -201,6 +201,7 @@
|
||||
"evaluate_scalar": "simplecadapi.params.expr",
|
||||
"evaluate_value": "simplecadapi.params.expr",
|
||||
"explain_tag": "simplecadapi.operators.selection",
|
||||
"list_tag_splits": "simplecadapi.operators.selection",
|
||||
"explode_rassembly": "simplecadapi.operators.product",
|
||||
"expression_uses_units": "simplecadapi.params.units",
|
||||
"extend_rsketch": "simplecadapi.operators.sketch",
|
||||
|
||||
@@ -21,6 +21,57 @@ SPLITS = frozenset({"cut_rsolid", "fillet_rsolid", "chamfer_rsolid"})
|
||||
"""Operations whose list result is the pieces of one body."""
|
||||
|
||||
|
||||
class TagSplitWarning(UserWarning):
|
||||
"""An operation split a tagged entity: the tag went to none of the pieces, each carries ``<tag>.split<i>``.
|
||||
|
||||
A diagnostic, not a failure: a tag follows its entity as a reference does, and a split is where that ends. Look at
|
||||
the pieces (the editor highlights them), and tag the ones you mean after the split if later code needs them.
|
||||
"""
|
||||
|
||||
|
||||
def tag_splits(values: Any, namespace: str) -> list[dict]:
|
||||
"""The tag splits the operations of one cell (node ids ``<namespace>_...``) made, in the shapes *values* hold."""
|
||||
|
||||
from simplecadapi._cpp import Solid, list_tag_splits
|
||||
|
||||
shapes: list = []
|
||||
|
||||
def collect(value: Any) -> None:
|
||||
if isinstance(value, Solid):
|
||||
shapes.append(value)
|
||||
elif isinstance(value, (list, tuple)):
|
||||
for item in value:
|
||||
collect(item)
|
||||
elif type(value).__name__ == "Part":
|
||||
for body in value.bodies:
|
||||
collect(body.solid)
|
||||
|
||||
for value in values:
|
||||
collect(value)
|
||||
seen: set = set()
|
||||
out: list[dict] = []
|
||||
for shape in shapes:
|
||||
try:
|
||||
rows = list_tag_splits(shape)
|
||||
except Exception: # noqa: BLE001 - a diagnostic never fails the cell
|
||||
continue
|
||||
for row in rows:
|
||||
if not row["node_id"].startswith(namespace + "_"):
|
||||
continue
|
||||
key = (row["node_id"], row["tag"], row["source_topo_id"])
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
out.append(row)
|
||||
return out
|
||||
|
||||
|
||||
def split_message(row: dict) -> str:
|
||||
into = ", ".join(row["into"])
|
||||
return (f"{row['op']} split the entity tagged {row['tag']!r} into {len(row['into'])} pieces; "
|
||||
f"they carry {into} and {row['tag']!r} names none of them. Tag the pieces you mean after this operation "
|
||||
f"if later code selects them (scad.list_tag_splits(shape) lists the splits).")
|
||||
|
||||
|
||||
class Pieces(list):
|
||||
"""The solids one body was split into, in a stable order (``cut_rsolid``: by centroid)."""
|
||||
|
||||
@@ -59,6 +110,21 @@ def apply_to_pieces(name: str, function: Callable[..., Any], args: tuple, kwargs
|
||||
selectors = {("arg", i): _open(a) for i, a in enumerate(args) if _is_selector(a)}
|
||||
selectors.update({("kw", k): _open(v) for k, v in kwargs.items() if _is_selector(v)})
|
||||
found = {slot: 0 for slot in selectors}
|
||||
from ..ref import IN_PIECES
|
||||
|
||||
token = IN_PIECES.set(True)
|
||||
try:
|
||||
out = _each_piece(function, pieces, side, key, args, kwargs, selectors, found)
|
||||
finally:
|
||||
IN_PIECES.reset(token)
|
||||
for slot, (_, cardinality) in selectors.items():
|
||||
if found[slot] == 0:
|
||||
raise ValueError(f"{name}: the selection found nothing on any piece of the split body")
|
||||
_check(name, cardinality, found[slot])
|
||||
return out
|
||||
|
||||
|
||||
def _each_piece(function, pieces, side, key, args, kwargs, selectors, found) -> Pieces:
|
||||
out = Pieces()
|
||||
for piece in pieces:
|
||||
call_args, call_kwargs = list(args), dict(kwargs)
|
||||
@@ -84,9 +150,18 @@ def apply_to_pieces(name: str, function: Callable[..., Any], args: tuple, kwargs
|
||||
out.extend(result)
|
||||
else:
|
||||
out.append(result)
|
||||
for slot, (_, cardinality) in selectors.items():
|
||||
_check(name, cardinality, found[slot])
|
||||
return out
|
||||
|
||||
|
||||
__all__ = ["Pieces", "SPLITS", "TAKES_PIECES", "apply_to_pieces"]
|
||||
def run_on_pieces(function: Callable[..., Any], args: tuple, kwargs: dict) -> Any:
|
||||
"""Run an operation that takes the pieces together (:data:`TAKES_PIECES`), its selectors resolved per piece."""
|
||||
from ..ref import IN_PIECES
|
||||
|
||||
token = IN_PIECES.set(True)
|
||||
try:
|
||||
return function(*args, **kwargs)
|
||||
finally:
|
||||
IN_PIECES.reset(token)
|
||||
|
||||
|
||||
__all__ = ["Pieces", "SPLITS", "TAKES_PIECES", "TagSplitWarning", "apply_to_pieces", "run_on_pieces", "split_message", "tag_splits"]
|
||||
|
||||
@@ -596,6 +596,13 @@ class MarimoKernel:
|
||||
" print('SCA-WORKPLANES', _wjson.dumps(_workplanes()))\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"
|
||||
" import json as _sjson\n"
|
||||
" print('SCA-TAGSPLITS', _sjson.dumps(_splits()))\n"
|
||||
"except Exception:\n"
|
||||
" pass\n"
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -607,6 +614,11 @@ class MarimoKernel:
|
||||
out["workplanes"] = json.loads(line[len("SCA-WORKPLANES "):])
|
||||
except ValueError:
|
||||
pass
|
||||
elif line.startswith("SCA-TAGSPLITS "):
|
||||
try:
|
||||
out["tag_splits"] = json.loads(line[len("SCA-TAGSPLITS "):])
|
||||
except ValueError:
|
||||
pass
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -122,6 +122,7 @@ class WorkspaceState:
|
||||
"preview",
|
||||
"selection",
|
||||
"workplanes",
|
||||
"tag_splits",
|
||||
)
|
||||
|
||||
def __init__(self, workspace: Path, notebook: Path | None = None) -> None:
|
||||
@@ -133,6 +134,7 @@ class WorkspaceState:
|
||||
self.lock = threading.Lock()
|
||||
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.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.
|
||||
@@ -269,6 +271,7 @@ class WorkspaceState:
|
||||
return
|
||||
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
|
||||
kernel = MarimoKernel(
|
||||
notebook,
|
||||
server_port=self.port,
|
||||
@@ -1141,6 +1144,8 @@ class WorkspaceState:
|
||||
published = time.perf_counter()
|
||||
self.push_cells()
|
||||
self._push_workplanes(result.get("workplanes"))
|
||||
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"):
|
||||
print(
|
||||
f"[sca edit] settle: kernel call {(published - signed) * 1000:.0f} ms "
|
||||
@@ -1169,6 +1174,14 @@ class WorkspaceState:
|
||||
self._last_publish_error = message
|
||||
self.hub.broadcast({"type": "status", "error": message[-300:]})
|
||||
|
||||
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 []):
|
||||
return
|
||||
self._tag_splits = splits
|
||||
self.emit({"type": "tag_splits", "splits": splits})
|
||||
self.write_snapshot()
|
||||
|
||||
def _push_workplanes(self, workplanes: Any) -> None:
|
||||
"""The notebook's workplanes and their frames, as the kernel computed them: sent when they change."""
|
||||
if not isinstance(workplanes, list) or workplanes == self._workplanes:
|
||||
@@ -1660,6 +1673,10 @@ class WorkspaceState:
|
||||
},
|
||||
"modified_parameters": sorted(saved),
|
||||
"model_revision": self.preview_revision,
|
||||
# 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 []
|
||||
],
|
||||
}
|
||||
|
||||
def write_endpoint(self, host: str) -> None:
|
||||
|
||||
@@ -125,6 +125,7 @@ from simplecadapi._cpp import (
|
||||
apply_tag,
|
||||
apply_tag_rselection,
|
||||
explain_tag,
|
||||
list_tag_splits,
|
||||
list_tags,
|
||||
select_edges_by_tag,
|
||||
select_faces_by_tag,
|
||||
@@ -315,6 +316,7 @@ __all__ = [
|
||||
"elevate_curve_degree_redge",
|
||||
"elevate_surface_degree_rface",
|
||||
"explain_tag",
|
||||
"list_tag_splits",
|
||||
"explode_rassembly",
|
||||
"extend_rsketch",
|
||||
"extrude_rsolid",
|
||||
|
||||
@@ -15,6 +15,7 @@ from simplecadapi._cpp import (
|
||||
apply_tag,
|
||||
apply_tag_rselection,
|
||||
explain_tag,
|
||||
list_tag_splits,
|
||||
list_tags,
|
||||
select_edges_by_tag,
|
||||
select_faces_by_tag,
|
||||
@@ -24,6 +25,7 @@ __all__ = [
|
||||
"apply_tag",
|
||||
"apply_tag_rselection",
|
||||
"explain_tag",
|
||||
"list_tag_splits",
|
||||
"list_tags",
|
||||
"select_edges_by_tag",
|
||||
"select_faces_by_tag",
|
||||
|
||||
+96
-13
@@ -34,6 +34,7 @@ reference without it was made under version 1).
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import contextvars
|
||||
import dataclasses
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
@@ -49,14 +50,14 @@ _native = _cpp._native if hasattr(_cpp, "_native") else None
|
||||
NAMING: int = int(_er.NAMING_VERSION.rsplit("/", 1)[-1])
|
||||
"""The naming version references are made under now (``scad-naming/<NAMING>``)."""
|
||||
|
||||
Kind = Literal["face", "edge", "vertex"]
|
||||
Kind = Literal["face", "edge", "vertex", "solid"]
|
||||
Follow = Literal["identity", "derived"]
|
||||
Guard = Union[Tuple[str, Tuple[float, float, float], float], Tuple[str, Tuple[float, float, float], float, Tuple[float, float, float]]]
|
||||
"""``(geometry type, centre, size)`` or ``(geometry type, centre, size, normal)``: what the entity looked like when it
|
||||
was picked (size: area of a face, length of an edge). It never chooses between history results; it checks a
|
||||
was picked (size: area of a face, length of an edge, volume of a solid). It never chooses between history results; it checks a
|
||||
positional anchor and ranks look-alikes of a lost reference."""
|
||||
|
||||
_KINDS = ("face", "edge", "vertex")
|
||||
_KINDS = ("face", "edge", "vertex", "solid")
|
||||
_RECORD_VERSION = 1
|
||||
|
||||
|
||||
@@ -137,7 +138,7 @@ def _check_between(between: Any) -> tuple:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ElementRef:
|
||||
"""A stable reference to one face, edge or vertex; ``repr()`` is the code that makes it.
|
||||
"""A stable reference to one face, edge, vertex or solid; ``repr()`` is the code that makes it.
|
||||
|
||||
Fields: ``kind``; ``feature`` and ``op`` (where the entity was born); then exactly one of ``role`` (its kernel
|
||||
role, with ``ordinal`` saying which of the entities with that role), ``topo`` (its position in that output, for an
|
||||
@@ -166,9 +167,11 @@ class ElementRef:
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.kind not in _KINDS:
|
||||
raise ValueError(f"a reference names a face, an edge or a vertex, not {self.kind!r}")
|
||||
raise ValueError(f"a reference names a face, an edge, a vertex or a solid, not {self.kind!r}")
|
||||
if sum(x is not None for x in (self.role, self.topo, self.between)) != 1:
|
||||
raise ValueError("a reference names its entity by role=, by topo= or (an edge) by between=, exactly one of them")
|
||||
if self.kind == "solid" and self.topo is None:
|
||||
raise ValueError("a solid has no kernel role: a solid reference names it by topo= (its place in the output)")
|
||||
if self.between is not None:
|
||||
if self.kind != "edge":
|
||||
raise ValueError("between= names an edge by the two faces it lies between")
|
||||
@@ -277,16 +280,50 @@ class ElementRef:
|
||||
|
||||
# -- resolving ---------------------------------------------------------------------------------------------------
|
||||
def resolve(self, shape: Any) -> Resolution:
|
||||
"""Follow the reference to the entities of *shape*; never raises for a split or a lost reference."""
|
||||
"""Follow the reference to the entities of *shape*; never raises for a split or a lost reference.
|
||||
|
||||
*shape* may be the pieces of a split body (``scad.Pieces``, a list of solids): the reference is resolved in each,
|
||||
and ``bodies`` says which piece each entity lies in.
|
||||
"""
|
||||
if isinstance(shape, (list, tuple)):
|
||||
return self._resolve_in_pieces(list(shape))
|
||||
if self.between is not None:
|
||||
return self._resolve_between(shape)
|
||||
resolved = _er.resolve(self.anchor(), shape, follow=self.follow, guard=self._guard_dict())
|
||||
if resolved.version_changed and self.guard is not None and resolved.status in ("ok", "merged"):
|
||||
# Made under other naming rules: the answer stands only if it still looks like what was picked.
|
||||
if any(entity._geom_type() != self.guard[0] for entity in resolved.entities):
|
||||
if any(_er._geom_type(entity) != self.guard[0] for entity in resolved.entities):
|
||||
return Resolution("lost", [], [], list(resolved.hops), None, "version_changed", self._lookalikes(shape), [], True)
|
||||
return resolved
|
||||
|
||||
def _resolve_in_pieces(self, pieces: list) -> Resolution:
|
||||
found: list = []
|
||||
bodies: list = []
|
||||
hops: list = []
|
||||
merged = changed = False
|
||||
missing: Optional[Resolution] = None
|
||||
for index, piece in enumerate(pieces):
|
||||
resolved = self.resolve(piece)
|
||||
changed = changed or resolved.version_changed
|
||||
if resolved.status == "lost":
|
||||
if missing is None or missing.reason == "other_output":
|
||||
missing = resolved
|
||||
continue
|
||||
merged = merged or resolved.status == "merged"
|
||||
hops = hops or list(resolved.hops)
|
||||
found.extend(resolved.entities)
|
||||
bodies.extend(index for _ in resolved.entities)
|
||||
if not found:
|
||||
if missing is None:
|
||||
return Resolution("lost", [], [], [], None, "no_pieces", [], [], changed)
|
||||
return dataclasses.replace(missing, reason="not_in_pieces" if missing.reason == "other_output" else missing.reason)
|
||||
if len(found) == 1:
|
||||
return Resolution("merged" if merged else "ok", found, [], hops, None, None, [], bodies, changed)
|
||||
candidates = _er._geometric_order([_er._candidate(e, str(getattr(e, "topo_id", ""))) for e in found])
|
||||
order = {id(c.entity): i for i, c in enumerate(candidates)}
|
||||
ranked = sorted(zip(found, bodies), key=lambda pair: order[id(pair[0])])
|
||||
return Resolution("split", [e for e, _ in ranked], [], hops, None, None, candidates, [b for _, b in ranked], changed)
|
||||
|
||||
def _resolve_between(self, shape: Any) -> Resolution:
|
||||
"""The edges of *shape* that lie between (a piece of) each of the two faces."""
|
||||
sides = []
|
||||
@@ -464,6 +501,34 @@ def vertex(
|
||||
piece=piece, guard=guard, digest=digest, naming=naming)
|
||||
|
||||
|
||||
def solid(
|
||||
feature: str,
|
||||
op: str,
|
||||
*,
|
||||
topo: str = "solid_0",
|
||||
occurrence: int = 0,
|
||||
slot: int = 0,
|
||||
piece: Optional[int] = None,
|
||||
guard: Optional[Guard] = None,
|
||||
digest: Optional[str] = None,
|
||||
naming: int = 1,
|
||||
) -> ElementRef:
|
||||
"""A reference to a solid (a body) born in *feature* by *op*.
|
||||
|
||||
A solid has no kernel role: it is named by its position in the output of the operation that made it (``slot``: a
|
||||
cut that splits a body outputs its pieces in order, by centre then size) and checked by its ``guard``
|
||||
(``("SOLID", centre, volume)``). Through later operations it is followed like a face: a fillet, a shell or a move
|
||||
continues it, a union merges it, a cut that splits it splits it (``piece`` then says which piece is meant). Resolve
|
||||
it in a solid, or in the pieces of a split body (a list of solids).
|
||||
|
||||
Examples:
|
||||
>>> left = scad.ref.solid("slot", "make_cut_rsolid_list", slot=0, guard=("SOLID", (-10.5, 0, 5), 1900))
|
||||
>>> left.one(pieces) # the solid of the pieces it names
|
||||
"""
|
||||
return _make("solid", feature, op, topo=topo, occurrence=occurrence, slot=slot, piece=piece, guard=guard,
|
||||
digest=digest, naming=naming)
|
||||
|
||||
|
||||
def of(entity: Any, shape: Any, *, follow: Follow = "identity", guard: bool = True) -> ElementRef:
|
||||
"""The stable reference of *entity*, a face, edge or vertex of *shape* (or of a shape *shape* descends from).
|
||||
|
||||
@@ -497,7 +562,7 @@ def _born(entity: Any, shape: Any, *, follow: str = "identity", fingerprint: Any
|
||||
anchor = _er.stable_anchor_of(entity, shape)
|
||||
kind = str(anchor["kind"]).lower()
|
||||
if kind not in _KINDS:
|
||||
raise ValueError(f"a reference names a face, an edge or a vertex, not a {kind}")
|
||||
raise ValueError(f"a reference names a face, an edge, a vertex or a solid, not a {kind}")
|
||||
shared = len(_cpp._native._stable_candidates(node, anchor)) > 1
|
||||
role = anchor.get("role") or None
|
||||
return ElementRef(
|
||||
@@ -599,7 +664,7 @@ def _selector(kind: str, refs: Sequence[ElementRef]) -> Any:
|
||||
wrong = [r for r in refs if r.kind != kind]
|
||||
if wrong:
|
||||
raise ValueError(f"{kind}s(...) takes {kind} references; {wrong[0].code()} is a {wrong[0].kind}")
|
||||
factory = {"face": _ql.faces, "edge": _ql.edges, "vertex": _ql.vertices}[kind]
|
||||
factory = {"face": _ql.faces, "edge": _ql.edges, "vertex": _ql.vertices, "solid": _ql.solids}[kind]
|
||||
predicates = [predicate(r) for r in refs]
|
||||
return factory().where(predicates[0] if len(predicates) == 1 else _ql.or_(*predicates))
|
||||
|
||||
@@ -633,10 +698,15 @@ def vertices(*refs: Union[ElementRef, Sequence[ElementRef]]) -> Any:
|
||||
return _selector("vertex", _flatten(refs))
|
||||
|
||||
|
||||
def solids(*refs: Union[ElementRef, Sequence[ElementRef]]) -> Any:
|
||||
"""The selection of the solids the references name (see :func:`faces`)."""
|
||||
return _selector("solid", _flatten(refs))
|
||||
|
||||
|
||||
# ---- reading the spelling back --------------------------------------------------------------------------------------
|
||||
|
||||
_FACTORIES = {"face": "face", "edge": "edge", "vertex": "vertex"}
|
||||
_SELECTIONS = {"faces": "face", "edges": "edge", "vertices": "vertex"}
|
||||
_FACTORIES = {"face": "face", "edge": "edge", "vertex": "vertex", "solid": "solid"}
|
||||
_SELECTIONS = {"faces": "face", "edges": "edge", "vertices": "vertex", "solids": "solid"}
|
||||
|
||||
|
||||
def _call_name(node: ast.expr) -> Optional[str]:
|
||||
@@ -701,7 +771,7 @@ def parse_selection(node: ast.expr) -> Tuple[str, list[ElementRef]]:
|
||||
|
||||
def selection_code(kind: str, refs: Sequence[ElementRef], prefix: str = "scad.ref") -> str:
|
||||
"""The code of a selection: one reference on one line, several one per line."""
|
||||
plural = {"face": "faces", "edge": "edges", "vertex": "vertices"}[kind]
|
||||
plural = {"face": "faces", "edge": "edges", "vertex": "vertices", "solid": "solids"}[kind]
|
||||
if len(refs) == 1:
|
||||
return f"{prefix}.{plural}({refs[0].code(prefix)})"
|
||||
inner = "".join(f"\n {r.code(prefix)}," for r in refs)
|
||||
@@ -711,8 +781,19 @@ def selection_code(kind: str, refs: Sequence[ElementRef], prefix: str = "scad.re
|
||||
# ---- the resolver ql.ref asks ---------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
IN_PIECES: contextvars.ContextVar[bool] = contextvars.ContextVar("scad_ref_in_pieces", default=False)
|
||||
"""Set while an operation runs on the pieces of a split body one piece at a time (``simplecadapi._glue.pieces``)."""
|
||||
|
||||
|
||||
def _resolve_record(scope: Any, record: Mapping[str, Any]) -> list:
|
||||
return ElementRef.from_dict(record).all(scope)
|
||||
reference = ElementRef.from_dict(record)
|
||||
if IN_PIECES.get():
|
||||
resolved = reference.resolve(scope)
|
||||
if resolved.status == "lost" and resolved.reason in ("other_output", "not_in_target"):
|
||||
# Alive in another piece of the split body this scope is one piece of: nothing of it here. The operation
|
||||
# over the pieces checks what the selection found on all of them together.
|
||||
return []
|
||||
return reference.all(scope)
|
||||
|
||||
|
||||
_ql._set_reference_resolver(_resolve_record)
|
||||
@@ -738,6 +819,8 @@ __all__ = [
|
||||
"predicate",
|
||||
"resolve",
|
||||
"selection_code",
|
||||
"solid",
|
||||
"solids",
|
||||
"vertex",
|
||||
"vertices",
|
||||
]
|
||||
|
||||
@@ -126,6 +126,8 @@ def _execute(args: argparse.Namespace) -> tuple[dict[str, Any], int]:
|
||||
"notebook": str(run.config.path),
|
||||
"cells": [
|
||||
{"name": cell.name, "key": cell.key, "status": cell.status}
|
||||
| ({"tag_splits": [{"tag": r["tag"], "into": r["into"], "op": r["op"]} for r in cell.tag_splits]}
|
||||
if cell.tag_splits else {})
|
||||
for cell in run.cells
|
||||
],
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
import warnings
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
@@ -34,6 +35,7 @@ from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from simplecadapi._glue.pieces import TagSplitWarning, split_message, tag_splits
|
||||
from simplecadapi._glue.session import GraphSession
|
||||
from ..recording.source_mapping import cell_sources
|
||||
from ._marimo import (
|
||||
@@ -351,10 +353,25 @@ def _cell_recording(
|
||||
_running.reset(token)
|
||||
# Reached only when the body succeeded; failures propagate untouched.
|
||||
_check_bound(session, cell, glbls)
|
||||
_warn_tag_splits(scope, cell, glbls)
|
||||
# The cell cache writes the nodes of the session beside the cell's entry.
|
||||
_sessions[cell.cell_id] = session
|
||||
|
||||
|
||||
def _warn_tag_splits(scope: NotebookScope, cell: CellImpl, glbls: MutableGlobals) -> None:
|
||||
"""Warn, in the cell's output and at the cell's place in the notebook, about the tagged entities its operations
|
||||
split (see TagSplitWarning)."""
|
||||
|
||||
key = scope.cells.key(cell.cell_id)
|
||||
rows = tag_splits((glbls[name] for name in cell.defs if name in glbls), key)
|
||||
if not rows:
|
||||
return
|
||||
placement = scope.cells.place(key)
|
||||
line = placement.line_offset + 1 if placement is not None else 1
|
||||
for row in rows:
|
||||
warnings.warn_explicit(TagSplitWarning(split_message(row)), TagSplitWarning, str(scope.config.path), line)
|
||||
|
||||
|
||||
def _check_bound(session: GraphSession, cell: CellImpl, glbls: MutableGlobals) -> None:
|
||||
held = {
|
||||
id(requirement)
|
||||
|
||||
@@ -224,6 +224,52 @@ def live_workplanes() -> list[dict[str, Any]]:
|
||||
return workplane_frames(values)
|
||||
|
||||
|
||||
def scene_tag_splits(scene: PreviewScene) -> list[dict[str, Any]]:
|
||||
"""The tag splits behind the solids of *scene*, with the entities of each piece (``scad.list_tag_splits``).
|
||||
|
||||
One row per split: ``tag``, ``into`` (the pieces' tags), ``op``, and ``pieces``: per entity that carries a piece's
|
||||
tag, ``piece`` (its index in ``into``), ``node_id`` (the scene node drawing it) and ``entity_id``. The editor
|
||||
highlights the pieces and says what was split, so whoever looks can judge whether the split was meant.
|
||||
"""
|
||||
|
||||
from .._cpp import list_tag_splits, ql
|
||||
|
||||
rows: dict[tuple, dict[str, Any]] = {}
|
||||
for key, solid in scene.solids.items():
|
||||
try:
|
||||
splits = list_tag_splits(solid)
|
||||
except Exception: # noqa: BLE001 - a diagnostic never breaks the preview
|
||||
continue
|
||||
if not splits:
|
||||
continue
|
||||
definition, body = scene.definitions[key], scene.bodies.get(key)
|
||||
prefix = f"entity/{definition}/" if body is None else f"entity/{definition}/body:{body}/"
|
||||
nodes = [node.node_id for node in scene.nodes if node.part_key == key]
|
||||
entities = [("solid", solid)] + [("face", f) for f in ql.faces().resolve(solid)] + [
|
||||
("edge", e) for e in ql.edges().resolve(solid)
|
||||
]
|
||||
tagged = [(kind, entity, set(entity._list_tags())) for kind, entity in entities]
|
||||
for split in splits:
|
||||
row = rows.setdefault(
|
||||
(split["node_id"], split["tag"], split["source_topo_id"]),
|
||||
{"tag": split["tag"], "into": list(split["into"]), "op": split["op"], "pieces": []},
|
||||
)
|
||||
for index, name in enumerate(split["into"]):
|
||||
for kind, entity, tags in tagged:
|
||||
if name in tags:
|
||||
for node_id in nodes:
|
||||
row["pieces"].append(
|
||||
{"piece": index, "node_id": node_id, "entity_id": f"{prefix}{kind}/{entity.topo_id}"}
|
||||
)
|
||||
return list(rows.values())
|
||||
|
||||
|
||||
def live_tag_splits() -> list[dict[str, Any]]:
|
||||
""":func:`scene_tag_splits` of the scene last previewed in this kernel (empty before the first preview)."""
|
||||
|
||||
return scene_tag_splits(_last_preview) if _last_preview is not None else []
|
||||
|
||||
|
||||
def preview_entity_info(entity_id: str) -> dict[str, Any] | None:
|
||||
"""The properties of one entity of the scene last previewed (see :func:`entity_info`)."""
|
||||
|
||||
@@ -251,7 +297,9 @@ def publish_live(url: str, *, step: str = "", timeout: float = 60.0) -> LivePack
|
||||
|
||||
|
||||
__all__ = [
|
||||
"live_tag_splits",
|
||||
"live_workplanes",
|
||||
"scene_tag_splits",
|
||||
"workplane_frames",
|
||||
"LivePackage",
|
||||
"LiveUnavailableError",
|
||||
|
||||
@@ -32,6 +32,7 @@ from dataclasses import dataclass, replace
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal, TypeVar
|
||||
|
||||
from simplecadapi._glue.pieces import tag_splits
|
||||
from ..artifacts.assembly_io import attached_definition
|
||||
from ..artifacts.canonical import validate_logical_id
|
||||
from ..build.definition import Definition
|
||||
@@ -90,6 +91,9 @@ class CellReport:
|
||||
key: str
|
||||
"""The cell's key: the namespace of its ids (see :mod:`.cells`)."""
|
||||
status: CellStatus
|
||||
tag_splits: tuple[dict, ...] = ()
|
||||
"""The tagged entities this cell's operations split (``scad.list_tag_splits`` rows): each piece carries
|
||||
``<tag>.split<i>`` and the tag names none of them. Reported whether the cell ran or was restored."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -342,6 +346,9 @@ def _run(
|
||||
if cell.cell_id in restored
|
||||
else "ran" if cell.cell_id in progress.ran else "skipped"
|
||||
),
|
||||
tag_splits=tuple(
|
||||
tag_splits((values[name] for name in cell.defs if name in values), cells.key(cell.cell_id))
|
||||
),
|
||||
)
|
||||
for cell in ordered
|
||||
)
|
||||
|
||||
@@ -61,7 +61,7 @@ class Candidate:
|
||||
kind: str
|
||||
geom_type: str
|
||||
center: tuple
|
||||
size: float # area of a face, length of an edge
|
||||
size: float # area of a face, length of an edge, volume of a solid
|
||||
score: float = 0.0 # lost only: distance to the guard, smaller is closer
|
||||
|
||||
def describe(self) -> Dict[str, Any]:
|
||||
@@ -165,16 +165,22 @@ 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())
|
||||
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()
|
||||
|
||||
|
||||
def guard_of(entity: Any) -> Dict[str, Any]:
|
||||
"""A geometric fingerprint of *entity*: checks a resolution and ranks candidates for a lost one, never more."""
|
||||
|
||||
c = entity.get_center()
|
||||
guard: Dict[str, Any] = {
|
||||
"kind": type(entity).__name__.lower(),
|
||||
"geom_type": entity._geom_type(),
|
||||
"geom_type": _geom_type(entity),
|
||||
"center": [c.x, c.y, c.z],
|
||||
"size": _size(entity),
|
||||
}
|
||||
@@ -190,7 +196,7 @@ def _candidate(entity: Any, topo_id: str, score: float = 0.0) -> Candidate:
|
||||
entity=entity,
|
||||
topo_id=topo_id,
|
||||
kind=type(entity).__name__.lower(),
|
||||
geom_type=entity._geom_type(),
|
||||
geom_type=_geom_type(entity),
|
||||
center=(c.x, c.y, c.z),
|
||||
size=_size(entity),
|
||||
score=score,
|
||||
@@ -205,7 +211,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}.get(kind)
|
||||
factory = {"face": ql.faces, "edge": ql.edges, "solid": ql.solids}.get(kind)
|
||||
if factory is None:
|
||||
return []
|
||||
out: List[Candidate] = []
|
||||
@@ -215,7 +221,7 @@ def _ranked_lookalikes(shape: Any, guard: Dict[str, Any], kind: str, limit: int
|
||||
distance = math.dist((c.x, c.y, c.z), guard["center"])
|
||||
size = _size(entity)
|
||||
score = distance + abs(size - guard["size"]) / max(guard["size"], 1e-9)
|
||||
if entity._geom_type() != guard.get("geom_type"):
|
||||
if _geom_type(entity) != guard.get("geom_type"):
|
||||
score += 1000.0
|
||||
if "normal" in guard and hasattr(entity, "get_normal_at"):
|
||||
n = entity.get_normal_at()
|
||||
@@ -243,6 +249,11 @@ def _bodies_of(shape: Any, entities: List[Any]) -> List[Optional[int]]:
|
||||
kind = type(entity).__name__
|
||||
found = None
|
||||
for index, solid in enumerate(solids):
|
||||
if kind == "Solid":
|
||||
if solid == entity:
|
||||
found = index
|
||||
break
|
||||
continue
|
||||
members = ql.faces().resolve(solid) if kind == "Face" else ql.edges().resolve(solid)
|
||||
if any(member == entity for member in members):
|
||||
found = index
|
||||
|
||||
@@ -465,10 +465,11 @@ def test_an_n_ary_cut_composes_its_steps():
|
||||
r = er.resolve(anchor, cut)
|
||||
assert r.status == "split"
|
||||
assert sorted(round(f.get_area(), 2) for f in r.entities) == [80.0, round(640 - 13 * math.pi, 2)]
|
||||
assert sorted(round(f.get_area(), 2) for f in ql.faces().where(ql.tag("user.top")).resolve(cut)) == [
|
||||
80.0,
|
||||
round(640 - 13 * math.pi, 2),
|
||||
]
|
||||
# the tag follows its face as the reference does: split, it names the pieces <tag>.split1, .split2
|
||||
assert ql.faces().where(ql.tag("user.top")).resolve(cut) == []
|
||||
pieces = {name: ql.faces().where(ql.tag(name)).exactly(1).resolve(cut)[0] for name in ("user.top.split1", "user.top.split2")}
|
||||
assert sorted(round(f.get_area(), 2) for f in pieces.values()) == [80.0, round(640 - 13 * math.pi, 2)]
|
||||
assert [c.center for c in r.candidates] == [tuple(f.get_center()) for f in (pieces["user.top.split1"], pieces["user.top.split2"])]
|
||||
|
||||
|
||||
def test_a_tag_survives_pickling_with_its_history():
|
||||
|
||||
@@ -82,7 +82,8 @@ def test_a_reference_reads_as_code_and_parses_back():
|
||||
("scad.ref.edge('base', 'make_box_rsolid', role='x', piece=-1)", "piece"),
|
||||
("scad.ref.face('base', 'make_box_rsolid', role=__import__('os').name)", "literal values only"),
|
||||
("scad.ref.face('base', 'make_box_rsolid', role='box.top', guard=('PLANE', (0, 0), 1))", "guard"),
|
||||
("scad.ref.solid('base', 'make_box_rsolid', role='box')", "not a reference"),
|
||||
("scad.ref.solid('base', 'make_box_rsolid', role='box')", "a solid has no kernel role"),
|
||||
("scad.ref.shell('base', 'make_box_rsolid', topo='shell_0')", "not a reference"),
|
||||
],
|
||||
)
|
||||
def test_a_malformed_reference_is_refused(text, message):
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
"""A tag follows its entity as a reference does: a split names the pieces <tag>.split<i>; solids have history and refs.
|
||||
|
||||
The pieces of a split are numbered when the operation is recorded (by centre, then size), the order a split reference
|
||||
lists its candidates in; the split is reported (list_tag_splits, the cell's TagSplitWarning, the run report).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
import simplecadapi as scad
|
||||
from simplecadapi.runtime import run_notebook
|
||||
from test_notebook_runtime import NotebookTestCase, cell, notebook_text
|
||||
|
||||
ql = scad.ql
|
||||
|
||||
|
||||
def _tags(shape, prefix: str) -> list[str]:
|
||||
return sorted(t for f in ql.faces().resolve(shape) for t in f._list_tags() if t.startswith(prefix))
|
||||
|
||||
|
||||
def _top(box):
|
||||
return scad.apply_tag_rselection(box, ql.faces().where(ql.prop("geom.center.z", ">=", 9.9)).exactly(1), "mount.top")
|
||||
|
||||
|
||||
def test_a_split_tagged_face_names_its_pieces_and_the_tag_none_of_them():
|
||||
with scad.GraphSession():
|
||||
box = _top(scad.make_box_rsolid(40.0, 10.0, 10.0))
|
||||
grooved = scad.cut_rsolid(box, scad.make_box_rsolid(2.0, 20.0, 4.0, bottom_face_center=(0.0, 0.0, 8.0)))
|
||||
assert _tags(grooved, "mount") == ["mount.top.split1", "mount.top.split2"]
|
||||
assert ql.faces().where(ql.tag("mount.top")).resolve(grooved) == []
|
||||
assert len(ql.faces().where(ql.tag("mount.top.*")).resolve(grooved)) == 2
|
||||
left = ql.faces().where(ql.tag("mount.top.split1")).exactly(1).resolve(grooved)[0]
|
||||
assert left.get_center().x < 0 # piece 1 is the one with the smaller centre
|
||||
[row] = scad.list_tag_splits(grooved)
|
||||
assert (row["tag"], row["into"], row["op"]) == ("mount.top", ["mount.top.split1", "mount.top.split2"], "make_cut_rsolid")
|
||||
# a hole is no split: the face keeps its tag
|
||||
drilled = scad.cut_rsolid(box, scad.make_cylinder_rsolid(1.0, 30.0, (10.0, 0.0, -5.0)))
|
||||
assert _tags(drilled, "mount") == ["mount.top"] and scad.list_tag_splits(drilled) == []
|
||||
|
||||
|
||||
def test_the_pieces_follow_on_and_a_second_split_numbers_again():
|
||||
with scad.GraphSession():
|
||||
box = _top(scad.make_box_rsolid(40.0, 10.0, 10.0))
|
||||
halves = scad.cut_rsolid(box, scad.make_box_rsolid(2.0, 20.0, 20.0)) # splits the body, and the top face
|
||||
moved = scad.translate_shape(halves, (0.0, 0.0, 1.0))
|
||||
assert [_tags(piece, "mount") for piece in moved] == [["mount.top.split1"], ["mount.top.split2"]]
|
||||
quarter = scad.cut_rsolid(moved[1], scad.make_box_rsolid(2.0, 20.0, 20.0, bottom_face_center=(10.0, 0.0, -5.0)))
|
||||
assert sorted(_tags(piece, "mount") for piece in quarter) == [["mount.top.split2.split1"], ["mount.top.split2.split2"]]
|
||||
|
||||
|
||||
def test_a_solid_is_continued_by_one_solid_operations_merged_by_a_union_and_split_by_a_cut():
|
||||
with scad.GraphSession():
|
||||
box = scad.apply_tag_rselection(scad.make_box_rsolid(40.0, 10.0, 10.0), ql.solids().exactly(1), "part.base")
|
||||
rounded = scad.fillet_rsolid(box, ql.edges().where(ql.prop("geom.center.z", ">=", 9.9)), 1.0)
|
||||
moved = scad.translate_shape(rounded, (1.0, 0.0, 0.0))
|
||||
assert "part.base" in moved._list_tags()
|
||||
joined = scad.union_rsolid(moved, scad.make_cylinder_rsolid(2.0, 20.0)) # another op: no second box to confuse it with
|
||||
reference = scad.ref.of(rounded, rounded)
|
||||
assert reference.kind == "solid" and reference.resolve(joined).status in ("ok", "merged")
|
||||
pieces = scad.cut_rsolid(moved, scad.make_box_rsolid(2.0, 20.0, 20.0, bottom_face_center=(1.0, 0.0, -5.0)))
|
||||
assert [sorted(t for t in p._list_tags() if t.startswith("part")) for p in pieces] == [["part.base.split1"], ["part.base.split2"]]
|
||||
resolved = reference.resolve(pieces)
|
||||
assert resolved.status == "split" and resolved.bodies == [0, 1]
|
||||
|
||||
|
||||
def test_a_solid_reference_names_one_piece_through_later_operations():
|
||||
with scad.GraphSession():
|
||||
box = scad.make_box_rsolid(40.0, 10.0, 10.0)
|
||||
# made before the cut's tool box exists: two make_box_rsolid nodes later, and the history tells them apart
|
||||
early = scad.ref.of(box, box)
|
||||
pieces = scad.cut_rsolid(box, scad.make_box_rsolid(2.0, 20.0, 20.0))
|
||||
assert early.resolve(pieces).status == "split"
|
||||
right = scad.ref.of(pieces[1], pieces[1])
|
||||
assert right.kind == "solid" and right.slot == 1 and scad.ref.parse(repr(right)) == right
|
||||
moved = scad.translate_shape(pieces, (0.0, 0.0, 3.0))
|
||||
assert right.one(moved).get_center().x > 0
|
||||
assert right.resolve(moved[0]).status == "lost"
|
||||
with pytest.raises(ValueError, match="a solid has no kernel role"):
|
||||
scad.ref.parse("scad.ref.solid('base', 'make_box_rsolid', role='box')")
|
||||
|
||||
|
||||
def test_a_reference_selection_works_over_the_pieces_and_refuses_one_that_finds_nothing():
|
||||
with scad.GraphSession():
|
||||
box = scad.make_box_rsolid(40.0, 10.0, 10.0)
|
||||
pieces = scad.cut_rsolid(box, scad.make_box_rsolid(2.0, 20.0, 20.0))
|
||||
moved = scad.translate_shape(pieces, (0.0, 0.0, 3.0))
|
||||
rim = ql.edges().where(ql.prop("geom.center.x", ">=", 15)).where(ql.prop("geom.center.z", ">=", 9)).resolve(pieces[1])[0]
|
||||
edge = scad.ref.of(rim, pieces[1])
|
||||
rounded = scad.fillet_rsolid(moved, scad.ref.edges(edge), 0.3)
|
||||
assert rounded[0].get_volume() == pytest.approx(moved[0].get_volume())
|
||||
assert rounded[1].get_volume() < moved[1].get_volume()
|
||||
top = scad.ref.of(ql.faces().where(ql.prop("geom.center.z", ">=", 12)).resolve(moved[0])[0], moved[0])
|
||||
shelled = scad.shell_rsolid(moved, scad.ref.faces(top), 0.5)
|
||||
assert shelled[0].get_volume() < moved[0].get_volume()
|
||||
assert shelled[1].get_volume() == pytest.approx(moved[1].get_volume())
|
||||
with pytest.raises(scad.ref.ElementRefError):
|
||||
scad.fillet_rsolid(moved[0], scad.ref.edges(edge), 0.3) # one piece, the edge is on the other
|
||||
|
||||
|
||||
SPLIT = notebook_text(
|
||||
cell(
|
||||
"box = scad.apply_tag_rselection(scad.make_box_rsolid(40.0, 10.0, 10.0),"
|
||||
" scad.ql.faces().where(scad.ql.prop('geom.center.z', '>=', 9.9)).exactly(1), 'mount.top')",
|
||||
returns="box",
|
||||
),
|
||||
cell(
|
||||
"grooved = scad.cut_rsolid(box, scad.make_box_rsolid(2.0, 20.0, 4.0, bottom_face_center=(0.0, 0.0, 8.0)))",
|
||||
reads="box",
|
||||
returns="grooved",
|
||||
),
|
||||
cell("part = scad.make_part_rpart(part_id='grooved', body=grooved)", reads="grooved", returns="part"),
|
||||
table='id = "grooved"',
|
||||
)
|
||||
|
||||
|
||||
class TestTheRunReportsTheSplit(NotebookTestCase):
|
||||
def test_a_split_is_reported_by_the_cell_that_made_it_ran_or_restored(self) -> None:
|
||||
nb = self.write("grooved.py", SPLIT)
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
first = run_notebook(nb)
|
||||
assert any(issubclass(w.category, scad.TagSplitWarning) and "mount.top.split1" in str(w.message) for w in caught)
|
||||
second = run_notebook(nb)
|
||||
for run in (first, second):
|
||||
splits = {report.key.split(".")[0]: report.tag_splits for report in run.cells if report.tag_splits}
|
||||
assert len(splits) == 1
|
||||
[rows] = splits.values()
|
||||
assert [row["into"] for row in rows] == [["mount.top.split1", "mount.top.split2"]]
|
||||
assert self.statuses(second)[2] == "cached"
|
||||
report = subprocess.run(
|
||||
[sys.executable, "-m", "simplecadapi.cli", "run", str(nb)], capture_output=True, text=True, check=True
|
||||
)
|
||||
cells = json.loads(report.stdout.strip().splitlines()[-1])["cells"]
|
||||
assert [c["tag_splits"] for c in cells if "tag_splits" in c] == [
|
||||
[{"tag": "mount.top", "into": ["mount.top.split1", "mount.top.split2"], "op": "make_cut_rsolid"}]
|
||||
]
|
||||
|
||||
|
||||
def test_the_preview_scene_lists_the_entities_of_each_piece():
|
||||
from simplecadapi.runtime.live import scene_tag_splits
|
||||
from simplecadapi.scene.preview import compile_preview
|
||||
|
||||
with scad.GraphSession():
|
||||
box = _top(scad.make_box_rsolid(40.0, 10.0, 10.0))
|
||||
grooved = scad.cut_rsolid(box, scad.make_box_rsolid(2.0, 20.0, 4.0, bottom_face_center=(0.0, 0.0, 8.0)))
|
||||
part = scad.make_part_rpart(part_id="grooved", body=grooved)
|
||||
[row] = scene_tag_splits(compile_preview(part))
|
||||
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"])
|
||||
Reference in New Issue
Block a user