editor: a colour slot for display colours; naming a face is the tag op with picked faces

op_specs offer a 'color' slot for Color parameters (set_body_appearance_rpart,
make_material_rmaterial) and an opacity slider in [0, 1]. apply_tag_rselection
returns AnyShape in its signature (it was the one untyped result in the
catalog) and its targets are faces picked in the viewport, so 'name this face'
is the existing tag operation. Fix: the generic op builder dropped every picked
selection (op.fillet_rsolid wrote no edges); a test now checks every op with a
selection passes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NiJingzhe
2026-11-04 11:19:17 +08:00
parent 4ff66173c5
commit c18d6b9038
5 changed files with 66 additions and 5 deletions
+7 -2
View File
@@ -621,6 +621,11 @@ struct TagTargetsName {
"simplecadapi._cpp._native.ShapeSelector | collections.abc.Sequence[simplecadapi._cpp._native.AnyShape]");
};
// The result of apply_tag_rselection: the scope's shape, as the class it is.
struct TaggedShapeName {
static constexpr auto name = py::detail::const_name("simplecadapi._cpp._native.AnyShape");
};
// The str enums by their values (members of the Python enums are str too).
struct TopologyPropagationName {
static constexpr auto name = py::detail::const_name("typing.Literal['local', 'downward']");
@@ -661,8 +666,8 @@ void bind_operators(py::module_& m) {
{"Pass a valid scope and a non-empty ShapeSelector or shape sequence.",
"Use a normalized tag string such as 'role.mounting_surface' or 'group.fasteners'.",
"Ensure every explicit target belongs to the assignment scope."}};
return shape_to_py(guarded(
spec, [&] { return apply_tag_rselection(scope, targets_from_py(targets), tag, topology, lineage); }));
return scad::pybind::AnyOf<TaggedShapeName>{shape_to_py(guarded(
spec, [&] { return apply_tag_rselection(scope, targets_from_py(targets), tag, topology, lineage); }))};
},
py::arg("scope"), py::arg("targets"), py::arg("tag"),
py::arg("topology_propagation") = TopologyPropagation::Local,
+5 -1
View File
@@ -63,7 +63,7 @@ class Slot:
kind: ``length`` (mm), ``angle`` (deg), ``float``, ``count``, ``bool``, ``enum``, ``point`` (three lengths),
``body`` (a solid made earlier), ``profile`` (a sketch face made earlier), ``select`` (faces or edges picked in the
viewport), ``points2d`` (``x, y`` per line), ``sketch`` (a sketch document, see :mod:`.sketch_doc`), ``assembly`` (an
assembly document, see :mod:`.assembly_doc`).
assembly document, see :mod:`.assembly_doc`), ``color`` (a display colour, RGB in [0, 1]).
"""
name: str
@@ -877,6 +877,10 @@ def check_values(spec: Spec, values: Mapping[str, Any], bodies: Mapping[str, str
points.append([_checked_number(Slot(slot.name, slot.label, "float"), v) for v in point])
grid.append(points)
clean[slot.name] = grid
elif slot.kind == "color":
if not (isinstance(raw, (list, tuple)) and len(raw) == 3):
raise FeatureError(f"{slot.label}: three numbers (red, green, blue) between 0 and 1")
clean[slot.name] = [_checked_number(Slot(slot.name, slot.label, "float", min=0.0, max=1.0), part) for part in raw]
elif slot.kind == "text":
if not isinstance(raw, str):
raise FeatureError(f"{slot.label}: text is required")
+11 -1
View File
@@ -96,6 +96,8 @@ def _slot(param: C.Param, features: Any) -> Any | None:
default = None if optional and not param.has_default else _default_number(param)
if param.has_default and param.default is None:
default = None
if param.name == "opacity": # a fraction: 0 (clear) to 1 (opaque)
return Slot(param.name, label, slot_kind, default=default, min=0.0, max=1.0, step=0.05, optional=optional)
return Slot(param.name, label, slot_kind, default=default, unit=unit, min=minimum, optional=optional)
if kind in _VECTOR_KINDS and not param.many:
default = list(param.default) if isinstance(param.default, (list, tuple)) and len(param.default) == 3 else ([0.0, 0.0, 1.0] if kind == "direction3" else [0.0, 0.0, 0.0])
@@ -117,6 +119,12 @@ def _slot(param: C.Param, features: Any) -> Any | None:
if optional:
return None if param.name != "name" else Slot(param.name, label, "text", default=None, optional=True)
return Slot(param.name, label, "text", default=str(param.default) if param.has_default else "")
if kind == "color": # a display colour: RGB in [0, 1]
default = [float(v) for v in param.default] if isinstance(param.default, (list, tuple)) and len(param.default) == 3 else None
return Slot(param.name, label, "color", default=default, optional=optional)
if kind == "shape" and param.many and "ShapeSelector" in param.type:
# shapes of the scope, or a ql selection of them (apply_tag_rselection's targets): faces picked in the viewport
return Slot(param.name, label, "select", entity="face")
if kind == "query" or (kind in ("edge", "face") and param.many and param.name in ("edges", "faces", "faces_to_remove")):
entity = "edge" if "edge" in param.name or kind == "edge" else "face"
return Slot(param.name, label, "select", entity=entity)
@@ -178,7 +186,7 @@ def _builder(op: C.Operation):
if slot.name in ("operation", "target"):
continue
value = c.values.get(slot.name)
if value is None:
if value is None and slot.kind != "select": # a selection is picked, not a value (its recipe is in c)
continue
if slot.kind in ("length", "angle", "float", "count"):
expr = c.var(slot.name)
@@ -188,6 +196,8 @@ def _builder(op: C.Operation):
expr = "[" + ", ".join("(" + ", ".join(repr(float(v)) for v in row) + ")" for row in value) + "]"
elif slot.kind == "grid":
expr = "[" + ", ".join("[" + ", ".join("(" + ", ".join(repr(float(v)) for v in p) + ")" for p in row) + "]" for row in value) + "]"
elif slot.kind == "color":
expr = "(" + ", ".join(repr(round(float(v), 4)) for v in value) + ")"
elif slot.kind in ("bool", "enum", "text"):
expr = json.dumps(value) if slot.kind != "bool" else repr(bool(value))
elif slot.kind == "select":
+1 -1
View File
@@ -59,7 +59,7 @@ def test_the_catalog_lists_every_operation_with_typed_slots():
assert len(ids) == len(set(ids)) >= 24
for spec in data["specs"]:
assert spec["slots"], spec["id"]
assert {slot["kind"] for slot in spec["slots"]} <= {"length", "angle", "float", "count", "bool", "enum", "point", "body", "select", "points2d", "points3d", "profile", "sketch", "assembly", "value", "text", "grid"} # value, text, grid: forms made from the SDK catalog
assert {slot["kind"] for slot in spec["slots"]} <= {"length", "angle", "float", "count", "bool", "enum", "point", "body", "select", "points2d", "points3d", "profile", "sketch", "assembly", "value", "text", "grid", "color"} # value, text, grid, color: forms made from the SDK catalog
@pytest.mark.parametrize("spec", F.SPECS, ids=lambda s: s.id)
+42
View File
@@ -69,3 +69,45 @@ def test_an_operation_made_from_defaults_runs(spec):
except (scad.errors.SimpleCADError, ValueError) as exc: # defaults that do not make a valid shape are the SDK's to refuse
pytest.skip(f"{spec.id}: the defaults are refused by the SDK: {str(exc).splitlines()[0]}")
assert scope["made"] is not None
def test_body_appearance_is_a_form_with_a_colour_slot_and_runs():
spec = next(s for s in SPECS if s.id == "op.set_body_appearance_rpart")
kinds = {slot.name: slot.kind for slot in spec.slots}
assert kinds == {"part": "value", "body_id": "text", "color": "color", "opacity": "float", "name": "text", "reset": "bool"}
opacity = next(slot for slot in spec.slots if slot.name == "opacity")
assert (opacity.min, opacity.max) == (0.0, 1.0)
values = {"part": "plate", "body_id": "body", "color": [0.9, 0.2, 0.1], "opacity": 0.5, "name": "Plate", "reset": False}
rendered = F.render_feature(spec.id, "painted", values, bodies={"plate": "part"})
assert "color=(0.9, 0.2, 0.1)" in rendered.feature
scope: dict = {"scad": scad, "plate": scad.make_part_rpart("plate", body=scad.make_box_rsolid(4, 4, 4))}
exec("\n".join(rendered.params), scope) # noqa: S102 - code under test is ours
exec(rendered.feature, scope) # noqa: S102
body = scope["painted"].bodies[0]
assert (body.color, body.opacity, body.name) == ((0.9, 0.2, 0.1), 0.5, "Plate")
with pytest.raises(F.FeatureError):
F.render_feature(spec.id, "painted", {**values, "color": [2, 0, 0]}, bodies={"plate": "part"})
def test_naming_a_face_is_the_tag_operation_with_picked_faces():
spec = next(s for s in SPECS if s.id == "op.apply_tag_rselection")
targets = next(slot for slot in spec.slots if slot.name == "targets")
assert (targets.kind, targets.entity) == ("select", "face")
assert spec.produces == "shape"
pick = [{"kind": "face", "properties": {"centroid": [0.0, 0.0, 4.0], "area": 16.0}, "geometry": {"type": "plane", "normal": [0, 0, 1]}}]
rendered = F.render_feature(spec.id, "named", {"scope": "block", "tag": "lid_seat", "topology_propagation": "local",
"lineage_policy": "continuation_fragment"},
bodies={"block": "solid"}, selections={"targets": pick}, known_slugs={"block"})
scope: dict = {"scad": scad, "block": scad.make_box_rsolid(4, 4, 4)}
exec(rendered.feature.replace("{BODY}", "block"), scope) # noqa: S102
top = scad.select_faces_by_tag(scope["named"], "lid_seat")
assert len(top) == 1
@pytest.mark.parametrize("spec", [s for s in SPECS if any(slot.kind == "select" for slot in s.slots)], ids=lambda s: s.id)
def test_a_picked_selection_is_passed_to_the_operation(spec):
picks = {slot.name: [{"kind": slot.entity, "properties": {"centroid": [0, 0, 0], "area": 10.0, "length": 5.0}, "geometry": {"type": "plane"}}]
for slot in spec.slots if slot.kind == "select"}
rendered = F.render_feature(spec.id, "probe", _values(spec), bodies=_BODIES, selections=picks, known_slugs=set(_BODIES))
call = next(n for n in ast.walk(ast.parse(rendered.feature)) if isinstance(n, ast.Call) and ast.unparse(n.func).endswith(spec.operation))
assert set(picks) <= {k.arg for k in call.keywords}, rendered.feature