runtime + preview: several open solids are shown side by side, but are no longer a Part
DECISION: the editor's need (several solids existing in one notebook with no assembly constraint) is met
in the notebook / preview layer, not by the Part. A `kind = "part"` notebook that ends with exactly one open
solid still gets the implicit one-body Part; with several open solids no product is chosen for the author.
WHY - THE DISCUSSION (owner and assistant, 2026-11-10; full account in design-docs/part-holds-one-solid.md)
The owner's need: the editor must support several solids in one notebook with no assembly constraint, e.g.
pattern a tool and then cut - for a moment there are more than one tool and the body. The multi-body Part
was invented to hold them and was judged wrong because it makes assembly hard. The agreed analysis: those
solids are intermediate values of a notebook, not product items, so the editor's real need is to SHOW every
open solid. This commit is that replacement: it keeps what the editor needed and removes it from the Part.
WHAT CHANGES
- runtime/projection.py
- the implicit Part of a part notebook is made from its one open body. Several open solids (a variable
per solid, the pieces of a split cut counted as solids) raise the new SeveralOpenBodiesError, a
ProductNotFoundError that names the solids and says what to do: make the Part from the solid that is
the part, or make a Part of each and an Assembly of them. `sca run`, export and every caller that needs
a product therefore stop with an actionable message instead of silently choosing or fusing.
- OpenBodies (part_id + solids by name) and loose_solids() are the value a preview draws in that case.
- project_product rebuilds the implicit Part with make_part_rpart(body=...) (it used the multi-body rule).
- runtime/live.py: preview_product catches SeveralOpenBodiesError and returns OpenBodies, so the live
preview of an unfinished notebook (a tool next to its target) keeps working, including when a later cell
failed (the partial-model report names the shown solids as before).
- scene/preview.py
- compile_open_bodies(part_id, solids): one node per solid, `node/<notebook id>/body:<name>`, entity
namespace `entity/<notebook id>/body:<name>/...` (two solids of the same shape stay two). This is the
same wire shape the multi-body preview produced, deliberately: editor-web, element references
(live_refs) and entity_info need no change.
- compile_preview draws a Part as one node; its multi-body branch is removed.
WHY NOT choose one open solid automatically (e.g. the last): the tip is a guess, and exporting a Part that
silently left a solid out is worse than an error; the author knows which solid is the part.
Checked by running: one open body -> Part; two open bodies -> SeveralOpenBodiesError with the guidance;
compile_open_bodies header / entity_info for two same-shape solids; a one-body Part previews as before.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -29,12 +29,31 @@ from typing import Any
|
||||
from ..artifacts.assembly_io import attached_definition
|
||||
from ..product.packages import build_product_package, encode_product_package
|
||||
from .._cpp import Face, Shell
|
||||
from ..scene.preview import PreviewScene, add_surfaces, compile_preview, encode_preview, entity_info, refine_preview
|
||||
from ..scene.preview import (
|
||||
PreviewScene,
|
||||
add_surfaces,
|
||||
compile_open_bodies,
|
||||
compile_preview,
|
||||
encode_preview,
|
||||
entity_info,
|
||||
refine_preview,
|
||||
)
|
||||
from ._marimo import safe_get_context
|
||||
from .cells import NotebookCells
|
||||
from .config import NotebookConfig, read_notebook_config
|
||||
from .executor import finish_kernel_cache
|
||||
from .projection import NoProductYetError, Product, ProductNotFoundError, find_product, open_bodies, product_reads, project_product
|
||||
from .projection import (
|
||||
NoProductYetError,
|
||||
OpenBodies,
|
||||
Product,
|
||||
ProductNotFoundError,
|
||||
SeveralOpenBodiesError,
|
||||
find_product,
|
||||
loose_solids,
|
||||
open_bodies,
|
||||
product_reads,
|
||||
project_product,
|
||||
)
|
||||
from .workspace import features_in_cell
|
||||
|
||||
PACKAGE_MEDIA_TYPE = "application/vnd.simplecad.scadpkg"
|
||||
@@ -221,7 +240,7 @@ def preview_product(
|
||||
failed: Iterable[FailedCell] = (),
|
||||
skipped: Iterable[str] = (),
|
||||
lost_reads: AbstractSet[str] = frozenset(),
|
||||
) -> tuple[Product, dict[str, Any] | None]:
|
||||
) -> tuple[Product | OpenBodies, dict[str, Any] | None]:
|
||||
"""The product to preview from *values* (the cells that are left, see :class:`LiveScope`), and whether it is partial.
|
||||
|
||||
With no failed cell this is :func:`~.projection.find_product`. With one, the product is found the same way among the
|
||||
@@ -230,6 +249,9 @@ def preview_product(
|
||||
failing step. The second item says what is shown (``None`` when the product is whole): ``{"failed": [...], "skipped":
|
||||
[cell ids], "shown": [names]}``. A product no failed cell would have built on (an explicit product upstream of none of
|
||||
them) is whole. Raises :class:`~.projection.ProductNotFoundError` when nothing is left to show, naming the failed cell.
|
||||
|
||||
A part notebook that ends with several open solids and no cell making the Part of one of them has no product yet (a
|
||||
Part holds exactly one solid): what is shown is :class:`~.projection.OpenBodies`, the solids side by side.
|
||||
"""
|
||||
|
||||
failed = tuple(failed)
|
||||
@@ -237,6 +259,9 @@ def preview_product(
|
||||
read = product_reads(cells, values)
|
||||
try:
|
||||
product = find_product(config, values, read)
|
||||
except SeveralOpenBodiesError as error:
|
||||
# the model is the solids themselves: a tool and its target, shown before a cell makes the Part of one of them
|
||||
product = OpenBodies(config.id, loose_solids(values, error.names))
|
||||
except ProductNotFoundError as error:
|
||||
if not failed:
|
||||
raise
|
||||
@@ -284,7 +309,12 @@ def _live_scene() -> PreviewScene:
|
||||
except NoProductYetError:
|
||||
# no solid yet (only sketches, curves, workplanes): the model is empty, which is no fault
|
||||
product, partial = None, None
|
||||
scene = compile_preview(product) if product is not None else PreviewScene(parts={}, nodes=[], solids={}, definitions={})
|
||||
if product is None:
|
||||
scene = PreviewScene(parts={}, nodes=[], solids={}, definitions={})
|
||||
elif isinstance(product, OpenBodies):
|
||||
scene = compile_open_bodies(product.part_id, product.bodies)
|
||||
else:
|
||||
scene = compile_preview(product)
|
||||
# the surfaces no later cell builds on (a loft, a patch, a shell sewn so far) are shown with the model
|
||||
add_surfaces(scene, open_surfaces(scope.values, product_reads(scope.cells, scope.values)))
|
||||
last_timings["compile_ms"] = round((time.perf_counter() - started) * 1000, 1)
|
||||
|
||||
@@ -26,6 +26,7 @@ also cache the notebook's values must flush the cache first.
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable, Mapping, Set as AbstractSet
|
||||
from dataclasses import dataclass
|
||||
|
||||
from ..artifacts.assembly_io import attached_definition
|
||||
from ..build.assembly_builder import declared_definitions
|
||||
@@ -39,9 +40,18 @@ from ..build.results import AssemblyBuildResult, PartBuildResult
|
||||
import weakref
|
||||
from typing import Any
|
||||
|
||||
from simplecadapi._cpp import Assembly, Edge, find_registered_node, isolated_recording, Part, SimpleWorkplane, Solid, Wire
|
||||
from simplecadapi._cpp import (
|
||||
Assembly,
|
||||
Edge,
|
||||
find_registered_node,
|
||||
isolated_recording,
|
||||
make_part_rpart,
|
||||
Part,
|
||||
SimpleWorkplane,
|
||||
Solid,
|
||||
Wire,
|
||||
)
|
||||
from simplecadapi._glue.session import lineage_of
|
||||
from ..product.bodies import part_from_bodies
|
||||
from simplecadapi._glue.session import GraphSession
|
||||
from ..recording.source_mapping import cell_sources
|
||||
from .cells import NotebookCells, bound_requirements
|
||||
@@ -54,6 +64,29 @@ class ProductNotFoundError(ValueError):
|
||||
"""No top-level value, or more than one, is the notebook's product."""
|
||||
|
||||
|
||||
class SeveralOpenBodiesError(ProductNotFoundError):
|
||||
"""A ``kind = "part"`` notebook ends with several solids nothing is built from, and no cell makes the Part.
|
||||
|
||||
A Part holds exactly one solid, so the runtime cannot choose for the author which of them is the part. ``names`` are
|
||||
the variables of the open solids, in cell order; a preview shows them side by side (:class:`OpenBodies`).
|
||||
"""
|
||||
|
||||
def __init__(self, message: str, names: tuple[str, ...]) -> None:
|
||||
super().__init__(message)
|
||||
self.names = names
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OpenBodies:
|
||||
"""The solids a notebook has made and not yet used, shown side by side: what a preview draws while no cell makes a
|
||||
Part of one of them (a tool next to the body it will cut). They are loose values, not a product: nothing places,
|
||||
mates or exports them."""
|
||||
|
||||
part_id: str
|
||||
bodies: Mapping[str, Solid]
|
||||
"""Solid by name: the variable, or ``<variable>_<n>`` for the n-th piece of a split cut."""
|
||||
|
||||
|
||||
class NoProductYetError(ProductNotFoundError):
|
||||
"""The notebook makes no Part, no Assembly and no solid yet (a new notebook, or one with only sketches, curves and
|
||||
workplanes so far). There is no product to export, but nothing is wrong: a preview of it is empty."""
|
||||
@@ -129,7 +162,7 @@ def find_product(
|
||||
f"{', '.join(names)}"
|
||||
)
|
||||
if config.kind == "part" and not others:
|
||||
implicit = _implicit_part(config, values, read)
|
||||
implicit = _implicit_part(config, values, read) # SeveralOpenBodiesError when it cannot choose
|
||||
if implicit is not None:
|
||||
return implicit
|
||||
if not others:
|
||||
@@ -189,17 +222,45 @@ def _ancestors(node: Any) -> set[str]:
|
||||
return out
|
||||
|
||||
|
||||
def _implicit_part(config: NotebookConfig, values: Mapping[str, object], read: AbstractSet[str]) -> Part | None:
|
||||
"""The product of a ``kind = "part"`` notebook without a cell that builds it: its open bodies, as a Part with the notebook id.
|
||||
def loose_solids(values: Mapping[str, object], names: Iterable[str]) -> dict[str, Solid]:
|
||||
"""The solids behind *names* (variables of open bodies): a Solid by its name, the pieces of a split cut as
|
||||
``<name>_1 .. <name>_n``."""
|
||||
|
||||
One open body is a one-body Part (body id ``"body"``); several are the bodies of one Part, named by their variables
|
||||
(the pieces of a split cut ``<name>_1..n``). ``None`` when there is no body yet.
|
||||
out: dict[str, Solid] = {}
|
||||
for name in names:
|
||||
value = values[name]
|
||||
if isinstance(value, Solid):
|
||||
out[name] = value
|
||||
elif len(value) == 1: # type: ignore[arg-type]
|
||||
out[name] = value[0] # type: ignore[index]
|
||||
else:
|
||||
for index, piece in enumerate(value, start=1): # type: ignore[arg-type]
|
||||
out[f"{name}_{index}"] = piece
|
||||
return out
|
||||
|
||||
|
||||
def _implicit_part(config: NotebookConfig, values: Mapping[str, object], read: AbstractSet[str]) -> Part | None:
|
||||
"""The product of a ``kind = "part"`` notebook without a cell that builds it: its one open body, as a Part with the
|
||||
notebook id (body id ``"body"``). ``None`` when there is no body yet.
|
||||
|
||||
A Part holds exactly one solid. Several open solids are several things the notebook has not chosen between:
|
||||
:class:`SeveralOpenBodiesError` says which, and what to do.
|
||||
"""
|
||||
|
||||
names = open_bodies(values, read)
|
||||
if not names:
|
||||
return None
|
||||
part = part_from_bodies(config.id, {name: values[name] for name in names})
|
||||
solids = loose_solids(values, names)
|
||||
if len(solids) > 1:
|
||||
raise SeveralOpenBodiesError(
|
||||
f"{config.path.name}: {len(solids)} solids are open at the end of the notebook ({', '.join(solids)}) and no "
|
||||
"cell makes the Part from one of them. A Part holds exactly one solid: make it from the solid that is the "
|
||||
"part (scad.make_part_rpart(part_id=scad.notebook_id(), body=...)); if they are separate parts, make a Part "
|
||||
"of each and an Assembly of them",
|
||||
tuple(names),
|
||||
)
|
||||
(solid,) = solids.values()
|
||||
part = make_part_rpart(part_id=config.id, body=solid)
|
||||
_IMPLICIT[id(part)] = part
|
||||
return part
|
||||
|
||||
@@ -236,9 +297,9 @@ def project_product(
|
||||
with isolated_recording(), cell_sources(cells):
|
||||
if _IMPLICIT.get(id(product)) is product:
|
||||
# the implicit Part of a kind = "part" notebook was made outside any cell: make it here, recorded, so the
|
||||
# definition has its one result node (the Part), whatever the number of bodies
|
||||
# definition has its one result node (the Part)
|
||||
with session:
|
||||
product = part_from_bodies(product.part_id, {body.body_id: body.solid for body in product.bodies})
|
||||
product = make_part_rpart(part_id=product.part_id, body=product.body)
|
||||
session.validate_graph_ownership(product)
|
||||
for node in session.graph.topological_order():
|
||||
for expression in node.expressions:
|
||||
@@ -272,4 +333,13 @@ def project_product(
|
||||
).value
|
||||
|
||||
|
||||
__all__ = ["NoProductYetError", "Product", "ProductNotFoundError", "find_product", "project_product"]
|
||||
__all__ = [
|
||||
"NoProductYetError",
|
||||
"OpenBodies",
|
||||
"Product",
|
||||
"ProductNotFoundError",
|
||||
"SeveralOpenBodiesError",
|
||||
"find_product",
|
||||
"loose_solids",
|
||||
"project_product",
|
||||
]
|
||||
|
||||
@@ -30,7 +30,7 @@ import struct
|
||||
import threading
|
||||
from collections import OrderedDict
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Collection
|
||||
from typing import Any, Collection, Mapping
|
||||
|
||||
import numpy as np
|
||||
|
||||
@@ -101,7 +101,8 @@ class PreviewScene:
|
||||
definitions: dict[str, str]
|
||||
"""The definition id each part key belongs to."""
|
||||
bodies: dict[str, str] = field(default_factory=dict)
|
||||
"""The body id of each part key that draws one body of a multi-body part (one-body parts are not listed)."""
|
||||
"""The name of each part key that draws one open solid of the notebook (:func:`compile_open_bodies`); the parts of a
|
||||
product are not listed."""
|
||||
|
||||
|
||||
# -- the per-part cache --------------------------------------------------------------
|
||||
@@ -272,51 +273,28 @@ def compile_preview(
|
||||
parts: dict[str, PartPreview] = {}
|
||||
solids: dict[str, Solid] = {}
|
||||
definitions: dict[str, str] = {}
|
||||
bodies: dict[str, str] = {}
|
||||
nodes: list[PreviewNode] = []
|
||||
|
||||
def add(part: Part, path: tuple[str, ...], placement: Placement, name: str) -> None:
|
||||
if not part.multi_body:
|
||||
body = part.body
|
||||
if not isinstance(body, Solid):
|
||||
raise PreviewError(f"part {part.part_id!r} has no solid body")
|
||||
preview = preview_solid(body, linear_tolerance=linear_tolerance, angular_tolerance=angular_tolerance)
|
||||
parts[preview.key] = preview
|
||||
solids.setdefault(preview.key, body)
|
||||
definitions.setdefault(preview.key, part.part_id)
|
||||
only = part.bodies[0]
|
||||
nodes.append(
|
||||
PreviewNode(
|
||||
node_id="node/" + "/".join(path),
|
||||
part_key=preview.key,
|
||||
definition_id=part.part_id,
|
||||
display_name=name,
|
||||
placement=placement,
|
||||
color=body_display_color(part, only),
|
||||
opacity=only.opacity,
|
||||
)
|
||||
)
|
||||
return
|
||||
# A multi-body part: one node per body, all with the part's placement (bodies are never placed apart). The
|
||||
# part key names the body as well, so two bodies of the same shape stay two entity namespaces.
|
||||
for item in part.bodies:
|
||||
preview = preview_solid(item.solid, linear_tolerance=linear_tolerance, angular_tolerance=angular_tolerance)
|
||||
key = f"{preview.key}/body:{item.body_id}"
|
||||
parts[key] = preview
|
||||
solids.setdefault(key, item.solid)
|
||||
definitions.setdefault(key, part.part_id)
|
||||
bodies.setdefault(key, item.body_id)
|
||||
nodes.append(
|
||||
PreviewNode(
|
||||
node_id="node/" + "/".join(path) + "/body:" + item.body_id,
|
||||
part_key=key,
|
||||
definition_id=part.part_id,
|
||||
display_name=f"{name} / {item.name or item.body_id}",
|
||||
placement=placement,
|
||||
color=body_display_color(part, item),
|
||||
opacity=item.opacity,
|
||||
)
|
||||
body = part.body
|
||||
if not isinstance(body, Solid):
|
||||
raise PreviewError(f"part {part.part_id!r} has no solid body")
|
||||
preview = preview_solid(body, linear_tolerance=linear_tolerance, angular_tolerance=angular_tolerance)
|
||||
parts[preview.key] = preview
|
||||
solids.setdefault(preview.key, body)
|
||||
definitions.setdefault(preview.key, part.part_id)
|
||||
only = part.bodies[0]
|
||||
nodes.append(
|
||||
PreviewNode(
|
||||
node_id="node/" + "/".join(path),
|
||||
part_key=preview.key,
|
||||
definition_id=part.part_id,
|
||||
display_name=name,
|
||||
placement=placement,
|
||||
color=body_display_color(part, only),
|
||||
opacity=only.opacity,
|
||||
)
|
||||
)
|
||||
|
||||
def visit(item: Part | Assembly, path: tuple[str, ...], placement: Placement, name: str) -> None:
|
||||
if isinstance(item, Part):
|
||||
@@ -334,7 +312,48 @@ def compile_preview(
|
||||
visit(product, (root_id,), identity_placement(), root_id)
|
||||
if not nodes:
|
||||
raise PreviewError("the product has nothing to draw")
|
||||
return PreviewScene(parts=parts, nodes=nodes, solids=solids, definitions=definitions, bodies=bodies)
|
||||
return PreviewScene(parts=parts, nodes=nodes, solids=solids, definitions=definitions)
|
||||
|
||||
|
||||
def compile_open_bodies(
|
||||
part_id: str,
|
||||
bodies: Mapping[str, Solid],
|
||||
*,
|
||||
linear_tolerance: float = DEFAULT_LINEAR_TOLERANCE,
|
||||
angular_tolerance: float = DEFAULT_ANGULAR_TOLERANCE,
|
||||
) -> PreviewScene:
|
||||
"""Preview solids that exist side by side and are not a product: the open solids of a notebook (a tool and the
|
||||
body it will cut), by name.
|
||||
|
||||
Each is a node ``node/<part_id>/body:<name>`` in world position, with its own entity namespace
|
||||
(``entity/<part_id>/body:<name>/...``, so two solids of the same shape stay two) and the viewer's default colour.
|
||||
They are loose values: nothing places, mates or exports them, and a Part holds exactly one solid.
|
||||
"""
|
||||
|
||||
parts: dict[str, PartPreview] = {}
|
||||
solids: dict[str, Solid] = {}
|
||||
definitions: dict[str, str] = {}
|
||||
names: dict[str, str] = {}
|
||||
nodes: list[PreviewNode] = []
|
||||
for name, solid in bodies.items():
|
||||
preview = preview_solid(solid, linear_tolerance=linear_tolerance, angular_tolerance=angular_tolerance)
|
||||
key = f"{preview.key}/body:{name}"
|
||||
parts[key] = preview
|
||||
solids[key] = solid
|
||||
definitions[key] = part_id
|
||||
names[key] = name
|
||||
nodes.append(
|
||||
PreviewNode(
|
||||
node_id=f"node/{part_id}/body:{name}",
|
||||
part_key=key,
|
||||
definition_id=part_id,
|
||||
display_name=name,
|
||||
placement=identity_placement(),
|
||||
)
|
||||
)
|
||||
if not nodes:
|
||||
raise PreviewError("there is no solid to draw")
|
||||
return PreviewScene(parts=parts, nodes=nodes, solids=solids, definitions=definitions, bodies=names)
|
||||
|
||||
|
||||
SURFACE_COLOR = (0.55, 0.78, 0.95)
|
||||
|
||||
Reference in New Issue
Block a user