diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 452045e4f53..d88b43d7cd1 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -4,7 +4,7 @@ on: push: branches: [main] pull_request: - branches: [main, initiative/repository-modernisation] + branches: [main, remove-future, initiative/repository-modernisation] permissions: contents: read diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 67a9eec63eb..655cf4d7b4d 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -4,7 +4,7 @@ on: push: branches: [main] pull_request: - branches: [main, initiative/repository-modernisation] + branches: [main, remove-future, initiative/repository-modernisation] permissions: contents: read diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 52afb1263a3..d9a1439a3e6 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -4,7 +4,7 @@ on: push: branches: [main] pull_request: - branches: [main, initiative/repository-modernisation] + branches: [main, remove-future, initiative/repository-modernisation] permissions: contents: read diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 2d52ab6842f..7d0d5f74790 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -3,7 +3,7 @@ name: verify pull request on: pull_request: types: [assigned, opened, synchronize, reopened, labeled, unlabeled] - branches: [main, initiative/repository-modernisation] + branches: [main, remove-future, initiative/repository-modernisation] permissions: contents: read diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a551c39b20..422376d67f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +* Added backend-neutral text, arrow, and fixed or associative distance + annotations to `compas.scene`. +* Added an ordered scene-scoped annotation collection and durable distance + styles with color, line width, text size, arrow size, and label offset. +* Added durable, reference-only scene objects with declarative persistent-state + fields, explicit data rebinding, inspectable unresolved references, and + hierarchy-only scene nodes. +* Added stable semantic scene objects for shapes, surfaces, frames, planes, and + vectors, with backend-neutral discretization and display state. +* Added MRO-composed editable scene-state fields, narrowly scoped non-state + declarations, and data-only mutation callbacks for contextual object editors. * Added a verified Linux Python 3.12 candidate wheel artifact for framework-wide pre-release integration. * Added the public `compas.typing` structural vocabulary with NumPy-aware `PointLike`, `VectorLike`, collection, and neutral `VerticesFaces` aliases. * Added the PEP 561 `py.typed` marker and installed-wheel static-consumer verification. @@ -23,6 +34,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +* Moved annotations out of the spatial scene hierarchy into schema-v3 + `SceneAnnotation` entries. Annotation items remain independently serialized + and bound by GUID; the former annotation `SceneObject` classes are removed. +* Made scene objects stable backend-neutral data records and replaced class + substitution with deterministic context- and MRO-keyed `draw` and `clear` + operations. Runtime resources remain outside durable scene objects. * Migrated core geometry constructors and plugin contracts from private overlapping type aliases to semantic structural inputs, including copied NumPy coordinates and integral face indices. * Added a committed uv development lock, documented direct quality commands while retaining Invoke convenience tasks, and migrated CI, release, artifact, and documentation mechanics to immutably pinned shared actions. * Standardized numerical triangle-mesh plugin inputs and outputs on structural `(vertices, triangles)` buffers. `Tessellation` remains an ephemeral discrete representation for geometry producers and scene handoff, but is not required at numerical backend boundaries. diff --git a/docs/getting-started/basics.visualisation.md b/docs/getting-started/basics.visualisation.md index 66618ac40df..559f50a4de0 100644 --- a/docs/getting-started/basics.visualisation.md +++ b/docs/getting-started/basics.visualisation.md @@ -11,9 +11,9 @@ COMPAS (data) objects can be visualised by placing them into a "scene". >>> scene.draw() ``` -When a COMPAS object is added, the scene creates the corresponding scene object -for the active visualisation context. Visualisation backends are provided by -separate COMPAS packages. +When a COMPAS object is added, the scene creates a stable, backend-neutral scene +object for its semantic type. Visualisation backends are provided by separate +COMPAS packages and register operations for these stable objects. ## Scene Objects @@ -21,19 +21,38 @@ When a COMPAS object is added to a scene, a scene object is created automaticall ```pycon >>> sceneobj = scene.add(box) ->>> sceneobj -BoxObject +>>> type(sceneobj).__name__ +'ShapeObject' ``` The scene object holds a reference to the COMPAS data object, and stores its visualisation settings and transformation matrix. Multiple scene objects can be created for the same COMPAS data object, each with different visualisation settings and transformations. +Core provides stable semantic scene-object types for data whose visualisation +needs additional backend-neutral settings: + +- `ShapeObject` and `SurfaceObject` store the `u` and `v` discretization + counts used to display analytic shapes and parametric surfaces. +- `FrameObject` and `PlaneObject` store their display `size`. +- `VectorObject` stores the vector's display `anchor`. +- `MeshObject` stores `hide_coplanaredges` and `use_vertexcolors` in addition + to its vertex, edge, and face settings. + +These settings describe durable presentation intent. A visualisation backend +decides how to draw them; changing the backend does not change the scene-object +type or its stored settings. + +For a `FrameObject`, the inherited `geometry` property is the represented +[`Frame`][compas.geometry.Frame]. Its inherited `frame` property has the same +meaning as on every `SceneObject`: it is the world-placement frame derived from +the scene hierarchy. The two frames therefore serve different purposes. + ```pycon >>> sceneobj1 = scene.add(box) >>> sceneobj2 = scene.add(box) >>> sceneobj1 is sceneobj2 False ->>> sceneobj1.data is sceneobj2.data +>>> sceneobj1.item is sceneobj2.item True ``` @@ -45,7 +64,7 @@ All scene objects have a color attribute. ```pycon >>> sceneobj = scene.add(box) >>> sceneobj.color -Color(0.0, 0.0, 0.0, alpha=1.0) +Color(1.0, 1.0, 1.0, alpha=1.0) ``` Color attributes can be set using a COMPAS Color object, or a tuple of RGB values, with the color components specified as floats in the range 0.0-1.0 or as integers in the range 0-255. @@ -73,12 +92,106 @@ For example, meshes can have different colors for the vertices, the edges, and t And the colors of vertices, edges, and faces can be specified individually, per element. See the section about mesh visualisation for more information. +### Editable Attributes + +Stable scene-object classes declare which of their attributes may be exposed by +an object editor. The resolved mapping contains only attribute names and +optional data-side update callbacks. Visualisation packages decide how to +construct controls and refresh their views. + +```pycon +>>> attributes = type(sceneobj).editable_attributes() +>>> "show_surfaces" in attributes +True +>>> sceneobj.update_editable_attribute("opacity", 0.5) +>>> sceneobj.opacity +0.5 +``` + +The declarations compose through the scene-object class hierarchy. A `None` +callback uses ordinary attribute assignment. A declaration may instead provide +an atomic, synchronous data-update callback when assignment alone is not +sufficient. Update callbacks never draw, rebuild render data, or refresh a user +interface. + +Durable editable attributes are declared once as scene state: + +```python +from compas.scene import SceneObject +from compas.scene import SceneStateField + + +class CustomObject(SceneObject): + __scene_state_namespace__ = "example.CustomObject" + __scene_state_fields__ = (SceneStateField("quality", int, required=False, editable=True),) +``` + +The separate `__editable_attributes__` mapping is reserved for editable +attributes that are not durable scene state. Derived callback overrides retain +the inherited attribute position, while new attributes append in declaration +order. Use +[`SceneObject.update_editable_attribute`][compas.scene.SceneObject.update_editable_attribute] +to apply the default assignment or the declared data-update callback. + +Editability does not add presentation metadata to +[`SceneStateField`][compas.scene.SceneStateField] and is not serialized. A +durable scene-state field is not editable unless it explicitly sets +`editable=True`. + +### Data, Scene State, and Extensions + +Every scene object is a [`Data`][compas.data.Data] object. COMPAS serialization +wraps it in an envelope containing its data type, GUID, optional name, and the +payload returned by `SceneObject.__data__`. The represented geometry or +datastructure is another independent `Data` object; the scene object stores +only its GUID in the `item` field. + +The scene-object payload has two state layers: + +- Common state such as `transformation`, `color`, `opacity`, and `show` is + stored directly in the payload. +- Type-specific state declared by `SceneStateField` is stored under the + declaring class's namespace in the `extensions` mapping. + +For example, a shape scene object may serialize geometry display settings and +shape resolution separately: + +```python +from compas.colors import Color + + +payload = { + "item": "", + "transformation": None, + "color": Color.white(), + "opacity": 1.0, + "show": True, + "extensions": { + "compas.scene.GeometryObject": { + "show_points": False, + "show_lines": True, + }, + "compas.scene.ShapeObject": { + "u": 16, + "v": 16, + }, + }, +} +``` + +Namespaces let subclasses and external packages add durable state without +widening the common scene-object payload. Unknown namespaced values are +preserved during a round trip for forward compatibility. Runtime item +bindings, editable-attribute callbacks, Viewer controls, selection, and render +resources are not stored in `extensions` or elsewhere in the serialized scene. + ## Scene Hierarchy -Scene objects are organised in a hierarchy under a private root group. -The scene stores data and scene objects by GUID, while a COMPAS tree of -lightweight internal nodes records the hierarchy. Public hierarchy properties -on scene objects resolve these internal references. +Scene objects are organised in a hierarchy under an ordinary root group. A +[`SceneNode`][compas.scene.SceneNode] contains only an object GUID and child +nodes. Presentation state and the referenced data GUID belong to the stable +[`SceneObject`][compas.scene.SceneObject]. Each scene object has exactly one +node in a scene. ```pycon >>> scene = Scene() @@ -96,6 +209,69 @@ True True ``` +## Annotations + +Text, arrows, and dimensions belong to a separate ordered annotation +collection. They are durable scene data, but they do not have a hierarchy node, +parent, children, or transformation. Fixed dimension anchors therefore store +world-coordinate points, while associative anchors resolve spatial scene +objects by GUID. + +```pycon +>>> from compas.colors import Color +>>> from compas.scene import DimensionStyle +>>> from compas.scene import DistanceDimension +>>> from compas.scene import PointAnchor +>>> dimension = DistanceDimension( +... PointAnchor([0, 0, 0]), +... PointAnchor([3, 4, 0]), +... unit="m", +... ) +>>> entry = scene.add_annotation( +... dimension, +... name="Diagonal", +... style=DimensionStyle(color=Color.red(), text_size=14), +... ) +>>> scene.annotations == (entry,) +True +>>> entry in scene.objects +False +``` + +Annotation items remain independently serializable, just like geometry and +data structures. [`Scene.add_annotation`][compas.scene.Scene.add_annotation] +binds the supplied item for the current process. A scene loaded separately has +unresolved annotation entries until their items are restored with +[`Scene.bind`][compas.scene.Scene.bind] or +[`Scene.bind_many`][compas.scene.Scene.bind_many]. Use +[`Scene.remove_annotation`][compas.scene.Scene.remove_annotation] to remove an +entry without deleting its independently owned item. + +## Saving Scenes and Data + +A serialized scene contains its hierarchy, ordered annotation collection, +presentation state, and references to data objects by GUID. It does not embed +or own those data objects. Serialize the data separately when it should outlive +the current Python process. + +After loading a scene, its objects and hierarchy can be inspected immediately. +Bind the independently loaded data explicitly before accessing an object's +`item` or drawing it. + +```pycon +>>> description = scene.to_jsonstring() +>>> loaded_scene = Scene.from_jsonstring(description) +>>> loaded_scene.find_by_name(sceneobj.name).item_guid == box.guid +True +>>> loaded_scene.bind(box) +>>> loaded_scene.find_by_name(sceneobj.name).item is box +True +``` + +Use [`Scene.bind_many`][compas.scene.Scene.bind_many] when restoring several +referenced data objects at once. Bindings are runtime references: binding does +not copy the object or add it to the serialized scene description. + To use a different scene object as the parent, pass it to `Scene.add`. ```pycon @@ -103,43 +279,55 @@ To use a different scene object as the parent, pass it to `Scene.add`. >>> point = Point(1, 2, 3) >>> pointobj = scene.add(point) >>> boxobj = scene.add(box, parent=pointobj) ->>> boxobj.parent -PointObject +>>> type(boxobj.parent).__name__ +'GeometryObject' ``` -## Object Frame And Transformation +## Object transformations -Every scene objects can have a reference "frame" that represents its local coordinate system relative to the frame of its hierarchical parent. -In addition, an object can also have a local "transformation" which orientates this object from its frame. -The final transformation of an object relative to the world coordinate system is the aggregated multiplication of all its hierarchical ancesters' frames, -together with its own local frame and transformation. This prorperty can be accessed through the read-only attribute "worldtransformation". +Every scene object stores an optional local `transformation` relative to its +parent. A value of `None` represents the identity transformation. The +`worldtransformation` property composes the local transformations of the object +and its ancestors from the hierarchy root to the object. ```pycon ->>> from compas.geometry import Translation >>> from compas.geometry import Box ->>> from compas.geometry import Frame ->>> sceneobj1 = scene.add(Box()) ->>> sceneobj1.frame = Frame(point=[1.0, 0.0, 0.0], xaxis=[1.0, 0.0, 0.0], yaxis=[0.0, 1.0, 0.0]) ->>> sceneobj1.transformation = Translation.from_vector([10.0, 0.0, 0.0]) ->>> sceneobj1.worldtransformation -Transformation([[1.0, 0.0, 0.0, 11.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]], check=False) ->>> sceneobj1.worldtransformation == sceneobj1.frame.to_transfromation() * sceneobj1.transformation +>>> from compas.geometry import Translation +>>> parent = scene.add_group( +... "Assembly", +... transformation=Translation.from_vector([10.0, 0.0, 0.0]), +... ) +>>> child = scene.add( +... Box(1.0), +... parent=parent, +... transformation=Translation.from_vector([0.0, 2.0, 0.0]), +... ) +>>> child.worldtransformation == Translation.from_vector([10.0, 2.0, 0.0]) True ``` -The worldtransformation of a nestd "sceneobj2" will be calculated as: Frame of "sceneobj1" * Frame of "sceneobj2" * Transformation of "sceneobj2" -\>>> sceneobj2 = scene.add(Box(), parent=sceneobj1) -\>>> sceneobj2.frame = Frame([1.0, 1.0, 0.0], xaxis=[1.0, 0.0, 0.0],yaxis=[0.0, 1.0, 0.0]) -\>>> sceneobj2.transformation = Translation.from_vector([10.0, 10.0, 0.0]) -\>>> sceneobj.worldtransformation -Transformation(\[[1.0, 0.0, 0.0, 12.0], [0.0, 1.0, 0.0, 11.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]\], check=False) -\>>> sceneobj2.worldtransformation == sceneobj1.frame.to_transfromation() * sceneobj2.frame.to_transfrom() * sceneobj2.transformation +Assigning `worldtransformation` converts the requested world transformation to +the corresponding local transformation through the inverse parent world +transformation. The parent remains unchanged. + +```pycon +>>> child.worldtransformation = Translation.from_vector([20.0, 3.0, 0.0]) +>>> child.transformation == Translation.from_vector([10.0, 3.0, 0.0]) +True +>>> parent.transformation == Translation.from_vector([10.0, 0.0, 0.0]) True +``` + +`frame` is the frame represented by the current world transformation. Assigning +a frame is therefore another way to set `worldtransformation`; it is not a +separate local frame stored alongside `transformation`. ## Scene Context -Visualisation packages register their own scene contexts and scene object -implementations. Users can select a registered context explicitly: +Visualisation packages register `draw` and `clear` operations for stable scene +object and annotation-entry types. Selecting another context changes operation +lookup; it never replaces durable scene state or changes its Python types. +Users can select a registered context explicitly: ```pycon >>> scene = Scene(context="MyContextName") diff --git a/src/compas/files/gltf/gltf_conversions.py b/src/compas/files/gltf/gltf_conversions.py index ea1630636ee..e7239bbfd0b 100644 --- a/src/compas/files/gltf/gltf_conversions.py +++ b/src/compas/files/gltf/gltf_conversions.py @@ -2,7 +2,6 @@ import warnings from collections.abc import Sequence -from contextlib import contextmanager from typing import TYPE_CHECKING from typing import Any from typing import cast @@ -28,8 +27,7 @@ from compas.scene import Group from compas.scene import MeshObject from compas.scene import Scene -from compas.scene.context import ITEM_SCENEOBJECT -from compas.scene.context import register +from compas.scene.context import register_sceneobject_type if TYPE_CHECKING: from compas.files.gltf.gltf_document import GLTFDocument @@ -37,20 +35,6 @@ from compas.scene import SceneObject # noqa: F401 -@contextmanager -def _base_scene_context(): - """Provide base scene objects without triggering visualization plugin discovery.""" - original = {context: registry.copy() for context, registry in ITEM_SCENEOBJECT.items()} - register(Geometry, GeometryObject, context=None) - register(Mesh, MeshObject, context=None) - try: - yield - finally: - ITEM_SCENEOBJECT.clear() - for context, registry in original.items(): - ITEM_SCENEOBJECT[context].update(registry) - - def _indexed_positions( positions: Sequence[Sequence[float]], indices: Sequence[int] | None, @@ -308,10 +292,10 @@ def add_node(node: "GLTFNode", parent: "SceneObject") -> None: for child_key in node.children: add_node(document.nodes[child_key], group) - with _base_scene_context(): - for root_key in source_scene.children: - assert scene.root is not None - add_node(document.nodes[root_key], scene.root) + register_sceneobject_type(Geometry, GeometryObject) + register_sceneobject_type(Mesh, MeshObject) + for root_key in source_scene.children: + add_node(document.nodes[root_key], scene.root) return scene diff --git a/src/compas/scene/__init__.py b/src/compas/scene/__init__.py index 7fdcb3299b9..0638a4feb19 100644 --- a/src/compas/scene/__init__.py +++ b/src/compas/scene/__init__.py @@ -1,29 +1,54 @@ -"""Visualize COMPAS geometry and data structures through scene objects. +"""Visualize COMPAS data through spatial objects and annotations. -Each supported item type is paired with a scene object type. Visualization -contexts register specialized scene object implementations through plugins. +Each supported item type is paired with one stable semantic scene-object type. +Text, arrow, and dimension items use the separate ordered annotation +collection. Visualization contexts register operations rather than replacement +classes. """ +from ._scenenode import SceneNode +from .exceptions import SceneItemNotBoundError from .exceptions import SceneObjectNotRegisteredError +from .exceptions import SceneStateError +from .exceptions import SceneOperationNotRegisteredError from .sceneobject import SceneObject +from .sceneobject import SceneAttributeUpdate +from .sceneobject import SceneStateField from .meshobject import MeshObject from .graphobject import GraphObject from .geometryobject import GeometryObject +from .shapeobject import ShapeObject +from .surfaceobject import SurfaceObject +from .frameobject import FrameObject +from .planeobject import PlaneObject +from .vectorobject import VectorObject from .volmeshobject import VolMeshObject from .group import Group +from .annotations import ArrowAnnotation +from .annotations import ComponentAnchor +from .annotations import DistanceDimension +from .annotations import PointAnchor +from .annotations import TextAnnotation +from .sceneannotation import DimensionStyle +from .sceneannotation import SceneAnnotation -from .context import clear -from .context import before_draw -from .context import after_draw from .context import register_scene_objects +from .context import register_scene_operations from .context import get_sceneobject_cls -from .context import register +from .context import get_scene_operation +from .context import register_sceneobject_type +from .context import register_scene_operation from .scene import Scene from compas.plugins import plugin from compas.geometry import Geometry +from compas.geometry import Shape +from compas.geometry import Surface +from compas.geometry import Frame +from compas.geometry import Plane +from compas.geometry import Vector from compas.datastructures import Mesh from compas.datastructures import Graph from compas.datastructures import VolMesh @@ -31,26 +56,49 @@ @plugin(category="factories", pluggable_name="register_scene_objects") def register_scene_objects_base() -> None: - """Register the context-independent core scene object types.""" - register(Geometry, GeometryObject, context=None) - register(Mesh, MeshObject, context=None) - register(Graph, GraphObject, context=None) - register(VolMesh, VolMeshObject, context=None) + """Register stable core scene-object types.""" + register_sceneobject_type(Geometry, GeometryObject) + register_sceneobject_type(Shape, ShapeObject) + register_sceneobject_type(Surface, SurfaceObject) + register_sceneobject_type(Frame, FrameObject) + register_sceneobject_type(Plane, PlaneObject) + register_sceneobject_type(Vector, VectorObject) + register_sceneobject_type(Mesh, MeshObject) + register_sceneobject_type(Graph, GraphObject) + register_sceneobject_type(VolMesh, VolMeshObject) __all__ = [ "SceneObjectNotRegisteredError", + "SceneItemNotBoundError", + "SceneStateError", + "SceneOperationNotRegisteredError", + "SceneNode", "SceneObject", + "SceneAttributeUpdate", + "SceneStateField", "MeshObject", "GraphObject", "GeometryObject", + "ShapeObject", + "SurfaceObject", + "FrameObject", + "PlaneObject", + "VectorObject", "VolMeshObject", "Group", - "clear", - "before_draw", - "after_draw", + "PointAnchor", + "ComponentAnchor", + "TextAnnotation", + "ArrowAnnotation", + "DistanceDimension", + "DimensionStyle", + "SceneAnnotation", "register_scene_objects", + "register_scene_operations", "get_sceneobject_cls", - "register", + "get_scene_operation", + "register_sceneobject_type", + "register_scene_operation", "Scene", ] diff --git a/src/compas/scene/_scenenode.py b/src/compas/scene/_scenenode.py index 4bf144926fd..15c5d9b5cc2 100644 --- a/src/compas/scene/_scenenode.py +++ b/src/compas/scene/_scenenode.py @@ -1,11 +1,57 @@ +from typing import Any +from typing import Self from uuid import UUID from compas.datastructures import TreeNode class SceneNode(TreeNode["SceneNode"]): - """Private hierarchy node referencing a scene object by GUID.""" + """One hierarchy entry referencing a stable scene object. + + Parameters + ---------- + object_guid + The GUID of the referenced scene object. + + Notes + ----- + A scene node owns hierarchy only. Its referenced `SceneObject` owns all + durable presentation and item-reference state. + + """ + + _ALLOWED_DATA_KEYS = {"object", "children"} + + @property + def __data__(self) -> dict[str, Any]: + """Return the recursive hierarchy representation.""" + return { + "object": str(self.object_guid), + "children": [child.__data__ for child in self.children], + } + + @classmethod + def __from_data__(cls, data: dict[str, Any]) -> Self: + """Construct a hierarchy entry and its descendants.""" + unknown = set(data) - cls._ALLOWED_DATA_KEYS + if unknown: + raise ValueError("Unknown scene-node fields: {}.".format(", ".join(sorted(unknown)))) + missing = cls._ALLOWED_DATA_KEYS - set(data) + if missing: + raise ValueError("Missing scene-node fields: {}.".format(", ".join(sorted(missing)))) + if not isinstance(data["children"], list): + raise TypeError("Scene-node children should be a list.") + try: + object_guid = UUID(data["object"]) + except (AttributeError, TypeError, ValueError): + raise ValueError("Scene-node object should be a UUID string.") from None + node = cls(object_guid) + for child_data in data["children"]: + node.add(cls.__from_data__(child_data)) + return node def __init__(self, object_guid: UUID) -> None: - super().__init__() + if not isinstance(object_guid, UUID): + raise TypeError("Scene-node object_guid should be a UUID.") + super().__init__(name=str(object_guid)) self.object_guid = object_guid diff --git a/src/compas/scene/annotations.py b/src/compas/scene/annotations.py new file mode 100644 index 00000000000..587416e62b5 --- /dev/null +++ b/src/compas/scene/annotations.py @@ -0,0 +1,605 @@ +from math import isfinite +from typing import TYPE_CHECKING +from typing import Any +from typing import Literal +from typing import Self +from typing import cast +from uuid import UUID + +from compas.data import Data +from compas.geometry import Line +from compas.geometry import Point +from compas.geometry import Transformation +from compas.geometry import distance_point_point +from compas.typing import PointLike + +from .exceptions import SceneItemNotBoundError + +__all__ = [ + "PointAnchor", + "ComponentAnchor", + "TextAnnotation", + "ArrowAnnotation", + "DistanceDimension", +] + +if TYPE_CHECKING: + from .scene import Scene + + +type HorizontalAlignment = Literal["left", "center", "right"] +type VerticalAlignment = Literal["bottom", "center", "top"] +type HeightMode = Literal["screen", "world"] +type ComponentType = Literal["point", "vertex", "node", "line", "edge"] +type ComponentKey = int | str | tuple[ComponentKey, ...] +type EdgeKey = tuple[ComponentKey, ComponentKey] + + +class PointAnchor(Data): + """A fixed dimension anchor in the dimension's local coordinates. + + Parameters + ---------- + point + The fixed anchor point. + name + The anchor name. + + """ + + @property + def __data__(self) -> dict[str, Any]: + """Return the fixed-anchor data. + + Returns + ------- + dict[str, Any] + The serializable fixed-anchor data. + + """ + return {"point": self.point} + + @classmethod + def __from_data__(cls, data: dict[str, Any]) -> Self: + """Construct a fixed anchor from its serialized data. + + Returns + ------- + PointAnchor + The reconstructed fixed anchor. + + """ + _validate_schema(data, {"point"}, "point-anchor") + return cls(data["point"]) + + def __init__(self, point: PointLike, name: str | None = None) -> None: + super().__init__(name=name) + self.point = _copy_point(point) + + def __eq__(self, other: object) -> bool: + return isinstance(other, PointAnchor) and self.point == other.point + + def resolve(self, transformation: Transformation | None = None) -> Point: + """Return the fixed point, optionally transformed to world coordinates. + + Parameters + ---------- + transformation + Transformation from the owning dimension's local coordinates to + world coordinates. + + Returns + ------- + Point + A new point. The stored anchor is never modified. + + """ + point = _copy_point(self.point) + if transformation is not None: + point.transform(transformation) + return point + + +class ComponentAnchor(Data): + """An associative anchor that resolves a scene component's current point. + + Parameters + ---------- + object_guid + GUID of the scene object containing the component. + component_type + Component selector type. Supported values are `"point"`, `"vertex"`, + `"node"`, `"line"`, and `"edge"`. + component + Stable vertex or node key, or a pair of edge endpoint keys. Stable keys + may be integers, strings, or recursively nested tuples of those values. + Point and line anchors have no component key. + parameter + Normalized line or edge parameter in the closed interval from zero to + one. Point, vertex, and node anchors have no parameter. + name + The anchor name. + + Notes + ----- + Resolution reads the referenced item every time. An unavailable object, + item, or component returns `None`; no fallback point is stored or reused. + + """ + + @property + def __data__(self) -> dict[str, Any]: + """Return the associative-anchor data. + + Returns + ------- + dict[str, Any] + The serializable associative-anchor data. + + """ + return { + "object_guid": str(self.object_guid), + "component_type": self.component_type, + "component": self.component, + "parameter": self.parameter, + } + + @classmethod + def __from_data__(cls, data: dict[str, Any]) -> Self: + """Construct an associative anchor from its serialized data. + + Returns + ------- + ComponentAnchor + The reconstructed associative anchor. + + """ + _validate_schema(data, {"object_guid", "component_type", "component", "parameter"}, "component-anchor") + component = cast(ComponentKey | EdgeKey | None, _restore_component_key(data["component"])) + return cls( + UUID(data["object_guid"]), + data["component_type"], + component=component, + parameter=data["parameter"], + ) + + def __init__( + self, + object_guid: UUID, + component_type: ComponentType, + component: ComponentKey | EdgeKey | None = None, + parameter: float | None = None, + *, + name: str | None = None, + ) -> None: + super().__init__(name=name) + if not isinstance(object_guid, UUID): + raise TypeError("Component-anchor object_guid should be a UUID.") + if component_type not in {"point", "vertex", "node", "line", "edge"}: + raise ValueError(f"Unsupported component-anchor type: {component_type!r}.") + if component_type in {"point", "line"}: + if component is not None: + raise ValueError(f"A {component_type} anchor should not have a component key.") + elif component_type in {"vertex", "node"}: + if not _is_component_key(component): + raise TypeError(f"A {component_type} anchor should have a stable serializable component key.") + else: + if not isinstance(component, tuple) or len(component) != 2 or not all(_is_component_key(key) for key in component): + raise TypeError("An edge anchor should have a pair of stable serializable endpoint keys.") + if component_type in {"line", "edge"}: + if isinstance(parameter, bool) or not isinstance(parameter, (int, float)): + raise TypeError(f"A {component_type} anchor should have a numeric parameter.") + if not 0.0 <= parameter <= 1.0: + raise ValueError(f"A {component_type} anchor parameter should be between 0.0 and 1.0.") + elif parameter is not None: + raise ValueError(f"A {component_type} anchor should not have a parameter.") + self.object_guid = object_guid + self.component_type = component_type + self.component = component + self.parameter = float(parameter) if parameter is not None else None + + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, ComponentAnchor) + and self.object_guid == other.object_guid + and self.component_type == other.component_type + and self.component == other.component + and self.parameter == other.parameter + ) + + def resolve(self, scene: "Scene") -> Point | None: + """Resolve the component to its current world-coordinate point. + + Parameters + ---------- + scene + Scene containing the referenced scene object and its bound item. + + Returns + ------- + Point | None + The current world-coordinate point, or `None` when the reference + cannot be resolved. + + """ + try: + sceneobject = scene.object(self.object_guid) + item = sceneobject.item + except (KeyError, SceneItemNotBoundError): + return None + if item is None: + return None + try: + if self.component_type == "point": + if not isinstance(item, Point): + return None + point: object = item + elif self.component_type == "line": + if not isinstance(item, Line): + return None + parameter = cast(float, self.parameter) + point = item.point_at(parameter) + elif self.component_type == "vertex": + vertex_point = getattr(item, "vertex_point", None) + if not callable(vertex_point): + return None + point = vertex_point(self.component) + elif self.component_type == "node": + node_point = getattr(item, "node_point", None) + if not callable(node_point): + return None + point = node_point(self.component) + else: + has_edge = getattr(item, "has_edge", None) + edge_point = getattr(item, "edge_point", None) + if not callable(has_edge) or not callable(edge_point): + return None + edge = cast(EdgeKey, self.component) + reverse = (edge[1], edge[0]) + if not has_edge(edge) and not has_edge(reverse): + return None + point = edge_point(self.component, self.parameter) + except (KeyError, IndexError): + return None + resolved = _copy_point(cast(PointLike, point)) + resolved.transform(sceneobject.worldtransformation) + return resolved + + +class TextAnnotation(Data): + """Backend-neutral world text anchored in local coordinates. + + Parameters + ---------- + text + Annotation text. + anchor + Local anchor point. + height + Positive text height in screen pixels or world units, according to + `height_mode`. + height_mode + `"screen"` for constant screen size or `"world"` for world-space size. + horizontal_alignment + Horizontal alignment relative to the anchor. + vertical_alignment + Vertical alignment relative to the anchor. + name + The annotation name. + + """ + + @property + def __data__(self) -> dict[str, Any]: + """Return the text-annotation data. + + Returns + ------- + dict[str, Any] + The serializable text-annotation data. + + """ + return { + "text": self.text, + "anchor": self.anchor, + "height": self.height, + "height_mode": self.height_mode, + "horizontal_alignment": self.horizontal_alignment, + "vertical_alignment": self.vertical_alignment, + } + + @classmethod + def __from_data__(cls, data: dict[str, Any]) -> Self: + """Construct a text annotation from its serialized data. + + Returns + ------- + TextAnnotation + The reconstructed text annotation. + + """ + _validate_schema( + data, + {"text", "anchor", "height", "height_mode", "horizontal_alignment", "vertical_alignment"}, + "text-annotation", + ) + return cls(**data) + + def __init__( + self, + text: str, + anchor: PointLike, + height: float = 12.0, + height_mode: HeightMode = "screen", + horizontal_alignment: HorizontalAlignment = "left", + vertical_alignment: VerticalAlignment = "bottom", + *, + name: str | None = None, + ) -> None: + super().__init__(name=name) + if not isinstance(text, str): + raise TypeError("Text-annotation text should be a string.") + if isinstance(height, bool) or not isinstance(height, (int, float)): + raise TypeError("Text-annotation height should be a number.") + if not isfinite(height) or height <= 0: + raise ValueError("Text-annotation height should be finite and positive.") + if height_mode not in {"screen", "world"}: + raise ValueError(f"Unsupported text-annotation height mode: {height_mode!r}.") + if horizontal_alignment not in {"left", "center", "right"}: + raise ValueError(f"Unsupported horizontal alignment: {horizontal_alignment!r}.") + if vertical_alignment not in {"bottom", "center", "top"}: + raise ValueError(f"Unsupported vertical alignment: {vertical_alignment!r}.") + self.text = text + self.anchor = _copy_point(anchor) + self.height = float(height) + self.height_mode = height_mode + self.horizontal_alignment = horizontal_alignment + self.vertical_alignment = vertical_alignment + + def __eq__(self, other: object) -> bool: + return isinstance(other, TextAnnotation) and self.__data__ == other.__data__ + + +class ArrowAnnotation(Data): + """Backend-neutral world arrow between two local-coordinate points. + + Parameters + ---------- + start + Local arrow start point. + end + Local arrow end point. + name + The annotation name. + + """ + + @property + def __data__(self) -> dict[str, Any]: + """Return the arrow-annotation data. + + Returns + ------- + dict[str, Any] + The serializable arrow-annotation data. + + """ + return {"start": self.start, "end": self.end} + + @classmethod + def __from_data__(cls, data: dict[str, Any]) -> Self: + """Construct an arrow annotation from its serialized data. + + Returns + ------- + ArrowAnnotation + The reconstructed arrow annotation. + + """ + _validate_schema(data, {"start", "end"}, "arrow-annotation") + return cls(**data) + + def __init__(self, start: PointLike, end: PointLike, *, name: str | None = None) -> None: + super().__init__(name=name) + start_point = _copy_point(start) + end_point = _copy_point(end) + if start_point == end_point: + raise ValueError("Arrow-annotation start and end points should be different.") + self.start = start_point + self.end = end_point + + def __eq__(self, other: object) -> bool: + return isinstance(other, ArrowAnnotation) and self.start == other.start and self.end == other.end + + +class DistanceDimension(Data): + """A distance annotation with independently fixed or associative anchors. + + Parameters + ---------- + start + First fixed or associative anchor. + end + Second fixed or associative anchor. + unit + Optional informational unit suffix. No coordinate conversion is + performed. + precision + Non-negative number of fixed-point decimal places. + label + Optional verbatim label overriding derived distance formatting. + name + The dimension name. + + """ + + @property + def __data__(self) -> dict[str, Any]: + """Return the distance-dimension data. + + Returns + ------- + dict[str, Any] + The serializable distance-dimension data. + + """ + return { + "start": self.start, + "end": self.end, + "unit": self.unit, + "precision": self.precision, + "label": self.label, + } + + @classmethod + def __from_data__(cls, data: dict[str, Any]) -> Self: + """Construct a distance dimension from its serialized data. + + Returns + ------- + DistanceDimension + The reconstructed distance dimension. + + """ + _validate_schema(data, {"start", "end", "unit", "precision", "label"}, "distance-dimension") + return cls(**data) + + def __init__( + self, + start: PointAnchor | ComponentAnchor, + end: PointAnchor | ComponentAnchor, + unit: str | None = None, + precision: int = 2, + label: str | None = None, + *, + name: str | None = None, + ) -> None: + super().__init__(name=name) + if not isinstance(start, (PointAnchor, ComponentAnchor)): + raise TypeError("Distance-dimension start should be a PointAnchor or ComponentAnchor.") + if not isinstance(end, (PointAnchor, ComponentAnchor)): + raise TypeError("Distance-dimension end should be a PointAnchor or ComponentAnchor.") + if unit is not None and not isinstance(unit, str): + raise TypeError("Distance-dimension unit should be a string or None.") + if unit is not None and not unit.strip(): + raise ValueError("Distance-dimension unit should be non-empty or None.") + if isinstance(precision, bool) or not isinstance(precision, int): + raise TypeError("Distance-dimension precision should be an integer.") + if precision < 0: + raise ValueError("Distance-dimension precision should be non-negative.") + if label is not None and not isinstance(label, str): + raise TypeError("Distance-dimension label should be a string or None.") + self.start = start + self.end = end + self.unit = unit + self.precision = precision + self.label = label + + def __eq__(self, other: object) -> bool: + return isinstance(other, DistanceDimension) and self.__data__ == other.__data__ + + def resolve( + self, + scene: "Scene | None" = None, + transformation: Transformation | None = None, + ) -> tuple[Point, Point] | None: + """Resolve both anchors to world-coordinate points. + + Parameters + ---------- + scene + Scene used to resolve associative anchors. + transformation + Transformation from this dimension's local coordinates to world + coordinates. It applies only to fixed anchors. + + Returns + ------- + tuple[Point, Point] | None + Resolved start and end points, or `None` if either associative + anchor is unresolved. + + """ + start = self._resolve_anchor(self.start, scene, transformation) + end = self._resolve_anchor(self.end, scene, transformation) + if start is None or end is None: + return None + return start, end + + def distance( + self, + scene: "Scene | None" = None, + transformation: Transformation | None = None, + ) -> float | None: + """Return the current resolved distance, or `None` if unresolved. + + Returns + ------- + float | None + The resolved distance, or `None`. + + """ + points = self.resolve(scene, transformation) + if points is None: + return None + return distance_point_point(*points) + + def formatted_label( + self, + scene: "Scene | None" = None, + transformation: Transformation | None = None, + ) -> str | None: + """Return the verbatim override or current formatted distance label. + + Returns + ------- + str | None + The label override, derived label, or `None` if unresolved. + + """ + if self.label is not None: + return self.label + distance = self.distance(scene, transformation) + if distance is None: + return None + value = f"{distance:.{self.precision}f}" + return f"{value} {self.unit}" if self.unit else value + + @staticmethod + def _resolve_anchor( + anchor: PointAnchor | ComponentAnchor, + scene: "Scene | None", + transformation: Transformation | None, + ) -> Point | None: + if isinstance(anchor, PointAnchor): + return anchor.resolve(transformation) + if scene is None: + return None + return anchor.resolve(scene) + + +def _validate_schema(data: dict[str, Any], expected: set[str], label: str) -> None: + unknown = set(data) - expected + if unknown: + raise ValueError(f"Unknown {label} fields: {', '.join(sorted(unknown))}.") + missing = expected - set(data) + if missing: + raise ValueError(f"Missing {label} fields: {', '.join(sorted(missing))}.") + + +def _copy_point(point: PointLike) -> Point: + return Point(point[0], point[1], point[2]) + + +def _is_component_key(value: object) -> bool: + if isinstance(value, bool): + return False + if isinstance(value, (int, str)): + return True + return isinstance(value, tuple) and all(_is_component_key(item) for item in value) + + +def _restore_component_key(value: object) -> object: + if isinstance(value, list): + return tuple(_restore_component_key(item) for item in value) + return value diff --git a/src/compas/scene/context.py b/src/compas/scene/context.py index 4bdf63798ec..08614b7c715 100644 --- a/src/compas/scene/context.py +++ b/src/compas/scene/context.py @@ -1,153 +1,171 @@ +from __future__ import annotations + import inspect -from collections import defaultdict +from collections.abc import Callable from typing import TYPE_CHECKING +from typing import Any from compas.data import Data from compas.plugins import pluggable -from compas.plugins import validate_plugin_implementation from .exceptions import SceneObjectNotRegisteredError +from .exceptions import SceneOperationNotRegisteredError if TYPE_CHECKING: + from .sceneannotation import SceneAnnotation from .sceneobject import SceneObject -ITEM_SCENEOBJECT: defaultdict[str | None, dict[type[Data], type["SceneObject"]]] = defaultdict(dict) - -@pluggable(category="drawing-utils") -def clear(guids: list[object] | None = None) -> None: - """Clear all or selected objects from the current visualization context. +SCENEOBJECT_TYPES: dict[type[Data], type["SceneObject"]] = {} +SCENE_OPERATIONS: dict[str, dict[type[SceneObject | SceneAnnotation], dict[str, Callable[..., Any]]]] = {} +_SCENEOBJECTS_DISCOVERED = False +_OPERATIONS_DISCOVERED = False - Parameters - ---------- - guids - The identifiers to clear. If `None`, clear the entire context. - """ +@pluggable(category="factories", selector="collect_all") +def register_scene_objects() -> None: + """Register stable semantic scene-object types.""" raise NotImplementedError -@pluggable(category="drawing-utils") -def before_draw() -> None: - """Perform context-specific operations before drawing a scene.""" - pass - - -@pluggable(category="drawing-utils") -def after_draw(drawn_objects: list[object]) -> None: - """Perform context-specific operations after drawing a scene. - - Parameters - ---------- - drawn_objects - The objects that were drawn. - - """ - pass - - @pluggable(category="factories", selector="collect_all") -def register_scene_objects() -> None: - """Register scene object types available in the current context.""" +def register_scene_operations() -> None: + """Register context-specific scene operations.""" raise NotImplementedError -def register(item_type: type[Data], sceneobject_type: "type[SceneObject]", context: str | None = None) -> None: - """Register a scene object type to a data type. +def register_sceneobject_type(item_type: type[Data], sceneobject_type: type["SceneObject"]) -> None: + """Register the stable scene-object type for a data type. Parameters ---------- item_type - The type of data item. + The represented data type. sceneobject_type - The compatible scene object type. - context - The visualization context in which to register the pair. + Its stable semantic scene-object type. + + Raises + ------ + ValueError + If another scene-object type is already registered for `item_type`. """ - ITEM_SCENEOBJECT[context][item_type] = sceneobject_type + existing = SCENEOBJECT_TYPES.get(item_type) + if existing is not None and existing is not sceneobject_type: + raise ValueError(f"A scene-object type is already registered for {item_type.__name__}.") + SCENEOBJECT_TYPES[item_type] = sceneobject_type -def detect_current_context() -> str | None: - """Select the only registered named visualization context, if available. +def get_sceneobject_cls(item: Data) -> type["SceneObject"]: + """Return the stable semantic scene-object type for an item. + + Parameters + ---------- + item + The represented data item. Returns ------- - str | None - The context name when exactly one named context is registered. - Otherwise, `None`. - - """ - - contexts = [name for name, registry in ITEM_SCENEOBJECT.items() if name is not None and registry] - return contexts[0] if len(contexts) == 1 else None - - -def _get_sceneobject_cls( - data: Data, - context: str | None = None, - sceneobject_type: "type[SceneObject] | None" = None, -) -> "type[SceneObject]": - # in any case user gets to override the choice - context_name = context or detect_current_context() + type[SceneObject] - dtype = type(data) - cls = None + Raises + ------ + SceneObjectNotRegisteredError + If no compatible stable type is registered. - if sceneobject_type is not None: - cls = sceneobject_type - else: - registry = ITEM_SCENEOBJECT[context_name] + """ + _ensure_sceneobjects_discovered() + for item_type in inspect.getmro(type(item)): + sceneobject_type = SCENEOBJECT_TYPES.get(item_type) + if sceneobject_type is not None: + return sceneobject_type + raise SceneObjectNotRegisteredError(f"No stable scene-object type is registered for {type(item).__name__}.") + + +def register_scene_operation( + context: str, + sceneobject_type: type[SceneObject | SceneAnnotation], + operation: str, + implementation: Callable[..., Any], +) -> None: + """Register one context-specific scene operation. - for type_ in inspect.getmro(dtype): - cls = registry.get(type_, None) - if cls is not None: - break + Parameters + ---------- + context + Stable visualization-context name. + sceneobject_type + Stable scene-object or annotation-entry type accepted by the + implementation. + operation + Operation name. Initially only `draw` and `clear` are supported. + implementation + Operation function. - if cls is None: - raise SceneObjectNotRegisteredError("No scene object is registered for this data type: {} in this context: {}".format(dtype, context_name)) + Raises + ------ + ValueError + If the key is invalid or already has another implementation. - return cls + """ + if not context: + raise ValueError("A scene-operation context should be a non-empty string.") + if operation not in {"draw", "clear"}: + raise ValueError("A scene operation should be 'draw' or 'clear'.") + operations = SCENE_OPERATIONS.setdefault(context, {}).setdefault(sceneobject_type, {}) + existing = operations.get(operation) + if existing is not None and existing is not implementation: + raise ValueError(f"Scene operation already registered: {context}/{sceneobject_type.__name__}/{operation}.") + operations[operation] = implementation -def get_sceneobject_cls( - item: Data | None, - context: str | None = None, - sceneobject_type: "type[SceneObject] | None" = None, - **kwargs: object, -) -> "type[SceneObject]": - """Get the registered scene object type for an item. +def get_scene_operation(context: str, sceneobject_type: type[SceneObject | SceneAnnotation], operation: str) -> Callable[..., Any]: + """Resolve a scene operation using stable-type MRO fallback. Parameters ---------- - item - The item to represent. context - The visualization context used for registration lookup. + Visualization-context name. sceneobject_type - An explicit scene object type overriding registration lookup. - **kwargs - Additional scene object options, ignored during type selection. + Concrete stable scene-object or annotation-entry type. + operation + Operation name. Returns ------- - type[SceneObject] - The selected scene object type. + Callable[..., Any] Raises ------ - ValueError - If `item` is `None`. - SceneObjectNotRegisteredError - If no compatible scene object type is registered. + SceneOperationNotRegisteredError + If the context has no compatible implementation. """ - if not ITEM_SCENEOBJECT: + _ensure_operations_discovered() + registry = SCENE_OPERATIONS.get(context, {}) + for candidate in inspect.getmro(sceneobject_type): + implementation = registry.get(candidate, {}).get(operation) + if implementation is not None: + return implementation + raise SceneOperationNotRegisteredError(context, sceneobject_type, operation) + + +def detect_current_context() -> str | None: + """Return the only registered visualization context, if unambiguous.""" + _ensure_operations_discovered() + contexts = [context for context, registry in SCENE_OPERATIONS.items() if registry] + return contexts[0] if len(contexts) == 1 else None + + +def _ensure_sceneobjects_discovered() -> None: + global _SCENEOBJECTS_DISCOVERED + if not _SCENEOBJECTS_DISCOVERED: register_scene_objects() + _SCENEOBJECTS_DISCOVERED = True - if item is None: - raise ValueError("Cannot create a scene object for None. Please ensure you pass a instance of a supported class.") - cls = _get_sceneobject_cls(item, context=context, sceneobject_type=sceneobject_type) - validate_plugin_implementation(cls) - return cls +def _ensure_operations_discovered() -> None: + global _OPERATIONS_DISCOVERED + if not _OPERATIONS_DISCOVERED: + register_scene_operations() + _OPERATIONS_DISCOVERED = True diff --git a/src/compas/scene/descriptors/color.py b/src/compas/scene/descriptors/color.py index 728060e625e..15db66d8b32 100644 --- a/src/compas/scene/descriptors/color.py +++ b/src/compas/scene/descriptors/color.py @@ -84,5 +84,5 @@ def __set__(self, obj: object, value: ColorInput) -> None: """ if value is None: return - - setattr(obj, self.private_name, Color.coerce(value)) + color = Color.coerce(value) + setattr(obj, self.private_name, color) diff --git a/src/compas/scene/exceptions.py b/src/compas/scene/exceptions.py index 4851a67fe14..03ede226232 100644 --- a/src/compas/scene/exceptions.py +++ b/src/compas/scene/exceptions.py @@ -1,2 +1,25 @@ class SceneObjectNotRegisteredError(Exception): """Exception that is raised when no scene object is registered for a given data type.""" + + +class SceneItemNotBoundError(LookupError): + """Raised when an operation requires an unresolved scene item reference.""" + + def __init__(self, object_guid: object, item_guid: object) -> None: + super().__init__(f"Scene object {object_guid} requires unbound item {item_guid}.") + self.object_guid = object_guid + self.item_guid = item_guid + + +class SceneStateError(ValueError): + """Raised when declared durable scene state is invalid.""" + + +class SceneOperationNotRegisteredError(LookupError): + """Raised when a visualization context has no compatible operation.""" + + def __init__(self, context: str, sceneobject_type: type[object], operation: str) -> None: + super().__init__(f"No '{operation}' scene operation is registered for {sceneobject_type.__name__} in context '{context}'.") + self.context = context + self.sceneobject_type = sceneobject_type + self.operation = operation diff --git a/src/compas/scene/frameobject.py b/src/compas/scene/frameobject.py new file mode 100644 index 00000000000..eed38dd5983 --- /dev/null +++ b/src/compas/scene/frameobject.py @@ -0,0 +1,22 @@ +from typing import Any + +from .geometryobject import GeometryObject +from .sceneobject import SceneStateField + + +class FrameObject(GeometryObject): + """Scene object for a frame. + + Parameters + ---------- + size + Display size of the frame axes. + + """ + + __scene_state_namespace__ = "compas.scene.FrameObject" + __scene_state_fields__ = (SceneStateField("size", (int, float), default=1.0, required=False),) + + def __init__(self, size: float = 1.0, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.size = size diff --git a/src/compas/scene/geometryobject.py b/src/compas/scene/geometryobject.py index 416e9019950..1ddb8d9cdc3 100644 --- a/src/compas/scene/geometryobject.py +++ b/src/compas/scene/geometryobject.py @@ -6,6 +6,7 @@ from .descriptors.color import ColorAttribute from .sceneobject import SceneObject +from .sceneobject import SceneStateField class GeometryObject(SceneObject): @@ -14,6 +15,17 @@ class GeometryObject(SceneObject): pointcolor = ColorAttribute() linecolor = ColorAttribute() surfacecolor = ColorAttribute() + __scene_state_namespace__ = "compas.scene.GeometryObject" + __scene_state_fields__ = ( + SceneStateField("show_points", bool, default=False, required=False, editable=True), + SceneStateField("show_lines", bool, default=True, required=False, editable=True), + SceneStateField("show_surfaces", bool, default=True, required=False, editable=True), + SceneStateField("pointcolor", (Color, type(None)), default=None, required=False, editable=True), + SceneStateField("linecolor", (Color, type(None)), default=None, required=False, editable=True), + SceneStateField("surfacecolor", (Color, type(None)), default=None, required=False, editable=True), + SceneStateField("linewidth", (int, float), default=1.0, required=False, editable=True), + SceneStateField("pointsize", (int, float), default=1.0, required=False, editable=True), + ) # ========================================================================== # Dunder methods diff --git a/src/compas/scene/graphobject.py b/src/compas/scene/graphobject.py index 4937a2b95a8..84b1bc39153 100644 --- a/src/compas/scene/graphobject.py +++ b/src/compas/scene/graphobject.py @@ -11,6 +11,7 @@ from .descriptors.colordict import ColorDictAttribute from .sceneobject import SceneObject +from .sceneobject import SceneStateField class GraphObject(SceneObject): @@ -25,6 +26,15 @@ class GraphObject(SceneObject): nodecolor = ColorDictAttribute() edgecolor = ColorDictAttribute() + __scene_state_namespace__ = "compas.scene.GraphObject" + __scene_state_fields__ = ( + SceneStateField("show_nodes", (bool, list), default=True, required=False, editable=True), + SceneStateField("show_edges", (bool, list), default=True, required=False, editable=True), + SceneStateField("nodecolor", required=False, editable=True), + SceneStateField("edgecolor", required=False, editable=True), + SceneStateField("edgewidth", (int, float), default=1.0, required=False, editable=True), + SceneStateField("nodesize", (int, float), default=1.0, required=False, editable=True), + ) # ========================================================================== # Dunder methods @@ -54,18 +64,6 @@ def __init__( # Properties # ========================================================================== - @property - def settings(self) -> dict[str, object]: - """The settings required to reconstruct the graph scene object.""" - settings = super().settings - settings["show_nodes"] = self.show_nodes - settings["show_edges"] = self.show_edges - settings["nodecolor"] = self.nodecolor - settings["edgecolor"] = self.edgecolor - settings["nodesize"] = self.nodesize - settings["edgewidth"] = self.edgewidth - return settings - @property def graph(self) -> Graph: """The graph represented by this scene object. @@ -80,10 +78,10 @@ def graph(self) -> Graph: def graph(self, graph: Graph) -> None: if self.scene is None: self._item_guid = graph.guid - self._detached_item = graph + self._item = graph else: self.scene.replace_item(self, graph) - self._transformation = None + self.transformation = None self._node_xyz = None self._node_xyz_revision = None @@ -111,57 +109,6 @@ def node_xyz(self, node_xyz: dict[Hashable, list[RealInput]]) -> None: self._node_xyz = node_xyz self._node_xyz_revision = None - # ========================================================================== - # Methods - # ========================================================================== - - def draw_nodes(self) -> list[object]: - """Draw the nodes of the graph. - - Nodes are drawn based on the values of - - * `self.show_nodes` - * `self.nodecolor` - * `self.nodesize` - - Returns - ------- - list[object] - The identifiers of the objects representing the nodes in the visualization context. - - """ - raise NotImplementedError - - def draw_edges(self) -> list[object]: - """Draw the edges of the graph. - - Edges are drawn based on the values of - - * `self.show_edges` - * `self.edgecolor` - * `self.edgewidth` - - Returns - ------- - list[object] - The identifiers of the objects representing the edges in the visualization context. - - """ - raise NotImplementedError - - def clear_nodes(self) -> None: - """Clear the nodes of the graph.""" - raise NotImplementedError - - def clear_edges(self) -> None: - """Clear the edges of the graph.""" - raise NotImplementedError - - def clear(self) -> None: - """Clear the nodes and edges of the graph.""" - self.clear_nodes() - self.clear_edges() - # ========================================================================== # Private helpers # ========================================================================== diff --git a/src/compas/scene/group.py b/src/compas/scene/group.py index f3f725b4693..4c38ea101ac 100644 --- a/src/compas/scene/group.py +++ b/src/compas/scene/group.py @@ -1,5 +1,4 @@ from typing import Any -from typing import Self from compas.data import Data @@ -7,97 +6,24 @@ class Group(SceneObject): - """A group of scene objects. + """Stable scene object used to group hierarchy entries. Parameters ---------- name - The name of the group. + The group name. **kwargs - Default keyword arguments passed to child scene objects. - - Examples - -------- - >>> from compas.scene import Scene - >>> from compas.scene import Group - >>> from compas.geometry import Point - >>> scene = Scene() - >>> group = Group(name="My Group") - >>> _ = scene.add(group) - >>> point = Point(0, 0, 0) - >>> _ = group.add(point) - >>> len(scene.objects) - 2 + Durable group presentation state. """ - # ========================================================================== - # Data - # ========================================================================== - - @property - def __data__(self) -> dict[str, object]: - data = { - "settings": self.settings, - "children": [child.__data__ for child in self.children], - } - return data - - # ========================================================================== - # Dunder methods - # ========================================================================== - - def __new__(cls, *args: Any, **kwargs: Any) -> Self: - # overwriting __new__ to revert to the default behavior of normal object, So an instance can be created directly without providing a registered item. - return object.__new__(cls) - - def __init__(self, name: str, **kwargs: Any) -> None: + def __init__(self, name: str = "Group", **kwargs: Any) -> None: super().__init__(name=name, **kwargs) - self.kwargs = kwargs - - # ========================================================================== - # Methods - # ========================================================================== def add(self, item: Data, **kwargs: Any) -> SceneObject: - """Add a child item to the group, using the group's kwargs as default values for the child sceneobject. - - Parameters - ---------- - item - The item to add. - **kwargs - Additional keyword arguments to create the scene object for the item. - - Returns - ------- - SceneObject - The scene object associated with the added item. - - """ - group_kwargs = self.kwargs.copy() - group_kwargs.update(kwargs) - kwargs = group_kwargs + """Add a child item with explicitly supplied presentation state.""" return super().add(item, **kwargs) def add_from_list(self, items: list[Data], **kwargs: Any) -> list[SceneObject]: - """Add a list of items to the group, using the group's kwargs as default values for the child sceneobject. - - Parameters - ---------- - items - The items to add. - **kwargs - Additional keyword arguments to create the scene object for the items. - - Returns - ------- - list[SceneObject] - The scene objects associated with the added items. - - """ - sceneobjects = [] - for item in items: - sceneobject = self.add(item, **kwargs) - sceneobjects.append(sceneobject) - return sceneobjects + """Add multiple child items with the same explicit presentation state.""" + return [self.add(item, **kwargs) for item in items] diff --git a/src/compas/scene/meshobject.py b/src/compas/scene/meshobject.py index c5595791ea3..b18c514a19b 100644 --- a/src/compas/scene/meshobject.py +++ b/src/compas/scene/meshobject.py @@ -8,6 +8,7 @@ from .descriptors.colordict import ColorDictAttribute from .sceneobject import SceneObject +from .sceneobject import SceneStateField class MeshObject(SceneObject): @@ -23,6 +24,19 @@ class MeshObject(SceneObject): vertexcolor = ColorDictAttribute() edgecolor = ColorDictAttribute() facecolor = ColorDictAttribute() + __scene_state_namespace__ = "compas.scene.MeshObject" + __scene_state_fields__ = ( + SceneStateField("show_vertices", (bool, list), default=False, required=False, editable=True), + SceneStateField("show_edges", (bool, list), default=False, required=False, editable=True), + SceneStateField("show_faces", (bool, list), default=True, required=False, editable=True), + SceneStateField("vertexcolor", required=False, editable=True), + SceneStateField("edgecolor", required=False, editable=True), + SceneStateField("facecolor", required=False, editable=True), + SceneStateField("edgewidth", (int, float), default=1.0, required=False, editable=True), + SceneStateField("vertexsize", (int, float), default=1.0, required=False, editable=True), + SceneStateField("hide_coplanaredges", bool, default=False, required=False), + SceneStateField("use_vertexcolors", bool, default=False, required=False), + ) # ========================================================================== # Dunder methods @@ -38,6 +52,8 @@ def __init__( facecolor: Mapping[Any, ColorInput] | Color | None = None, vertexsize: float = 1.0, edgewidth: float = 1.0, + hide_coplanaredges: bool = False, + use_vertexcolors: bool = False, **kwargs: Any, ) -> None: super().__init__(**kwargs) @@ -49,27 +65,13 @@ def __init__( self.facecolor = facecolor or self.color self.vertexsize = vertexsize self.edgewidth = edgewidth + self.hide_coplanaredges = hide_coplanaredges + self.use_vertexcolors = use_vertexcolors # ========================================================================== # Properties # ========================================================================== - @property - def settings(self) -> dict[str, object]: - """The settings required to reconstruct the mesh scene object.""" - settings = super().settings - # perhaps this should be renamed to just "vertices", "edges", "faces" - settings["show_vertices"] = self.show_vertices - settings["show_edges"] = self.show_edges - settings["show_faces"] = self.show_faces - # end of perhaps - settings["vertexcolor"] = self.vertexcolor - settings["edgecolor"] = self.edgecolor - settings["facecolor"] = self.facecolor - settings["vertexsize"] = self.vertexsize - settings["edgewidth"] = self.edgewidth - return settings - @property def mesh(self) -> Mesh: """The mesh represented by this scene object. @@ -83,73 +85,7 @@ def mesh(self) -> Mesh: def mesh(self, mesh: Mesh) -> None: if self.scene is None: self._item_guid = mesh.guid - self._detached_item = mesh + self._item = mesh else: self.scene.replace_item(self, mesh) - self._transformation = None - - # ========================================================================== - # Methods - # ========================================================================== - - def draw_vertices(self) -> list[object]: - """Draw the vertices of the mesh. - - Vertices are drawn based on the values of - - * `self.show_vertices` - * `self.vertexcolor` - * `self.vertexsize` - - Returns - ------- - list[object] - The identifiers of the objects representing the vertices in the visualization context. - - """ - raise NotImplementedError - - def draw_edges(self) -> list[object]: - """Draw the edges of the mesh. - - Edges are drawn based on the values of - - * `self.show_edges` - * `self.edgecolor` - * `self.edgewidth` - - Returns - ------- - list[object] - The identifiers of the objects representing the edges in the visualization context. - - """ - raise NotImplementedError - - def draw_faces(self) -> list[object]: - """Draw the faces of the mesh. - - Faces are drawn based on the values of - - * `self.show_faces` - * `self.facecolor` - - Returns - ------- - list[object] - The identifiers of the objects representing the faces in the visualization context. - - """ - raise NotImplementedError - - def clear_vertices(self) -> None: - """Clear the vertices of the mesh.""" - raise NotImplementedError - - def clear_edges(self) -> None: - """Clear the edges of the mesh.""" - raise NotImplementedError - - def clear_faces(self) -> None: - """Clear the faces of the mesh.""" - raise NotImplementedError + self.transformation = None diff --git a/src/compas/scene/planeobject.py b/src/compas/scene/planeobject.py new file mode 100644 index 00000000000..7088ec22f14 --- /dev/null +++ b/src/compas/scene/planeobject.py @@ -0,0 +1,30 @@ +from typing import Any +from typing import cast + +from compas.geometry import Plane + +from .geometryobject import GeometryObject +from .sceneobject import SceneStateField + + +class PlaneObject(GeometryObject): + """Scene object for a plane. + + Parameters + ---------- + size + Display size of the plane. + + """ + + __scene_state_namespace__ = "compas.scene.PlaneObject" + __scene_state_fields__ = (SceneStateField("size", (int, float), default=1.0, required=False),) + + def __init__(self, size: float = 1.0, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.size = size + + @property + def plane(self) -> Plane: + """The plane represented by this scene object.""" + return cast(Plane, self.item) diff --git a/src/compas/scene/scene.py b/src/compas/scene/scene.py index 9621339c11d..06146b4ea0c 100644 --- a/src/compas/scene/scene.py +++ b/src/compas/scene/scene.py @@ -1,3 +1,6 @@ +from __future__ import annotations + +from collections.abc import Iterable from collections.abc import Iterator from collections.abc import Mapping from types import MappingProxyType @@ -14,11 +17,16 @@ from compas.datastructures import Tree from ._scenenode import SceneNode -from .context import after_draw -from .context import before_draw -from .context import clear +from .annotations import ArrowAnnotation +from .annotations import DistanceDimension +from .annotations import TextAnnotation from .context import detect_current_context +from .context import get_scene_operation +from .context import get_sceneobject_cls +from .exceptions import SceneItemNotBoundError from .group import Group +from .sceneannotation import DimensionStyle +from .sceneannotation import SceneAnnotation from .sceneobject import SceneObject if TYPE_CHECKING: @@ -26,465 +34,710 @@ class Scene(Data): - """A hierarchical collection of objects to visualize in a context. + """Backend-neutral spatial hierarchy and ordered annotations. + + Referenced data items remain independently serializable and are bound by + GUID. Spatial scene objects belong to the hierarchy. Annotation entries + belong to a separate flat collection. Visualization backends provide + context-keyed `draw` and `clear` operations without replacing durable + scene types. Parameters ---------- name - The name of the scene. + Scene name. context - The visualization context. If omitted, COMPAS selects the only - registered named context when one is available. - - Examples - -------- - >>> from compas.scene import Scene - >>> from compas.geometry import Box - >>> scene = Scene() - >>> box = Box.from_width_height_depth(1, 1, 1) - >>> boxobj = scene.add(box) - >>> scene.draw() # doctest: +SKIP + Optional default runtime visualization context. """ - # ========================================================================== - # Data - # ========================================================================== + SCHEMA_VERSION = 3 @property def __data__(self) -> dict[str, Any]: - def node_data(node: SceneNode) -> dict[str, Any]: - sceneobject = self._objects[node.object_guid] - data = { - "settings": sceneobject.settings, - "children": [node_data(child) for child in node.children], - } - if sceneobject.item_guid is not None: - data["item"] = str(sceneobject.item_guid) - return data - - root = self.tree.root - if root is None: - raise RuntimeError("The scene tree has no root node.") - item_guids = {sceneobject.item_guid for sceneobject in self.objects if sceneobject.item_guid is not None} + """Return stable scene objects plus hierarchy references.""" return { + "version": self.SCHEMA_VERSION, "name": self.name, - "root": node_data(root), - "items": [item for guid, item in self._items.items() if guid in item_guids], + "objects": [self._objects[node.object_guid] for node in self.tree.nodes], + "hierarchy": self.root_node.__data__, + "annotations": list(self._annotations), } @classmethod def __from_data__(cls, data: dict[str, Any]) -> Self: - scene = cls(data["name"]) - items = {str(item.guid): item for item in data["items"]} - - def add(node, parent, items): - for child_node in node.get("children", []): - settings = child_node["settings"] - if "item" in child_node: - guid = child_node["item"] - sceneobject = scene.add(items[guid], parent=parent, **settings) - else: - sceneobject = scene.add_group(parent=parent, **settings) - add(child_node, sceneobject, items) - - add(data["root"], scene.root, items) - - return scene - - # ========================================================================== - # Dunder methods - # ========================================================================== - - def __init__(self, name: str = "Scene", context: str | None = None) -> None: + """Construct an unresolved scene without visualization plugins.""" + expected = {"version", "name", "objects", "hierarchy", "annotations"} + unknown = set(data) - expected + if unknown: + raise ValueError("Unknown scene fields: {}.".format(", ".join(sorted(unknown)))) + missing = expected - set(data) + if missing: + raise ValueError("Missing scene fields: {}.".format(", ".join(sorted(missing)))) + if data["version"] != cls.SCHEMA_VERSION: + raise ValueError(f"Unsupported scene schema version: {data['version']}.") + if not isinstance(data["name"], str): + raise TypeError("Scene name should be a string.") + if not isinstance(data["objects"], list) or not all(isinstance(obj, SceneObject) for obj in data["objects"]): + raise TypeError("Scene objects should be a list of SceneObject values.") + if not isinstance(data["annotations"], list) or not all(isinstance(entry, SceneAnnotation) for entry in data["annotations"]): + raise TypeError("Scene annotations should be a list of SceneAnnotation values.") + objects: dict[UUID, SceneObject] = {} + for obj in data["objects"]: + if obj.guid in objects: + raise ValueError(f"Duplicate scene-object GUID: {obj.guid}.") + objects[obj.guid] = obj + annotation_guids: set[UUID] = set() + for entry in data["annotations"]: + if entry.guid in annotation_guids: + raise ValueError(f"Duplicate scene-annotation GUID: {entry.guid}.") + if entry.guid in objects: + raise ValueError(f"Scene GUID is shared by an object and annotation: {entry.guid}.") + annotation_guids.add(entry.guid) + root = SceneNode.__from_data__(data["hierarchy"]) + return cls( + data["name"], + context=None, + _detect_context=False, + _objects=objects, + _root=root, + _annotations=data["annotations"], + ) + + def __init__( + self, + name: str = "Scene", + context: str | None = None, + *, + _detect_context: bool = True, + _objects: dict[UUID, SceneObject] | None = None, + _root: SceneNode | None = None, + _annotations: list[SceneAnnotation] | None = None, + ) -> None: super().__init__(name=name) - self.context = context or detect_current_context() + self.context = context if context is not None or not _detect_context else detect_current_context() self._items: dict[UUID, Data] = {} - self._objects: dict[UUID, SceneObject] = {} + self._objects: dict[UUID, SceneObject] = _objects or {} + self._annotations: list[SceneAnnotation] = list(_annotations or []) + self._annotation_index: dict[UUID, SceneAnnotation] = {} self._nodes: dict[UUID, SceneNode] = {} + self._resources: dict[str, dict[UUID, tuple[object | None, list[object]]]] = {} self.tree: Tree[SceneNode] = Tree(name=name) - root = Group(name="ROOT", context=self.context) - self._attach(root, parent=None) + if _root is None: + root_object = Group(name="ROOT") + self._objects[root_object.guid] = root_object + _root = SceneNode(root_object.guid) + self.tree.add(_root) + self._index_nodes() + if set(self._objects) != set(self._nodes): + raise ValueError("Scene objects and hierarchy references should match exactly.") + if not isinstance(self.root, Group): + raise ValueError("The scene root should reference a Group.") + for obj in self._objects.values(): + obj._scene = self + for entry in self._annotations: + if entry.guid in self._objects or entry.guid in self._annotation_index: + raise ValueError(f"Duplicate scene element GUID: {entry.guid}.") + self._annotation_index[entry.guid] = entry + entry._scene = self def __str__(self) -> str: return str(self.tree) - # ========================================================================== - # Properties - # ========================================================================== + @property + def root_node(self) -> SceneNode: + """Return the hierarchy root node.""" + if self.tree.root is None: + raise RuntimeError("The scene hierarchy has no root.") + return self.tree.root @property def root(self) -> Group: - """The root group of the scene tree.""" - node = self.tree.root - if node is None: - raise RuntimeError("The scene tree has no root group.") - return cast(Group, self._objects[node.object_guid]) + """Return the stable root group.""" + return cast(Group, self._objects[self.root_node.object_guid]) @property - def nodes(self) -> Iterator[SceneObject]: - """An iterator over all nodes in the scene tree, including the root.""" - return (self._objects[node.object_guid] for node in self.tree.nodes) + def nodes(self) -> Iterator[SceneNode]: + """Iterate over hierarchy nodes, including the root.""" + return iter(self.tree.nodes) @property def objects(self) -> list[SceneObject]: - """All scene objects except the private root group.""" + """Return non-root scene objects in hierarchy order.""" return [self._objects[node.object_guid] for node in self.tree.nodes if not node.is_root] + @property + def annotations(self) -> tuple[SceneAnnotation, ...]: + """Return annotation entries in durable collection order. + + Returns + ------- + tuple[SceneAnnotation, ...] + The immutable ordered view of the scene annotation entries. + + """ + return tuple(self._annotations) + @property def item_store(self) -> Mapping[UUID, Data]: - """The read-only GUID-to-data mapping owned by the scene.""" + """Return read-only runtime item bindings.""" return MappingProxyType(self._items) @property def object_store(self) -> Mapping[UUID, SceneObject]: - """The read-only GUID-to-scene-object mapping owned by the scene.""" + """Return read-only durable scene-object storage.""" return MappingProxyType(self._objects) - @property - def context_objects(self) -> list[object]: - """The identifiers of all objects drawn in the visualization context.""" - guids: list[object] = [] - for obj in self.objects: - guids += obj.guids - return guids - - # ========================================================================== - # Constructors - # ========================================================================== - @classmethod def from_gltf(cls, document: "GLTFDocument", scene_key: int | None = None) -> Self: - """Construct a COMPAS scene from a glTF document. + """Construct a scene from a glTF document.""" + from compas.files.gltf.gltf_conversions import gltf_to_scene + + return gltf_to_scene(document, scene_key, scene_type=cls) + + def to_gltf(self) -> "GLTFDocument": + """Convert the scene to a glTF document.""" + from compas.files.gltf.gltf_conversions import scene_to_gltf + + return scene_to_gltf(self) + + def bind(self, item: Data) -> None: + """Bind an independently loaded item to every matching scene reference. + + Spatial objects and annotation entries resolve items through the same + GUID-indexed runtime store. Annotation entries additionally verify that + the item is supported and that any durable style matches its type. Parameters ---------- - document - Source glTF document. - scene_key - Scene to convert. By default, use the document's default or first scene. - - Returns - ------- - Scene - Converted scene. + item + Independently loaded data item referenced by the scene. + + Raises + ------ + KeyError + If no spatial object or annotation entry references the item GUID. + TypeError + If an annotation item is referenced from the spatial hierarchy, or + an annotation entry references a non-annotation item. + ValueError + If a different item with the same GUID is already bound, or a + dimension style is attached to an unsupported annotation type. """ - from compas.files.gltf.gltf_conversions import gltf_to_scene + if item.guid not in self._referenced_item_guids(): + raise KeyError(f"Scene does not reference item {item.guid}.") + existing = self._items.get(item.guid) + if existing is not None and existing is not item: + raise ValueError(f"A different data item with GUID {item.guid} is already bound.") + entries = [entry for entry in self._annotations if entry.item_guid == item.guid] + if any(obj.item_guid == item.guid for obj in self._objects.values()): + self._validate_spatial_binding(item) + for entry in entries: + self._validate_annotation_binding(entry, item) + self._items[item.guid] = item + for entry in entries: + self._normalize_annotation_style(entry, item) - return gltf_to_scene(document, scene_key, scene_type=cls) + def bind_many(self, items: Iterable[Data]) -> None: + """Bind multiple independently loaded items atomically. - # ========================================================================== - # Conversions - # ========================================================================== + Validation covers both spatial-object and annotation-entry references. + No binding or default-style normalization is applied unless every item + is valid. - def to_gltf(self) -> "GLTFDocument": - """Convert this scene to a glTF document. + Parameters + ---------- + items + Independently loaded data items referenced by the scene. + + Raises + ------ + KeyError + If any item GUID is not referenced by the scene. + TypeError + If any item is referenced from the wrong scene domain. + ValueError + If a different item with the same GUID is already bound, or an + annotation style is incompatible with its item. + + """ + staged = dict(self._items) + references = self._referenced_item_guids() + annotation_items: list[tuple[SceneAnnotation, Data]] = [] + for item in items: + if item.guid not in references: + raise KeyError(f"Scene does not reference item {item.guid}.") + existing = staged.get(item.guid) + if existing is not None and existing is not item: + raise ValueError(f"A different data item with GUID {item.guid} is already bound.") + if any(obj.item_guid == item.guid for obj in self._objects.values()): + self._validate_spatial_binding(item) + for entry in self._annotations: + if entry.item_guid == item.guid: + self._validate_annotation_binding(entry, item) + annotation_items.append((entry, item)) + staged[item.guid] = item + self._items = staged + for entry, item in annotation_items: + self._normalize_annotation_style(entry, item) + + def item(self, guid: UUID, *, object_guid: UUID | None = None) -> Data: + """Return a bound item or raise a precise unresolved-reference error.""" + try: + return self._items[guid] + except KeyError: + raise SceneItemNotBoundError(object_guid or "unknown", guid) from None + + def object(self, reference: SceneNode | UUID) -> SceneObject: + """Return a stable scene object by node or GUID.""" + guid = reference.object_guid if isinstance(reference, SceneNode) else reference + return self._objects[guid] + + def annotation(self, guid: UUID) -> SceneAnnotation: + """Return a scene annotation by its stable entry GUID. - Unsupported scene items are omitted with a warning. + Parameters + ---------- + guid + Annotation-entry GUID. Returns ------- - GLTFDocument - Converted document. - - """ - from compas.files.gltf.gltf_conversions import scene_to_gltf + SceneAnnotation + The matching durable annotation entry. - return scene_to_gltf(self) + Raises + ------ + KeyError + If the scene has no annotation with the given GUID. - # ========================================================================== - # Methods - # ========================================================================== + """ + return self._annotation_index[guid] + + def node(self, object_guid: UUID) -> SceneNode: + """Return the hierarchy node for a scene-object GUID.""" + return self._nodes[object_guid] + + def add(self, item: Data, parent: SceneObject | SceneNode | None = None, **kwargs: Any) -> SceneObject: + """Create and attach the stable semantic scene object for an item.""" + if isinstance(item, (TextAnnotation, ArrowAnnotation, DistanceDimension)): + raise TypeError("Annotations must be added with Scene.add_annotation().") + if not isinstance(item, Data): + raise TypeError("Scene.add expects a Data item. Use add_object for an existing scene object.") + sceneobject_type = get_sceneobject_cls(item) + return self.add_object(sceneobject_type(item=item, **kwargs), parent=parent) + + def add_object(self, sceneobject: SceneObject, parent: SceneObject | SceneNode | None = None) -> SceneObject: + """Attach an existing stable scene object explicitly.""" + if not isinstance(sceneobject, SceneObject): + raise TypeError("Expected a SceneObject.") + if sceneobject._item is not None: + self._validate_spatial_binding(sceneobject._item) + if sceneobject.scene is not None: + raise ValueError("The scene object already belongs to a scene.") + if sceneobject.guid in self._objects or sceneobject.guid in self._annotation_index: + raise ValueError(f"Scene object {sceneobject.guid} is already stored.") + parent_node = self._parent_node(parent) + node = SceneNode(sceneobject.guid) + self.tree.add(node, parent=parent_node) + self._nodes[sceneobject.guid] = node + self._objects[sceneobject.guid] = sceneobject + sceneobject._scene = self + if sceneobject.item_guid is not None and sceneobject._item is not None: + try: + self.bind(sceneobject._item) + except Exception: + self.tree.remove(node) + del self._nodes[sceneobject.guid] + del self._objects[sceneobject.guid] + sceneobject._scene = None + raise + return sceneobject - def add( + def add_reference( self, - item: Data | SceneObject, - parent: SceneObject | None = None, + item_guid: UUID, + *, + name: str, + parent: SceneObject | SceneNode | None = None, + object_type: type[SceneObject] = SceneObject, **kwargs: Any, ) -> SceneObject: - """Add an item to the scene. + """Create and attach an unresolved stable scene object.""" + return self.add_object(object_type(item_guid=item_guid, name=name, **kwargs), parent=parent) + + def add_group(self, name: str, parent: SceneObject | SceneNode | None = None, **kwargs: Any) -> Group: + """Create and attach a stable group object.""" + return cast(Group, self.add_object(Group(name=name, **kwargs), parent=parent)) + + def add_annotation( + self, + item: TextAnnotation | ArrowAnnotation | DistanceDimension, + *, + name: str | None = None, + show: bool = True, + style: DimensionStyle | None = None, + ) -> SceneAnnotation: + """Create and attach one annotation entry. Parameters ---------- item - The item to add. - parent - The parent scene object. The root group is used by default. - **kwargs - Additional keyword arguments to create the scene object for the item. + Independently serializable annotation data. + name + Entry name. + show + Whether the annotation is visible. + style + Optional distance-dimension style. Distance entries receive a + default style when omitted. Returns ------- - SceneObject - The scene object associated with the item. + SceneAnnotation + The attached durable annotation entry. - """ + Raises + ------ + TypeError + If the item, visibility, or style has the wrong type. + ValueError + If the style is incompatible with the annotation item. - parent = parent or self.root - - if parent.scene is not self: - raise ValueError("The parent scene object does not belong to this scene.") - - if isinstance(item, SceneObject): - sceneobject = item - if sceneobject.scene is not None: - raise ValueError("The scene object already belongs to a scene.") - else: - if isinstance(parent, Group): - # Use the parent group's settings as defaults for the child. - group_kwargs = parent.kwargs.copy() - group_kwargs.update(kwargs) - kwargs = group_kwargs - if "context" in kwargs: - if kwargs["context"] != self.context: - raise Exception("Object context should be the same as scene context: {} != {}".format(kwargs["context"], self.context)) - del kwargs["context"] # otherwist the SceneObject receives "context" twice, which results in an error - sceneobject = SceneObject(item=item, context=self.context, **kwargs) - self._attach(sceneobject, parent=parent) - return sceneobject + """ + return self.add_annotation_entry(SceneAnnotation(item, name=name, show=show, style=style)) - def add_group( - self, - name: str, - parent: SceneObject | None = None, - **kwargs: Any, - ) -> Group: - """Add a group to the scene. + def add_annotation_entry(self, entry: SceneAnnotation) -> SceneAnnotation: + """Attach an existing detached annotation entry. Parameters ---------- - name - The name of the group. - parent - The parent scene object. The root group is used by default. - **kwargs - Default keyword arguments passed to children of the group. + entry + Detached annotation entry to attach without copying. Returns ------- - Group - The added group. + SceneAnnotation + The same attached entry. + + Raises + ------ + TypeError + If `entry` is not a `SceneAnnotation`, or its resolved item belongs + to the spatial hierarchy. + ValueError + If the entry already belongs to a scene, its GUID collides with + another scene element, or its style is incompatible with its item. """ - group = Group(name=name, **kwargs) - self.add(group, parent=parent) - return group - - def remove(self, sceneobject: SceneObject) -> None: - """Remove a scene object and its descendants from the scene. + if not isinstance(entry, SceneAnnotation): + raise TypeError("Expected a SceneAnnotation.") + if entry.scene is not None: + raise ValueError("The scene annotation already belongs to a scene.") + if entry.guid in self._objects or entry.guid in self._annotation_index: + raise ValueError(f"Scene annotation {entry.guid} is already stored.") + self._annotations.append(entry) + self._annotation_index[entry.guid] = entry + entry._scene = self + if entry._item is not None: + try: + self.bind(entry._item) + except Exception: + self._annotations.remove(entry) + del self._annotation_index[entry.guid] + entry._scene = None + raise + return entry + + def add_annotation_reference( + self, + item_guid: UUID, + *, + name: str, + show: bool = True, + style: DimensionStyle | None = None, + ) -> SceneAnnotation: + """Create and attach an unresolved annotation entry. Parameters ---------- - sceneobject - The scene object to remove. + item_guid + GUID of the independently stored annotation item. + name + Entry name available before the item is bound. + show + Whether the annotation is visible. + style + Optional distance-dimension style. A reference with no style stays + unstyled until binding identifies a distance dimension. + + Returns + ------- + SceneAnnotation + The attached unresolved entry. + + Raises + ------ + TypeError + If the item GUID, visibility, or style has the wrong type. + ValueError + If the generated entry GUID collides with another scene element. """ - if sceneobject.scene is not self: + return self.add_annotation_entry(SceneAnnotation(item_guid=item_guid, name=name, show=show, style=style)) + + def remove(self, sceneobject: SceneObject | SceneNode) -> None: + """Remove an object hierarchy while preserving stable object identity.""" + node = sceneobject if isinstance(sceneobject, SceneNode) else self.node(sceneobject.guid) + if node.object_guid not in self._nodes: raise ValueError("The scene object does not belong to this scene.") - if sceneobject is self.root: + if node.is_root: raise ValueError("The root group cannot be removed.") - - node = self._nodes[sceneobject.guid] removed_nodes = list(node.traverse()) + for removed_node in removed_nodes: + obj = self._objects[removed_node.object_guid] + for context_name, resources in tuple(self._resources.items()): + if obj.guid in resources: + self.clear_object(obj, context=context_name) self.tree.remove(node) for removed_node in removed_nodes: - removed = self._objects.pop(removed_node.object_guid) - self._nodes.pop(removed.guid) - removed._detached_item = self._items.get(removed.item_guid) if removed.item_guid is not None else None - removed._scene = None + obj = self._objects.pop(removed_node.object_guid) + self._nodes.pop(removed_node.object_guid) + obj._item = self._items.get(obj.item_guid) if obj.item_guid is not None else None + obj._scene = None self._prune_items() - def replace_item(self, sceneobject: SceneObject, item: Data) -> None: - """Replace the data item represented by a scene object. + def remove_annotation(self, entry: SceneAnnotation | UUID) -> None: + """Remove an annotation entry while preserving its identity and state. + + Runtime context resources are cleared and an unreferenced item binding + is pruned. The independently owned annotation item is not deleted. Parameters ---------- - sceneobject - The scene object whose represented item should change. - item - The replacement data item. + entry + Attached annotation entry or its stable GUID. + + Raises + ------ + KeyError + If a supplied GUID does not identify an annotation in this scene. + ValueError + If a supplied entry does not belong to this scene. """ + annotation = self.annotation(entry) if isinstance(entry, UUID) else entry + if annotation.scene is not self or annotation.guid not in self._annotation_index: + raise ValueError("The scene annotation does not belong to this scene.") + for context_name, resources in tuple(self._resources.items()): + if annotation.guid in resources: + self.clear_annotation(annotation, context=context_name) + self._annotations.remove(annotation) + del self._annotation_index[annotation.guid] + annotation._item = cast( + TextAnnotation | ArrowAnnotation | DistanceDimension | None, + self._items.get(annotation.item_guid), + ) + annotation._scene = None + self._prune_items() + + def replace_item(self, sceneobject: SceneObject, item: Data) -> None: + """Replace a scene object's represented item.""" if sceneobject.scene is not self: raise ValueError("The scene object does not belong to this scene.") + self._validate_spatial_binding(item) existing = self._items.get(item.guid) if existing is not None and existing is not item: - raise ValueError("A different data item with the same GUID is already stored.") - self._items[item.guid] = item + raise ValueError("A different data item with the same GUID is already bound.") + old_guid = sceneobject.item_guid sceneobject._item_guid = item.guid + sceneobject._item = item + self._items[item.guid] = item sceneobject.invalidate() - self._prune_items() - - def clear_context(self, guids: list[object] | None = None) -> None: - """Clear the visualization context. + if old_guid is not None: + self._prune_items() + + def draw_object(self, sceneobject: SceneObject, context: str | None = None, runtime: object | None = None) -> list[object]: + """Draw one stable scene object through a registered operation.""" + context_name = self._context_name(context) + if sceneobject.guid in self._resources.get(context_name, {}): + self.clear_object(sceneobject, context=context_name) + implementation = get_scene_operation(context_name, type(sceneobject), "draw") + result = implementation(self, sceneobject, runtime) + handles = list(result or []) + self._resources.setdefault(context_name, {})[sceneobject.guid] = (runtime, handles) + return handles + + def clear_object(self, sceneobject: SceneObject, context: str | None = None, runtime: object | None = None) -> None: + """Clear one object's transient context resources.""" + context_name = self._context_name(context) + stored_runtime, resources = self._resources.get(context_name, {}).get(sceneobject.guid, (runtime, [])) + implementation = get_scene_operation(context_name, type(sceneobject), "clear") + implementation(self, sceneobject, runtime if runtime is not None else stored_runtime, tuple(resources)) + self._resources.get(context_name, {}).pop(sceneobject.guid, None) + + def draw_annotation(self, entry: SceneAnnotation, context: str | None = None, runtime: object | None = None) -> list[object]: + """Draw one annotation entry through a registered operation. Parameters ---------- - guids - The identifiers of the objects in the visualization context. - - Notes - ----- - If `guids` is `None`, clear all objects from the visualization context. + entry + Attached annotation entry to draw. + context + Visualization context. The scene default is used when omitted. + runtime + Optional context-specific runtime object. - If `guids` is a list, only those objects in the list will be removed. + Returns + ------- + list[object] + Backend-specific runtime handles. - `Scene.clear` uses this method to remove objects previously drawn by the - scene without removing unrelated context objects. + Raises + ------ + ValueError + If the entry does not belong to this scene or no unambiguous + visualization context is available. + SceneOperationNotRegisteredError + If the selected context has no compatible draw operation. """ - clear(guids) - - def clear(self, clear_scene: bool = True, clear_context: bool = True) -> None: - """Clear the scene. + if entry.scene is not self: + raise ValueError("The scene annotation does not belong to this scene.") + context_name = self._context_name(context) + if entry.guid in self._resources.get(context_name, {}): + self.clear_annotation(entry, context=context_name) + implementation = get_scene_operation(context_name, type(entry), "draw") + result = implementation(self, entry, runtime) + handles = list(result or []) + self._resources.setdefault(context_name, {})[entry.guid] = (runtime, handles) + return handles + + def clear_annotation(self, entry: SceneAnnotation, context: str | None = None, runtime: object | None = None) -> None: + """Clear one annotation entry's transient context resources. Parameters ---------- - clear_scene - If `True`, remove all scene objects from the scene tree. - clear_context - If `True`, remove all objects drawn by the scene from the - visualization context. - - Examples - -------- - Redraw the scene without modifying unrelated context objects. - - >>> scene.clear(clear_scene=False, clear_context=True) # doctest: +SKIP - >>> scene.draw() # doctest: +SKIP + entry + Attached annotation entry whose resources should be cleared. + context + Visualization context. The scene default is used when omitted. + runtime + Optional context-specific runtime object overriding the stored + runtime. + + Raises + ------ + ValueError + If the entry does not belong to this scene or no unambiguous + visualization context is available. + SceneOperationNotRegisteredError + If the selected context has no compatible clear operation. """ - guids = [] - - for sceneobject in self.objects: - guids += sceneobject.guids - sceneobject._guids = None - - if clear_scene: - for sceneobject in tuple(self.root.children): - self.remove(sceneobject) - - if clear_context: - self.clear_context(guids) - - def draw(self) -> list[object]: - """Draw the scene. - - This will just draw all scene objects in the scene tree, - without making any modifications to the visualization context. - For example, it will not remove any of the previously drawn objects. - - Returns - ------- - list[object] - The objects created in the visualization context. - - """ - - if not self.context: - raise ValueError("No context detected.") - - before_draw() - - drawn_objects: list[object] = [] + if entry.scene is not self: + raise ValueError("The scene annotation does not belong to this scene.") + context_name = self._context_name(context) + stored_runtime, resources = self._resources.get(context_name, {}).get(entry.guid, (runtime, [])) + implementation = get_scene_operation(context_name, type(entry), "clear") + implementation(self, entry, runtime if runtime is not None else stored_runtime, tuple(resources)) + self._resources.get(context_name, {}).pop(entry.guid, None) + + def draw(self, context: str | None = None, runtime: object | None = None) -> list[object]: + """Draw all visible spatial objects and annotation entries.""" + context_name = self._context_name(context) + drawn: list[object] = [] for sceneobject in self.objects: if sceneobject.show: - drawn_objects += sceneobject.draw() - - after_draw(drawn_objects) - - return drawn_objects - - def redraw(self) -> None: - """Redraw the scene. + drawn.extend(self.draw_object(sceneobject, context=context_name, runtime=runtime)) + for entry in self.annotations: + if entry.show: + drawn.extend(self.draw_annotation(entry, context=context_name, runtime=runtime)) + return drawn + + def clear(self, clear_scene: bool = True, clear_context: bool = True, context: str | None = None, runtime: object | None = None) -> None: + """Clear durable scene content and/or transient context resources.""" + if clear_context: + contexts = [context] if context is not None else ([self.context] if self.context is not None else list(self._resources)) + for context_name in contexts: + for sceneobject in tuple(self.objects): + if sceneobject.guid in self._resources.get(context_name, {}): + self.clear_object(sceneobject, context=context_name, runtime=runtime) + for entry in self.annotations: + if entry.guid in self._resources.get(context_name, {}): + self.clear_annotation(entry, context=context_name, runtime=runtime) + if clear_scene: + for child in tuple(self.root_node.children): + self.remove(child) + for entry in self.annotations: + self.remove_annotation(entry) - This removes all previously drawn objects from the visualization context, - before drawing all scene objects in the scene tree. + def redraw(self, context: str | None = None, runtime: object | None = None) -> None: + """Clear transient resources and draw the durable scene again.""" + self.clear(clear_scene=False, clear_context=True, context=context, runtime=runtime) + self.draw(context=context, runtime=runtime) - """ - self.clear(clear_scene=False, clear_context=True) - self.draw() + def find_node_by_name(self, name: str) -> SceneNode | None: + """Find the first hierarchy node whose scene object has a name.""" + return next((node for node in self.tree.nodes if not node.is_root and self.object(node).name == name), None) def find_by_name(self, name: str) -> SceneObject | None: - """Find the first scene object with the given name. - - Parameters - ---------- - name - Name of the object. - - Returns - ------- - SceneObject | None - The first matching scene object, or `None`. - - """ - return next((sceneobject for sceneobject in self.objects if sceneobject.name == name), None) + """Find the first scene object with a name.""" + node = self.find_node_by_name(name) + return self.object(node) if node is not None else None def find_by_itemtype(self, itemtype: type[Data]) -> SceneObject | None: - """Find the first scene object with a data item of the given type. - - Parameters - ---------- - itemtype - The type of the data item associated with the scene object. - - Returns - ------- - SceneObject | None - The first matching scene object, or `None`. - - """ - for obj in self.objects: - if isinstance(obj.item, itemtype): - return obj + """Find the first resolved object representing an item type.""" + return next((obj for obj in self.objects if obj.item_guid in self._items and isinstance(obj.item, itemtype)), None) def find_all_by_itemtype(self, itemtype: type[Data]) -> list[SceneObject]: - """Find all scene objects with a data item of the given type. - - Parameters - ---------- - itemtype - The type of the data item associated with the scene object. - - Returns - ------- - list[SceneObject] - All matching scene objects. - - """ - sceneobjects: list[SceneObject] = [] - for obj in self.objects: - if isinstance(obj.item, itemtype): - sceneobjects.append(obj) - return sceneobjects - - # ========================================================================== - # Private helpers - # ========================================================================== - - def _attach(self, sceneobject: SceneObject, parent: SceneObject | None) -> None: - if sceneobject.guid in self._objects: - raise ValueError("A scene object with the same GUID is already stored.") - - item = sceneobject.item - if item is not None: - existing = self._items.get(item.guid) - if existing is not None and existing is not item: - raise ValueError("A different data item with the same GUID is already stored.") - self._items[item.guid] = item - - node = SceneNode(sceneobject.guid) - parent_node = self._nodes[parent.guid] if parent else None - self.tree.add(node, parent=parent_node) - self._objects[sceneobject.guid] = sceneobject - self._nodes[sceneobject.guid] = node - sceneobject._scene = self - if hasattr(sceneobject, "_detached_item"): - del sceneobject._detached_item + """Find all resolved objects representing an item type.""" + return [obj for obj in self.objects if obj.item_guid in self._items and isinstance(obj.item, itemtype)] + + def _index_nodes(self) -> None: + indexed: dict[UUID, SceneNode] = {} + for node in self.tree.nodes: + if node.object_guid in indexed: + raise ValueError(f"Scene object {node.object_guid} appears more than once in the hierarchy.") + indexed[node.object_guid] = node + self._nodes = indexed + + def _parent_node(self, parent: SceneObject | SceneNode | None) -> SceneNode: + if parent is None: + return self.root_node + node = self.node(parent.guid) if isinstance(parent, SceneObject) else parent + if node.object_guid not in self._nodes: + raise ValueError("The parent does not belong to this scene.") + return node + + def _referenced_item_guids(self) -> set[UUID]: + object_guids = {obj.item_guid for obj in self._objects.values() if obj.item_guid is not None} + return object_guids | {entry.item_guid for entry in self._annotations} def _prune_items(self) -> None: - referenced = {sceneobject.item_guid for sceneobject in self._objects.values()} - for guid in set(self._items) - referenced: + for guid in set(self._items) - self._referenced_item_guids(): del self._items[guid] + + def _context_name(self, context: str | None) -> str: + context_name = context or self.context or detect_current_context() + if context_name is None: + raise ValueError("No unambiguous visualization context is available.") + return context_name + + @staticmethod + def _validate_annotation_binding(entry: SceneAnnotation, item: Data) -> None: + if not isinstance(item, (TextAnnotation, ArrowAnnotation, DistanceDimension)): + raise TypeError("A scene-annotation item should be a TextAnnotation, ArrowAnnotation, or DistanceDimension.") + if entry.style is not None and not isinstance(item, DistanceDimension): + raise ValueError("DimensionStyle is supported only for DistanceDimension entries.") + + @staticmethod + def _normalize_annotation_style(entry: SceneAnnotation, item: Data) -> None: + if isinstance(item, DistanceDimension) and entry.style is None: + entry.style = DimensionStyle() + + @staticmethod + def _validate_spatial_binding(item: Data) -> None: + if isinstance(item, (TextAnnotation, ArrowAnnotation, DistanceDimension)): + raise TypeError("Annotation items belong in Scene.annotations, not the spatial hierarchy.") diff --git a/src/compas/scene/sceneannotation.py b/src/compas/scene/sceneannotation.py new file mode 100644 index 00000000000..0642900f0d0 --- /dev/null +++ b/src/compas/scene/sceneannotation.py @@ -0,0 +1,372 @@ +from __future__ import annotations + +from math import isfinite +from typing import TYPE_CHECKING +from typing import Any +from typing import Self +from typing import cast +from uuid import UUID + +from compas.colors import Color +from compas.data import Data + +from .annotations import ArrowAnnotation +from .annotations import DistanceDimension +from .annotations import TextAnnotation +from .exceptions import SceneItemNotBoundError + +if TYPE_CHECKING: + from .scene import Scene + + +type AnnotationItem = TextAnnotation | ArrowAnnotation | DistanceDimension + + +class DimensionStyle(Data): + """Durable presentation style for a distance dimension. + + All sizes are expressed in logical screen pixels. `label_offset` follows + the screen-space normal on the left side of the projected dimension from + start to end. + + Parameters + ---------- + color + Line and label color. + line_width + Positive dimension-line width. + text_size + Positive label height. + arrow_size + Positive arrow-head width. The head length retains a 4:3 proportion. + label_offset + Finite signed label offset. + name + Style name. + + """ + + @property + def __data__(self) -> dict[str, Any]: + """Return the serializable dimension-style data. + + Returns + ------- + dict[str, Any] + The closed dimension-style payload. + + """ + return { + "color": self.color, + "line_width": self.line_width, + "text_size": self.text_size, + "arrow_size": self.arrow_size, + "label_offset": self.label_offset, + } + + @classmethod + def __from_data__(cls, data: dict[str, Any]) -> Self: + """Construct a style from its closed serialized schema. + + Returns + ------- + DimensionStyle + The reconstructed style. + + """ + expected = {"color", "line_width", "text_size", "arrow_size", "label_offset"} + unknown = set(data) - expected + if unknown: + raise ValueError("Unknown dimension-style fields: {}.".format(", ".join(sorted(unknown)))) + missing = expected - set(data) + if missing: + raise ValueError("Missing dimension-style fields: {}.".format(", ".join(sorted(missing)))) + return cls(**data) + + def __init__( + self, + color: Color | None = None, + line_width: float = 3.0, + text_size: float = 12.0, + arrow_size: float = 12.0, + label_offset: float = 0.0, + *, + name: str | None = None, + ) -> None: + super().__init__(name=name) + self.color = Color.white() if color is None else color + self.line_width = line_width + self.text_size = text_size + self.arrow_size = arrow_size + self.label_offset = label_offset + + def __eq__(self, other: object) -> bool: + return isinstance(other, DimensionStyle) and self.__data__ == other.__data__ + + @property + def color(self) -> Color: + """Return the dimension line and label color.""" + return self._color + + @color.setter + def color(self, value: Color) -> None: + if not isinstance(value, Color): + raise TypeError("Dimension-style color should be a Color.") + self._color = value + + @property + def line_width(self) -> float: + """Return the positive line width in logical pixels.""" + return self._line_width + + @line_width.setter + def line_width(self, value: float) -> None: + self._line_width = _positive_float(value, "line width") + + @property + def text_size(self) -> float: + """Return the positive label height in logical pixels.""" + return self._text_size + + @text_size.setter + def text_size(self, value: float) -> None: + self._text_size = _positive_float(value, "text size") + + @property + def arrow_size(self) -> float: + """Return the positive arrow-head width in logical pixels.""" + return self._arrow_size + + @arrow_size.setter + def arrow_size(self, value: float) -> None: + self._arrow_size = _positive_float(value, "arrow size") + + @property + def label_offset(self) -> float: + """Return the signed label offset in logical pixels.""" + return self._label_offset + + @label_offset.setter + def label_offset(self, value: float) -> None: + self._label_offset = _finite_float(value, "label offset") + + +class SceneAnnotation(Data): + """Stable scene-scoped placement of one annotation item. + + Annotation entries belong to a flat ordered collection rather than the + spatial hierarchy. They have no node, parent, children, or transformation. + + Parameters + ---------- + item + Independently serializable annotation item. + item_guid + GUID of an unresolved annotation item. + name + Entry name. + show + Whether the annotation is visible. + style + Optional distance-dimension presentation style. + + """ + + @property + def __data__(self) -> dict[str, Any]: + """Return the durable annotation-entry data. + + Returns + ------- + dict[str, Any] + The closed annotation-entry payload. + + """ + return { + "item": str(self.item_guid), + "show": self.show, + "style": self.style, + } + + @classmethod + def __from_data__(cls, data: dict[str, Any]) -> Self: + """Construct an unresolved annotation entry from serialized data. + + Returns + ------- + SceneAnnotation + The reconstructed entry. + + """ + expected = {"item", "show", "style"} + unknown = set(data) - expected + if unknown: + raise ValueError("Unknown scene-annotation fields: {}.".format(", ".join(sorted(unknown)))) + missing = expected - set(data) + if missing: + raise ValueError("Missing scene-annotation fields: {}.".format(", ".join(sorted(missing)))) + try: + item_guid = UUID(data["item"]) + except (AttributeError, TypeError, ValueError): + raise ValueError("Scene-annotation item should be a UUID string.") from None + return cls(item_guid=item_guid, show=data["show"], style=data["style"]) + + def __init__( + self, + item: AnnotationItem | None = None, + *, + item_guid: UUID | None = None, + name: str | None = None, + show: bool = True, + style: DimensionStyle | None = None, + ) -> None: + if item is None and item_guid is None: + raise ValueError("A scene annotation requires an item or item GUID.") + if item is not None and not isinstance(item, (TextAnnotation, ArrowAnnotation, DistanceDimension)): + raise TypeError("A scene-annotation item should be a TextAnnotation, ArrowAnnotation, or DistanceDimension.") + if item is not None and item_guid is not None and item.guid != item_guid: + raise ValueError("The supplied annotation item and item GUID do not match.") + if item_guid is not None and not isinstance(item_guid, UUID): + raise TypeError("Scene-annotation item_guid should be a UUID.") + if not isinstance(show, bool): + raise TypeError("Scene-annotation show should be a boolean.") + if style is not None and not isinstance(style, DimensionStyle): + raise TypeError("Scene-annotation style should be a DimensionStyle or None.") + if isinstance(item, DistanceDimension) and style is None: + style = DimensionStyle() + if item is not None: + _validate_item_style(item, style) + super().__init__(name=name or getattr(item, "name", None)) + self._item_guid = item.guid if item is not None else cast(UUID, item_guid) + self._item = item + self._scene: Scene | None = None + self.show = show + self.style = style + + @property + def item_guid(self) -> UUID: + """Return the GUID of the represented annotation item.""" + return self._item_guid + + @property + def item(self) -> AnnotationItem: + """Return the bound annotation item. + + Raises + ------ + SceneItemNotBoundError + If the annotation item is unresolved. + + """ + if self.scene is not None: + item = self.scene.item(self.item_guid, object_guid=self.guid) + return cast(AnnotationItem, item) + if self._item is None: + raise SceneItemNotBoundError(self.guid, self.item_guid) + return self._item + + @property + def scene(self) -> Scene | None: + """Return the owning scene, or `None` while detached.""" + return self._scene + + @property + def show(self) -> bool: + """Return whether the annotation is visible.""" + return self._show + + @show.setter + def show(self, value: bool) -> None: + if not isinstance(value, bool): + raise TypeError("Scene-annotation show should be a boolean.") + self._show = value + + @property + def style(self) -> DimensionStyle | None: + """Return the optional distance-dimension style.""" + return self._style + + @style.setter + def style(self, value: DimensionStyle | None) -> None: + if value is not None and not isinstance(value, DimensionStyle): + raise TypeError("Scene-annotation style should be a DimensionStyle or None.") + item = self._item + if item is None and self.scene is not None: + item = cast(AnnotationItem | None, self.scene.item_store.get(self.item_guid)) + if item is not None: + if isinstance(item, DistanceDimension) and value is None: + value = DimensionStyle() + _validate_item_style(item, value) + self._style = value + + def draw(self, context: str | None = None, runtime: object | None = None) -> list[object]: + """Draw this entry through its owning scene context. + + Parameters + ---------- + context + Visualization context. The owning scene default is used when + omitted. + runtime + Optional context-specific runtime object. + + Returns + ------- + list[object] + Backend-specific runtime handles. + + Raises + ------ + ValueError + If the entry is detached. + + """ + if self.scene is None: + raise ValueError("The scene annotation does not belong to a scene.") + return self.scene.draw_annotation(self, context=context, runtime=runtime) + + def clear(self, context: str | None = None, runtime: object | None = None) -> None: + """Clear this entry's transient resources through its owning scene. + + Parameters + ---------- + context + Visualization context. The owning scene default is used when + omitted. + runtime + Optional context-specific runtime object overriding the stored + runtime. + + Raises + ------ + ValueError + If the entry is detached. + + """ + if self.scene is None: + raise ValueError("The scene annotation does not belong to a scene.") + self.scene.clear_annotation(self, context=context, runtime=runtime) + + +def _finite_float(value: float, field: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise TypeError(f"Dimension-style {field} should be a number.") + result = float(value) + if not isfinite(result): + raise ValueError(f"Dimension-style {field} should be finite.") + return result + + +def _positive_float(value: float, field: str) -> float: + result = _finite_float(value, field) + if result <= 0.0: + raise ValueError(f"Dimension-style {field} should be positive.") + return result + + +def _validate_item_style(item: AnnotationItem, style: DimensionStyle | None) -> None: + if style is not None and not isinstance(item, DistanceDimension): + raise ValueError("DimensionStyle is supported only for DistanceDimension entries.") + + +__all__ = ["DimensionStyle", "SceneAnnotation"] diff --git a/src/compas/scene/sceneobject.py b/src/compas/scene/sceneobject.py index b2ab4fd4ca7..a6e9321ee13 100644 --- a/src/compas/scene/sceneobject.py +++ b/src/compas/scene/sceneobject.py @@ -1,10 +1,13 @@ +from collections.abc import Callable from collections.abc import Iterator +from collections.abc import Mapping +from dataclasses import dataclass from functools import reduce from operator import mul -from typing import TYPE_CHECKING +from types import MappingProxyType from typing import Any +from typing import ClassVar from typing import Literal -from typing import NoReturn from typing import Self from typing import cast from uuid import UUID @@ -14,328 +17,490 @@ from compas.geometry import Frame from compas.geometry import Transformation -from .context import clear -from .context import get_sceneobject_cls +from .context import get_scene_operation from .descriptors.color import ColorAttribute +from .exceptions import SceneItemNotBoundError +from .exceptions import SceneStateError -if TYPE_CHECKING: - from compas.datastructures import Tree - from compas.scene import Scene +_MISSING = object() - from ._scenenode import SceneNode + +type SceneAttributeUpdate[OwnerT] = Callable[[OwnerT, object], None] +type _SceneAttributeUpdate = Callable[[Any, object], None] + + +@dataclass(frozen=True, slots=True) +class SceneStateField[OwnerT]: + """Declaration of one durable semantic scene-object field. + + Parameters + ---------- + name + Stable serialized field name. + value_type + Runtime type or tuple of accepted runtime types. + attribute_name + Object attribute carrying the value. Defaults to `name`. + default + Value used when an optional serialized field is omitted. + required + Whether omission without a default is an error. + omit_default + Whether a value equal to `default` is omitted. + editable + Whether the ordinary object attribute may be edited by a consumer. + update + Optional synchronous data-only update callback. The callback must + leave the owner unchanged if it raises. The caller owns any rendering + or user-interface effects after a successful update. + + """ + + name: str + value_type: type[object] | tuple[type[object], ...] = object + attribute_name: str | None = None + default: object = _MISSING + required: bool = True + omit_default: bool = False + editable: bool = False + update: SceneAttributeUpdate[OwnerT] | None = None + + @property + def attribute(self) -> str: + """Return the ordinary object attribute carrying the value.""" + return self.attribute_name or self.name class SceneObject(Data): - """Base class for all scene objects. + """Stable backend-neutral description of one visualized item. Parameters ---------- item - The item to visualize. + The independently serializable item represented by this object. + item_guid + The GUID of an unresolved represented item. name - The name of the scene object. This is independent of the name of the - underlying data item because multiple scene objects can refer to the - same item. + The scene-object name. color - The color of the object. + Base display color. opacity - The opacity of the object. + Display opacity between zero and one. show - Whether to show the object. + Whether the object is visible. transformation - The local transformation relative to the parent scene object. - context - The context in which the scene object is created. - **kwargs - Additional keyword arguments to create the scene object for the item. + Local transformation relative to the parent scene object. + extensions + Unknown namespaced state preserved for forward round trips. Notes ----- - `SceneObject(...)` may dispatch to a registered subclass. The internal - `sceneobject_type` factory override is accepted by `__new__`, but is not an - initialization parameter of constructed scene objects. + Visualization backends provide context-keyed `draw` and `clear` + operations. They never replace this object's Python type. """ color = ColorAttribute() - - # ========================================================================== - # Data - # ========================================================================== + __editable_attributes__: ClassVar[Mapping[str, _SceneAttributeUpdate | None]] = { + "name": None, + "opacity": None, + } + __scene_state_namespace__: ClassVar[str | None] = None + __scene_state_fields__: ClassVar[tuple[SceneStateField[Any], ...]] = () @property - def __data__(self) -> dict[str, object]: - if self.item_guid is None: - raise ValueError("A scene object without an item cannot be serialized independently.") + def __data__(self) -> dict[str, Any]: + """Return the backend-neutral durable representation.""" + extensions = {namespace: dict(values) for namespace, values in self._extensions.items()} + for namespace, fields in self.scene_state_fields().items(): + values: dict[str, object] = {} + for field in fields: + value = getattr(self, field.attribute) + if not isinstance(value, field.value_type): + raise SceneStateError(f"Invalid scene-state field {namespace}.{field.name}: {type(value).__name__}.") + if field.omit_default and value == field.default: + continue + values[field.name] = value + if values: + extensions.setdefault(namespace, {}).update(values) + elif namespace not in extensions: + extensions.pop(namespace, None) return { - "item": str(self.item_guid), - "settings": self.settings, - "children": [child.__data__ for child in self.children], + "item": str(self.item_guid) if self.item_guid is not None else None, + "transformation": self.transformation, + "color": self.color, + "opacity": self.opacity, + "show": self.show, + "extensions": extensions, } @classmethod - def __from_data__(cls, data: dict[str, object]) -> NoReturn: - raise TypeError("Serialisation outside Scene not allowed.") - - # ========================================================================== - # Dunder methods - # ========================================================================== - - def __new__( - cls, - item: Data | None = None, - context: str | None = None, - sceneobject_type: type["SceneObject"] | None = None, - **kwargs: Any, - ) -> Self: - sceneobject_cls = get_sceneobject_cls(item, context=context, sceneobject_type=sceneobject_type, **kwargs) - return cast(Self, object.__new__(sceneobject_cls)) + def __from_data__(cls, data: dict[str, Any]) -> Self: + """Construct a stable scene object from its closed schema.""" + expected = {"item", "transformation", "color", "opacity", "show", "extensions"} + unknown = set(data) - expected + if unknown: + raise ValueError("Unknown scene-object fields: {}.".format(", ".join(sorted(unknown)))) + missing = expected - set(data) + if missing: + raise ValueError("Missing scene-object fields: {}.".format(", ".join(sorted(missing)))) + extensions = data["extensions"] + if not isinstance(extensions, dict): + raise TypeError("Scene-object extensions should be a mapping.") + kwargs: dict[str, Any] = {} + unknown_extensions: dict[str, dict[str, object]] = {} + for namespace, fields in cls.scene_state_fields().items(): + values = extensions.get(namespace, {}) + if not isinstance(values, dict): + raise TypeError(f"Scene-object extension '{namespace}' should be a mapping.") + field_names = {field.name for field in fields} + extra = set(values) - field_names + if extra: + unknown_extensions[namespace] = {name: values[name] for name in extra} + for field in fields: + if field.name in values: + value = values[field.name] + if not isinstance(value, field.value_type): + raise SceneStateError(f"Invalid scene-state field {namespace}.{field.name}: {type(value).__name__}.") + kwargs[field.attribute] = value + elif field.default is not _MISSING: + kwargs[field.attribute] = field.default + elif field.required: + raise SceneStateError(f"Missing scene-state field {namespace}.{field.name}.") + item_guid = UUID(data["item"]) if data["item"] is not None else None + for namespace, values in extensions.items(): + if namespace not in cls.scene_state_fields(): + unknown_extensions[namespace] = dict(values) + obj = cls( + item_guid=item_guid, + transformation=data["transformation"], + color=data["color"], + opacity=data["opacity"], + show=data["show"], + extensions=unknown_extensions, + **kwargs, + ) + return obj def __init__( self, item: Data | None = None, + *, + item_guid: UUID | None = None, name: str | None = None, color: Color | None = None, opacity: float = 1.0, show: bool = True, transformation: Transformation | None = None, - context: str | None = None, + extensions: dict[str, dict[str, object]] | None = None, **kwargs: object, ) -> None: - if item and not isinstance(item, Data): - raise ValueError("The item assigned to this scene object should be a data object: {}".format(type(item))) - - # This factory-only option has already been handled by __new__. - kwargs.pop("sceneobject_type", None) - name = name or getattr(item, "name", None) - super().__init__(name=name) - # the scene object needs to store the context - # because it has no access to the tree and/or the scene before it is added - # which means that adding child objects will be added in context "None" - self.context = context - self.attributes = kwargs - self._item_guid: UUID | None = item.guid if item else None - self._detached_item = item - self._scene: Scene | None = None - self._guids: list[object] | None = [] + if item is not None and not isinstance(item, Data): + raise TypeError("A scene-object item should be a Data object.") + if item is not None and item_guid is not None and item.guid != item_guid: + raise ValueError("The supplied item and item GUID do not match.") + if isinstance(opacity, bool) or not isinstance(opacity, (int, float)): + raise TypeError("Scene-object opacity should be a number.") + if not 0.0 <= opacity <= 1.0: + raise ValueError("Scene-object opacity should be between 0.0 and 1.0.") + if not isinstance(show, bool): + raise TypeError("Scene-object show should be a boolean.") + if transformation is not None and not isinstance(transformation, Transformation): + raise TypeError("Scene-object transformation should be a Transformation or None.") + if kwargs: + raise TypeError(f"Unexpected scene-object arguments: {', '.join(sorted(kwargs))}.") + super().__init__(name=name or getattr(item, "name", None)) + self._item_guid = item.guid if item is not None else item_guid + self._item = item + self._scene: Any = None self._transformation = transformation self._transformation_revision = 0 - self._contrastcolor = None - self.color = color or self.color - self.opacity = opacity + self._contrastcolor: Color | None = None + self.color = color or Color.white() + self.opacity = float(opacity) self.show = show - - def __repr__(self) -> str: - return "<{}: {}>".format(self.__class__.__name__, self.name) - - # ========================================================================== - # Properties - # ========================================================================== + self._extensions = {namespace: dict(values) for namespace, values in (extensions or {}).items()} @property - def scene(self) -> "Scene | None": - """The scene containing this object, if it has been added to one.""" - return self._scene + def item_guid(self) -> UUID | None: + """Return the GUID of the represented item.""" + return self._item_guid @property def item(self) -> Data | None: - """The data item represented by this scene object.""" - if self._item_guid is None: + """Return the represented item, or raise if its reference is unresolved.""" + if self.item_guid is None: return None - if self.scene is None: - return getattr(self, "_detached_item", None) - return self.scene.item_store[self._item_guid] + if self.scene is not None: + return self.scene.item(self.item_guid, object_guid=self.guid) + if self._item is None: + raise SceneItemNotBoundError(self.guid, self.item_guid) + return self._item @property - def item_guid(self) -> UUID | None: - """The GUID of the represented data item.""" - return self._item_guid + def scene(self) -> Any: + """Return the scene containing this object, if attached.""" + return self._scene @property - def parent(self) -> "SceneObject | None": - """The parent scene object.""" - if self.scene is None: - return None - node = self.scene._nodes[self.guid] - if node.parent is None: + def node(self) -> Any: + """Return the hierarchy node, if attached.""" + return self.scene.node(self.guid) if self.scene is not None else None + + @property + def parent(self) -> Self | None: + """Return the parent scene object, if any.""" + node = self.node + if node is None or node.parent is None: return None - return self.scene._objects[node.parent.object_guid] + return self.scene.object(node.parent.object_guid) @property def children(self) -> tuple["SceneObject", ...]: - """The child scene objects.""" - if self.scene is None: + """Return child scene objects in hierarchy order.""" + node = self.node + if node is None: return () - node = self.scene._nodes[self.guid] - return tuple(self.scene._objects[child.object_guid] for child in node.children) + return tuple(self.scene.object(child.object_guid) for child in node.children) @property - def tree(self) -> "Tree[SceneNode] | None": - """The hierarchy tree containing this scene object.""" - return self.scene.tree if self.scene else None + def tree(self) -> Any: + """Return the owning scene hierarchy, if attached.""" + return self.scene.tree if self.scene is not None else None @property def is_root(self) -> bool: - """Whether this scene object is the root group.""" - return bool(self.scene and self.scene._nodes[self.guid].is_root) + """Return whether this object is the hierarchy root.""" + return bool(self.node and self.node.is_root) @property def is_leaf(self) -> bool: - """Whether this scene object has no children.""" + """Return whether this object has no children.""" return not self.children @property def is_branch(self) -> bool: - """Whether this scene object is neither the root nor a leaf.""" + """Return whether this object is neither root nor leaf.""" return not self.is_root and not self.is_leaf @property def ancestors(self) -> Iterator["SceneObject"]: - """An iterator over the ancestor scene objects.""" - if self.scene is None: + """Iterate over ancestor scene objects.""" + if self.node is None: return iter(()) - node = self.scene._nodes[self.guid] - return (self.scene._objects[ancestor.object_guid] for ancestor in node.ancestors) + return (self.scene.object(node.object_guid) for node in self.node.ancestors) @property def descendants(self) -> Iterator["SceneObject"]: - """An iterator over the descendant scene objects.""" - if self.scene is None: + """Iterate over descendant scene objects.""" + if self.node is None: return iter(()) - node = self.scene._nodes[self.guid] - return (self.scene._objects[descendant.object_guid] for descendant in node.descendants) + return (self.scene.object(node.object_guid) for node in self.node.descendants) @property - def guids(self) -> list[object]: - """The identifiers of objects created in the visualization context.""" - return self._guids or [] + def transformation(self) -> Transformation | None: + """Return the local transformation.""" + return self._transformation + + @transformation.setter + def transformation(self, transformation: Transformation | None) -> None: + if transformation is not None and not isinstance(transformation, Transformation): + raise TypeError("Scene-object transformation should be a Transformation or None.") + self._transformation = transformation + if hasattr(self, "_transformation_revision"): + self._transformation_revision += 1 + self.invalidate() @property def frame(self) -> Frame: - """The frame represented by the world transformation. - - Setting the frame updates the local transformation relative to the - parent scene object. - - """ + """Return the frame represented by the world transformation.""" return Frame.from_transformation(self.worldtransformation) @frame.setter def frame(self, frame: Frame) -> None: self.worldtransformation = Transformation.from_frame(frame) - @property - def transformation(self) -> Transformation | None: - """The local transformation relative to the parent scene object. - - Setting the transformation invalidates transformation-dependent caches - on this object. Descendant caches detect the change lazily. - - """ - return self._transformation - - @transformation.setter - def transformation(self, transformation: Transformation | None) -> None: - self._transformation = transformation - self._transformation_revision += 1 - self.invalidate() - @property def worldtransformation(self) -> Transformation: - """The transformation from local coordinates to world coordinates. - - The transformation is computed from this object's local transformation - and those of its ancestors. Setting it derives the corresponding local - transformation relative to the parent. - - """ + """Return the transformation from local to world coordinates.""" transformations = [self.transformation] if self.transformation else [] parent = self.parent while parent and not parent.is_root: if parent.transformation: transformations.append(parent.transformation) parent = parent.parent - if transformations: - worldtransformation = reduce(mul, transformations[::-1]) - else: - worldtransformation = Transformation() - - return worldtransformation + return reduce(mul, transformations[::-1]) if transformations else Transformation() @worldtransformation.setter - def worldtransformation(self, worldtransformation: Transformation) -> None: - if isinstance(self.parent, SceneObject): - self.transformation = self.parent.worldtransformation.inverse() * worldtransformation - else: - self.transformation = worldtransformation + def worldtransformation(self, transformation: Transformation) -> None: + self.transformation = self.parent.worldtransformation.inverse() * transformation if self.parent else transformation @property def contrastcolor(self) -> Color | None: - """A lighter or darker color contrasting with the object color. - - The computed color is cached. Setting this property coerces the value to - a `Color`. - - """ - if not self._contrastcolor: - if self.color: - if self.color.is_light: - self._contrastcolor = self.color.darkened(50) - else: - self._contrastcolor = self.color.lightened(50) + """Return a cached color contrasting with the base color.""" + if self._contrastcolor is None and self.color: + self._contrastcolor = self.color.darkened(50) if self.color.is_light else self.color.lightened(50) return self._contrastcolor @contrastcolor.setter def contrastcolor(self, color: Color) -> None: self._contrastcolor = Color.coerce(color) - @property - def settings(self) -> dict[str, object]: - """The settings required to reconstruct the scene object.""" - settings = { - "name": self.name, - "color": self.color, - "opacity": self.opacity, - "show": self.show, - } + @classmethod + def editable_attributes(cls) -> Mapping[str, SceneAttributeUpdate[Self] | None]: + """Return editable attributes composed across the MRO. - if self.transformation: - settings["transformation"] = self.transformation + The result combines non-state declarations with editable durable + scene-state fields. A derived non-state declaration replaces an + inherited callback without changing attribute order. New attributes + append in declaration order. - return settings + Returns + ------- + Mapping[str, SceneAttributeUpdate[Self] | None] + Read-only ordered mapping from attribute names to optional + data-side update callbacks. A value of `None` selects ordinary + `setattr` mutation. - # ========================================================================== - # Methods - # ========================================================================== + Raises + ------ + TypeError + If a class declaration is not a mapping or a callback is not + callable. + SceneStateError + If a non-state declaration duplicates an editable scene-state + field. + ValueError + If an attribute name is empty. - def invalidate(self) -> None: - """Clear cached data derived from the represented item or transformation. + """ + declarations: dict[str, SceneAttributeUpdate[Self] | None] = {} + sources: dict[str, Literal["non-state", "state"]] = {} + state_fields = cls.scene_state_fields() + for owner in reversed(cls.mro()): + local = owner.__dict__.get("__editable_attributes__", {}) + if not isinstance(local, Mapping): + raise TypeError(f"Editable attributes on {owner.__name__} should be a mapping.") + for name, update in local.items(): + if not isinstance(name, str): + raise TypeError(f"Editable attribute names on {owner.__name__} should be strings.") + if not name: + raise ValueError(f"Editable attribute names on {owner.__name__} cannot be empty.") + if update is not None and not callable(update): + raise TypeError(f"Editable attribute update for {owner.__name__}.{name} should be callable or None.") + if sources.get(name) == "state": + raise SceneStateError(f"Editable attribute {owner.__name__}.{name} duplicates a scene-state field.") + declarations[name] = cast(SceneAttributeUpdate[Self] | None, update) + sources[name] = "non-state" + + namespace = owner.__dict__.get("__scene_state_namespace__") + if namespace not in state_fields: + continue + for field in state_fields[namespace]: + if not field.editable: + continue + name = field.attribute + if name in declarations: + raise SceneStateError(f"Editable scene-state field {namespace}.{field.name} duplicates {name}.") + declarations[name] = cast(SceneAttributeUpdate[Self] | None, field.update) + sources[name] = "state" + return MappingProxyType(declarations) + + def update_editable_attribute(self, name: str, value: object) -> None: + """Update one declared editable attribute. + + Ordinary declarations use `setattr`. A declaration-specific update + callback replaces that assignment and must leave this object unchanged + if it raises. This method performs no rendering or user-interface + refresh. + + Parameters + ---------- + name + Name of a declared editable attribute. + value + New attribute value. - Call this after mutating an underlying item through a path that the scene - object cannot observe directly. Descendants detect ancestor - transformation changes automatically and do not need to be invalidated. + Raises + ------ + KeyError + If `name` is not declared editable for this scene-object type. """ - self._invalidate_transformation_cache() + try: + update = self.editable_attributes()[name] + except KeyError: + raise KeyError(f"Scene object attribute is not editable: {name}.") from None + if update is None: + setattr(self, name, value) + else: + update(self, value) - def add(self, item: Data, **kwargs: Any) -> "SceneObject": - """Add a child item to the scene object. + @classmethod + def scene_state_fields(cls) -> dict[str, tuple[SceneStateField[Any], ...]]: + """Return durable type-specific fields composed across the MRO. - Parameters - ---------- - item - The item to add. - **kwargs - Additional keyword arguments to create the scene object for the item. + The result groups fields by their declaring class's scene-state + namespace. During serialization, field values are written to the + matching namespace in `SceneObject.__data__["extensions"]`. Common + scene state such as `color`, `opacity`, and `show` remains in the base + scene-object payload instead. Returns ------- - SceneObject - The scene object associated with the added item. + dict[str, tuple[SceneStateField, ...]] + Field declarations keyed by stable extension namespace. + + Raises + ------ + SceneStateError + If namespaces, field declarations, defaults, or editability + metadata are inconsistent. """ + declarations: dict[str, tuple[SceneStateField[Any], ...]] = {} + attributes: set[str] = set() + for owner in reversed(cls.mro()): + fields = owner.__dict__.get("__scene_state_fields__", ()) + if not fields: + continue + namespace = owner.__dict__.get("__scene_state_namespace__") + if not namespace: + raise SceneStateError(f"{owner.__name__} declares scene state without a namespace.") + if namespace in declarations: + raise SceneStateError(f"Duplicate scene-state namespace: {namespace}.") + names = [field.name for field in fields] + if len(names) != len(set(names)): + raise SceneStateError(f"Duplicate scene-state field in namespace {namespace}.") + for field in fields: + if not field.name or not field.attribute: + raise SceneStateError(f"Scene-state field names in namespace {namespace} cannot be empty.") + try: + isinstance(None, field.value_type) + except TypeError: + raise SceneStateError(f"Invalid value type for scene-state field {namespace}.{field.name}.") from None + if field.default is not _MISSING and field.required: + raise SceneStateError(f"Scene-state field {namespace}.{field.name} cannot have a default and be required.") + if field.default is not _MISSING and not isinstance(field.default, field.value_type): + raise SceneStateError(f"Invalid default for scene-state field {namespace}.{field.name}.") + if field.omit_default and field.default is _MISSING: + raise SceneStateError(f"Scene-state field {namespace}.{field.name} cannot omit an undeclared default.") + if not isinstance(field.editable, bool): + raise SceneStateError(f"Invalid editable flag for scene-state field {namespace}.{field.name}.") + if field.update is not None and not callable(field.update): + raise SceneStateError(f"Invalid update callback for scene-state field {namespace}.{field.name}.") + if field.update is not None and not field.editable: + raise SceneStateError(f"Scene-state field {namespace}.{field.name} cannot define update unless editable.") + if field.attribute in attributes: + raise SceneStateError(f"Duplicate scene-state adapter attribute: {field.attribute}.") + attributes.add(field.attribute) + declarations[namespace] = tuple(fields) + return declarations + + def add(self, item: Data, **kwargs: Any) -> "SceneObject": + """Add a child item through the owning scene.""" if self.scene is None: - raise RuntimeError("A detached scene object cannot own child objects.") + raise RuntimeError("A detached scene object cannot own children.") return self.scene.add(item, parent=self, **kwargs) def traverse( @@ -343,52 +508,36 @@ def traverse( strategy: Literal["depthfirst", "breadthfirst"] = "depthfirst", order: Literal["preorder", "postorder"] = "preorder", ) -> Iterator["SceneObject"]: - """Traverse this scene-object subtree. - - Parameters - ---------- - strategy - The traversal strategy. - order - The depth-first traversal order. - - Yields - ------ - SceneObject - The next scene object in the traversal. - - """ - if self.scene is None: + """Iterate over this hierarchy subtree.""" + if self.node is None: yield self return - node = self.scene._nodes[self.guid] - for descendant in node.traverse(strategy=strategy, order=order): - yield self.scene._objects[descendant.object_guid] - - def draw(self) -> list[object]: - """The main drawing method.""" - raise NotImplementedError + for node in self.node.traverse(strategy=strategy, order=order): + yield self.scene.object(node.object_guid) - def clear(self) -> None: - """The main clearing method.""" - clear(guids=self.guids) - self._guids = None + def draw(self, context: str | None = None, runtime: object | None = None) -> list[object]: + """Draw this object through a context-keyed operation.""" + if self.scene is None: + raise RuntimeError("A detached scene object cannot be drawn.") + return self.scene.draw_object(self, context=context, runtime=runtime) - # ========================================================================== - # Private helpers - # ========================================================================== + def clear(self, context: str | None = None, runtime: object | None = None) -> None: + """Clear this object's transient context resources.""" + if self.scene is None: + raise RuntimeError("A detached scene object has no context resources.") + self.scene.clear_object(self, context=context, runtime=runtime) - def _invalidate_transformation_cache(self) -> None: - """Invalidate cached data derived from the local transformation. + def invalidate(self) -> None: + """Clear caches derived from the represented item or transformation.""" + self._invalidate_transformation_cache() - Scene object types with transformation-dependent caches override this - hook. The base scene object has no such cache. + def _operation(self, context: str, operation: str) -> Any: + return get_scene_operation(context, type(self), operation) - """ + def _invalidate_transformation_cache(self) -> None: pass def _worldtransformation_revision(self) -> tuple[int, ...]: - """Return the revisions that determine the current world transformation.""" revisions = [self._transformation_revision] parent = self.parent while parent and not parent.is_root: diff --git a/src/compas/scene/shapeobject.py b/src/compas/scene/shapeobject.py new file mode 100644 index 00000000000..ecfd05faaac --- /dev/null +++ b/src/compas/scene/shapeobject.py @@ -0,0 +1,36 @@ +from typing import Any +from typing import cast + +from compas.geometry import Shape + +from .geometryobject import GeometryObject +from .sceneobject import SceneStateField + + +class ShapeObject(GeometryObject): + """Scene object for an analytic shape. + + Parameters + ---------- + u + Number of discretization intervals in the first parameter direction. + v + Number of discretization intervals in the second parameter direction. + + """ + + __scene_state_namespace__ = "compas.scene.ShapeObject" + __scene_state_fields__ = ( + SceneStateField("u", int, default=16, required=False), + SceneStateField("v", int, default=16, required=False), + ) + + def __init__(self, u: int = 16, v: int = 16, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.u = u + self.v = v + + @property + def shape(self) -> Shape: + """The analytic shape represented by this scene object.""" + return cast(Shape, self.item) diff --git a/src/compas/scene/surfaceobject.py b/src/compas/scene/surfaceobject.py new file mode 100644 index 00000000000..5c4de633168 --- /dev/null +++ b/src/compas/scene/surfaceobject.py @@ -0,0 +1,36 @@ +from typing import Any +from typing import cast + +from compas.geometry import Surface + +from .geometryobject import GeometryObject +from .sceneobject import SceneStateField + + +class SurfaceObject(GeometryObject): + """Scene object for a parametric surface. + + Parameters + ---------- + u + Number of discretization intervals in the first parameter direction. + v + Number of discretization intervals in the second parameter direction. + + """ + + __scene_state_namespace__ = "compas.scene.SurfaceObject" + __scene_state_fields__ = ( + SceneStateField("u", int, default=16, required=False), + SceneStateField("v", int, default=16, required=False), + ) + + def __init__(self, u: int = 16, v: int = 16, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.u = u + self.v = v + + @property + def surface(self) -> Surface: + """The parametric surface represented by this scene object.""" + return cast(Surface, self.item) diff --git a/src/compas/scene/vectorobject.py b/src/compas/scene/vectorobject.py new file mode 100644 index 00000000000..f61f92f0257 --- /dev/null +++ b/src/compas/scene/vectorobject.py @@ -0,0 +1,31 @@ +from typing import Any +from typing import cast + +from compas.geometry import Point +from compas.geometry import Vector + +from .geometryobject import GeometryObject +from .sceneobject import SceneStateField + + +class VectorObject(GeometryObject): + """Scene object for a vector. + + Parameters + ---------- + anchor + Point at which the vector is displayed. + + """ + + __scene_state_namespace__ = "compas.scene.VectorObject" + __scene_state_fields__ = (SceneStateField("anchor", Point),) + + def __init__(self, anchor: Point | None = None, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.anchor = anchor if anchor is not None else Point(0.0, 0.0, 0.0) + + @property + def vector(self) -> Vector: + """The vector represented by this scene object.""" + return cast(Vector, self.item) diff --git a/src/compas/scene/volmeshobject.py b/src/compas/scene/volmeshobject.py index ce54bae96f2..5eb1e29b351 100644 --- a/src/compas/scene/volmeshobject.py +++ b/src/compas/scene/volmeshobject.py @@ -10,6 +10,7 @@ from .descriptors.colordict import ColorDictAttribute from .sceneobject import SceneObject +from .sceneobject import SceneStateField class VolMeshObject(SceneObject): @@ -26,6 +27,19 @@ class VolMeshObject(SceneObject): edgecolor = ColorDictAttribute() facecolor = ColorDictAttribute() cellcolor = ColorDictAttribute() + __scene_state_namespace__ = "compas.scene.VolMeshObject" + __scene_state_fields__ = ( + SceneStateField("show_vertices", (bool, list), default=False, required=False), + SceneStateField("show_edges", (bool, list), default=False, required=False), + SceneStateField("show_faces", (bool, list), default=True, required=False), + SceneStateField("show_cells", (bool, list), default=True, required=False), + SceneStateField("vertexcolor", required=False), + SceneStateField("edgecolor", required=False), + SceneStateField("facecolor", required=False), + SceneStateField("cellcolor", required=False), + SceneStateField("vertexsize", (int, float), default=1.0, required=False), + SceneStateField("edgewidth", (int, float), default=1.0, required=False), + ) # ========================================================================== # Dunder methods @@ -63,20 +77,6 @@ def __init__( # Properties # ========================================================================== - @property - def settings(self) -> dict[str, object]: - """The settings required to reconstruct the volmesh scene object.""" - settings = super().settings - settings["show_vertices"] = self.show_vertices - settings["show_edges"] = self.show_edges - settings["show_faces"] = self.show_faces - settings["show_cells"] = self.show_cells - settings["vertexcolor"] = self.vertexcolor - settings["edgecolor"] = self.edgecolor - settings["facecolor"] = self.facecolor - settings["cellcolor"] = self.cellcolor - return settings - @property def volmesh(self) -> VolMesh: """The volmesh represented by this scene object. @@ -91,10 +91,10 @@ def volmesh(self) -> VolMesh: def volmesh(self, volmesh: VolMesh) -> None: if self.scene is None: self._item_guid = volmesh.guid - self._detached_item = volmesh + self._item = volmesh else: self.scene.replace_item(self, volmesh) - self._transformation = None + self.transformation = None self._vertex_xyz = None self._vertex_xyz_revision = None @@ -122,92 +122,6 @@ def vertex_xyz(self, vertex_xyz: dict[int, list[RealInput]]) -> None: self._vertex_xyz = vertex_xyz self._vertex_xyz_revision = None - # ========================================================================== - # Methods - # ========================================================================== - - def draw_vertices(self) -> list[object]: - """Draw the vertices of the volmesh. - - The vertices are drawn based on the values of - - * `self.show_vertices` - * `self.vertexcolor` - * `self.vertexsize` - - Returns - ------- - list[object] - The identifiers of the objects representing the vertices in the visualization context. - - """ - raise NotImplementedError - - def draw_edges(self) -> list[object]: - """Draw the edges of the volmesh. - - The edges are drawn based on the values of - - * `self.show_edges` - * `self.edgecolor` - * `self.edgewidth` - - Returns - ------- - list[object] - The identifiers of the objects representing the edges in the visualization context. - - """ - raise NotImplementedError - - def draw_faces(self) -> list[object]: - """Draw the faces of the volmesh. - - The faces are drawn based on the values of - - * `self.show_faces` - * `self.facecolor` - - Returns - ------- - list[object] - The identifiers of the objects representing the faces in the visualization context. - - """ - raise NotImplementedError - - def draw_cells(self) -> list[object]: - """Draw the cells of the volmesh. - - The cells are drawn based on the values of - - * `self.show_cells` - * `self.cellcolor` - - Returns - ------- - list[object] - The identifiers of the objects representing the cells in the visualization context. - - """ - raise NotImplementedError - - def clear_vertices(self) -> None: - """Clear the vertices of the volmesh.""" - raise NotImplementedError - - def clear_edges(self) -> None: - """Clear the edges of the volmesh.""" - raise NotImplementedError - - def clear_faces(self) -> None: - """Clear the faces of the volmesh.""" - raise NotImplementedError - - def clear_cells(self) -> None: - """Clear the cells of the volmesh.""" - raise NotImplementedError - # ========================================================================== # Private helpers # ========================================================================== diff --git a/tests/compas/files/test_gltf_conversions.py b/tests/compas/files/test_gltf_conversions.py index be010e02687..2a033add47a 100644 --- a/tests/compas/files/test_gltf_conversions.py +++ b/tests/compas/files/test_gltf_conversions.py @@ -9,7 +9,6 @@ from compas.files.gltf.constants import MODE_TRIANGLE_STRIP from compas.files.gltf.data_classes import PrimitiveData from compas.files.gltf.gltf_conversions import GLTFConversionWarning -from compas.files.gltf.gltf_conversions import _base_scene_context from compas.files.gltf.gltf_conversions import gltf_line_loop_to_polyline from compas.files.gltf.gltf_conversions import gltf_lines_to_lines from compas.files.gltf.gltf_conversions import gltf_points_to_pointcloud @@ -108,13 +107,12 @@ def test_gltf_to_scene_expands_loop_and_fan_modes(mode): def test_scene_to_gltf_preserves_hierarchy_and_supported_geometry(): - with _base_scene_context(): - scene = Scene(name="Model") - group = scene.add_group("Group", transformation=Translation.from_vector([1, 2, 3])) - mesh = Mesh.from_vertices_and_faces([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], [[0, 1, 2, 3]]) - scene.add(mesh, parent=group, name="Surface") - scene.add(Pointcloud([[0, 0, 0], [1, 1, 1]]), parent=group, name="Points") - scene.add(Polyline([[0, 0, 0], [1, 0, 0], [1, 1, 0]]), parent=group, name="Path") + scene = Scene(name="Model") + group = scene.add_group("Group", transformation=Translation.from_vector([1, 2, 3])) + mesh = Mesh.from_vertices_and_faces([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], [[0, 1, 2, 3]]) + scene.add(mesh, parent=group, name="Surface") + scene.add(Pointcloud([[0, 0, 0], [1, 1, 1]]), parent=group, name="Points") + scene.add(Polyline([[0, 0, 0], [1, 0, 0], [1, 1, 0]]), parent=group, name="Path") document = scene.to_gltf() @@ -131,10 +129,9 @@ def test_scene_to_gltf_preserves_hierarchy_and_supported_geometry(): def test_scene_to_gltf_warns_for_unsupported_items_and_preserves_children(): - with _base_scene_context(): - scene = Scene(name="Model") - unsupported = scene.add(Vector(1, 0, 0), name="Direction") - scene.add(Pointcloud([[0, 0, 0]]), parent=unsupported, name="Child") + scene = Scene(name="Model") + unsupported = scene.add(Vector(1, 0, 0), name="Direction") + scene.add(Pointcloud([[0, 0, 0]]), parent=unsupported, name="Child") with pytest.warns(GLTFConversionWarning, match="Vector"): document = scene.to_gltf() diff --git a/tests/compas/scene/test_annotations.py b/tests/compas/scene/test_annotations.py new file mode 100644 index 00000000000..7a7a0b98552 --- /dev/null +++ b/tests/compas/scene/test_annotations.py @@ -0,0 +1,414 @@ +import subprocess +import sys +from importlib import import_module +from uuid import uuid4 + +import pytest + +from compas.colors import Color +from compas.datastructures import Graph +from compas.datastructures import Mesh +from compas.geometry import Line +from compas.geometry import Point +from compas.geometry import Translation +from compas.scene import ArrowAnnotation +from compas.scene import ComponentAnchor +from compas.scene import DimensionStyle +from compas.scene import DistanceDimension +from compas.scene import PointAnchor +from compas.scene import Scene +from compas.scene import SceneAnnotation +from compas.scene import TextAnnotation + + +def test_annotation_roundtrip_is_headless(): + code = """ +import sys +from compas.scene import TextAnnotation + +item = TextAnnotation('headless', [0, 0, 0]) +TextAnnotation.from_jsonstring(item.to_jsonstring()) +assert 'compas_viewer' not in sys.modules +""" + + result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True) + + assert result.returncode == 0, result.stderr + + +def test_legacy_annotation_sceneobject_module_is_removed(): + with pytest.raises(ModuleNotFoundError): + import_module("compas.scene.annotationobject") + + +@pytest.mark.parametrize( + "item", + [ + TextAnnotation("origin", [0, 0, 0], height=18, horizontal_alignment="center"), + ArrowAnnotation([0, 0, 0], [1, 2, 3]), + DistanceDimension(PointAnchor([0, 0, 0]), PointAnchor([3, 4, 0]), unit="mm", precision=3), + ComponentAnchor(uuid4(), "edge", component=("a", "b"), parameter=0.25), + PointAnchor([1, 2, 3]), + ], +) +def test_annotation_data_roundtrips(item): + restored = type(item).from_jsonstring(item.to_jsonstring()) + + assert restored == item + assert restored.guid == item.guid + assert restored.__data__ == item.__data__ + + +@pytest.mark.parametrize( + "item", + [ + TextAnnotation("A", [0, 0, 0]), + ArrowAnnotation([0, 0, 0], [1, 0, 0]), + DistanceDimension(PointAnchor([0, 0, 0]), PointAnchor([1, 0, 0])), + ], +) +def test_annotations_use_the_flat_collection_only(item): + scene = Scene(context=None, _detect_context=False) + + with pytest.raises(TypeError, match="add_annotation"): + scene.add(item) + entry = scene.add_annotation(item) + + assert type(entry) is SceneAnnotation + assert entry.item is item + assert scene.annotations == (entry,) + assert entry not in scene.objects + assert not hasattr(entry, "node") + assert not hasattr(entry, "transformation") + + +def test_scene_roundtrip_keeps_annotation_items_reference_only(): + point = Point(1, 2, 3) + scene = Scene(context=None, _detect_context=False) + pointobject = scene.add(point) + dimension = DistanceDimension( + ComponentAnchor(pointobject.guid, "point"), + PointAnchor([4, 2, 3]), + ) + dimensionentry = scene.add_annotation(dimension) + + restored_scene = Scene.from_jsonstring(scene.to_jsonstring()) + restored_dimension = DistanceDimension.from_jsonstring(dimension.to_jsonstring()) + restored_point = Point.from_jsonstring(point.to_jsonstring()) + + assert restored_scene.item_store == {} + restored_scene.bind_many([restored_point, restored_dimension]) + restored_entry = restored_scene.annotation(dimensionentry.guid) + assert restored_entry.item is restored_dimension + assert restored_dimension.distance(restored_scene) == pytest.approx(3.0) + + +def test_fixed_dimension_derives_distance_and_deterministic_label(): + dimension = DistanceDimension( + PointAnchor([0, 0, 0]), + PointAnchor([3, 4, 0]), + unit="mm", + precision=3, + ) + + assert dimension.resolve() == (Point(0, 0, 0), Point(3, 4, 0)) + assert dimension.distance() == pytest.approx(5.0) + assert dimension.formatted_label() == "5.000 mm" + assert DistanceDimension(dimension.start, dimension.end, precision=0).formatted_label() == "5" + assert DistanceDimension(dimension.start, dimension.end, label="clearance").formatted_label() == "clearance" + + +def test_fixed_dimension_points_are_world_coordinates_outside_the_hierarchy(): + scene = Scene(context=None, _detect_context=False) + dimension = DistanceDimension(PointAnchor([0, 0, 0]), PointAnchor([1, 0, 0])) + entry = scene.add_annotation(dimension) + + assert entry not in scene.objects + assert dimension.resolve(scene) == (Point(0, 0, 0), Point(1, 0, 0)) + assert dimension.distance(scene) == pytest.approx(1.0) + + +def test_component_anchors_follow_datastructure_and_scene_transformations(): + mesh = Mesh.from_vertices_and_faces([[0, 0, 0], [2, 0, 0], [0, 1, 0]], [[0, 1, 2]]) + scene = Scene(context=None, _detect_context=False) + meshobject = scene.add(mesh, transformation=Translation.from_vector([5, 0, 0])) + start = ComponentAnchor(meshobject.guid, "vertex", component=0) + end = ComponentAnchor(meshobject.guid, "edge", component=(1, 0), parameter=0.25) + dimension = DistanceDimension(start, end) + + assert dimension.resolve(scene) == (Point(5, 0, 0), Point(6.5, 0, 0)) + assert dimension.distance(scene) == pytest.approx(1.5) + + mesh.set_vertex_point(1, [4, 0, 0]) + + assert dimension.resolve(scene) == (Point(5, 0, 0), Point(8, 0, 0)) + assert dimension.distance(scene) == pytest.approx(3.0) + + +def test_component_anchor_supports_point_line_and_graph_node_components(): + scene = Scene(context=None, _detect_context=False) + pointobject = scene.add(Point(1, 2, 3)) + lineobject = scene.add(Line([0, 0, 0], [4, 0, 0])) + graph = Graph() + graph.add_node("a", x=0, y=2, z=0) + graphobject = scene.add(graph) + + assert ComponentAnchor(pointobject.guid, "point").resolve(scene) == Point(1, 2, 3) + assert ComponentAnchor(lineobject.guid, "line", parameter=0.25).resolve(scene) == Point(1, 0, 0) + assert ComponentAnchor(graphobject.guid, "node", component="a").resolve(scene) == Point(0, 2, 0) + + +def test_component_anchor_supports_serializable_tuple_graph_keys(): + graph = Graph() + graph.add_node(("a", 0), x=0, y=0, z=0) + graph.add_node(("b", (1, 2)), x=2, y=0, z=0) + graph.add_edge(("a", 0), ("b", (1, 2))) + scene = Scene(context=None, _detect_context=False) + graphobject = scene.add(graph) + node = ComponentAnchor(graphobject.guid, "node", component=("a", 0)) + edge = ComponentAnchor( + graphobject.guid, + "edge", + component=(("a", 0), ("b", (1, 2))), + parameter=0.25, + ) + + restored_node = ComponentAnchor.from_jsonstring(node.to_jsonstring()) + restored_edge = ComponentAnchor.from_jsonstring(edge.to_jsonstring()) + + assert restored_node.resolve(scene) == Point(0, 0, 0) + assert restored_edge.resolve(scene) == Point(0.5, 0, 0) + + +def test_mixed_dimension_keeps_fixed_anchor_in_world_coordinates(): + scene = Scene(context=None, _detect_context=False) + pointobject = scene.add(Point(5, 0, 0)) + dimension = DistanceDimension( + PointAnchor([1, 0, 0]), + ComponentAnchor(pointobject.guid, "point"), + ) + scene.add_annotation(dimension) + + assert dimension.resolve(scene) == (Point(1, 0, 0), Point(5, 0, 0)) + + +def test_dimension_style_roundtrips_and_mutates_independently(): + style = DimensionStyle( + color=Color.red(), + line_width=2, + text_size=14, + arrow_size=9, + label_offset=-4, + ) + restored = DimensionStyle.from_jsonstring(style.to_jsonstring()) + + assert restored == style + assert restored.line_width == 2.0 + restored.line_width = 5 + assert restored.line_width == 5.0 + + +def test_distance_entries_receive_default_style_and_other_annotations_reject_it(): + scene = Scene(context=None, _detect_context=False) + dimension = DistanceDimension(PointAnchor([0, 0, 0]), PointAnchor([1, 0, 0])) + + entry = scene.add_annotation(dimension) + + assert entry.style == DimensionStyle() + entry.style = None + assert entry.style == DimensionStyle() + with pytest.raises(ValueError, match="only for DistanceDimension"): + scene.add_annotation(TextAnnotation("A", [0, 0, 0]), style=DimensionStyle()) + + +def test_annotation_remove_and_explicit_reattach_preserve_identity_and_state(): + item = TextAnnotation("A", [0, 0, 0]) + scene = Scene(context=None, _detect_context=False) + entry = scene.add_annotation(item, name="Label", show=False) + guid = entry.guid + + scene.remove_annotation(entry) + + assert entry.scene is None + assert entry.item is item + assert entry.guid == guid + assert entry.name == "Label" + assert entry.show is False + assert item.guid not in scene.item_store + + other = Scene(context=None, _detect_context=False) + other.add_annotation_entry(entry) + assert other.annotation(guid) is entry + assert entry.item is item + + +def test_shared_annotation_item_is_pruned_after_last_entry(): + item = TextAnnotation("Shared", [0, 0, 0]) + scene = Scene(context=None, _detect_context=False) + first = scene.add_annotation(item) + second = scene.add_annotation(item) + + scene.remove_annotation(first) + assert scene.item_store[item.guid] is item + + scene.remove_annotation(second) + assert item.guid not in scene.item_store + + +def test_unresolved_distance_reference_normalizes_style_when_bound(): + dimension = DistanceDimension(PointAnchor([0, 0, 0]), PointAnchor([1, 0, 0])) + scene = Scene(context=None, _detect_context=False) + entry = scene.add_annotation_reference(dimension.guid, name="Distance") + + assert entry.style is None + scene.bind(dimension) + + assert entry.item is dimension + assert entry.style == DimensionStyle() + entry.style = None + assert entry.style == DimensionStyle() + + +def test_annotation_and_spatial_bindings_reject_wrong_item_domains(): + text = TextAnnotation("A", [0, 0, 0]) + point = Point(0, 0, 0) + scene = Scene(context=None, _detect_context=False) + scene.add_annotation_reference(point.guid, name="Invalid annotation") + scene.add_reference(text.guid, name="Invalid spatial item") + + with pytest.raises(TypeError, match="scene-annotation item"): + scene.bind(point) + with pytest.raises(TypeError, match="Scene.annotations"): + scene.bind(text) + + assert scene.item_store == {} + + +def test_bound_text_reference_rejects_later_dimension_style_assignment(): + text = TextAnnotation("A", [0, 0, 0]) + scene = Scene(context=None, _detect_context=False) + entry = scene.add_annotation_reference(text.guid, name="Text") + scene.bind(text) + + with pytest.raises(ValueError, match="only for DistanceDimension"): + entry.style = DimensionStyle() + + +def test_scene_rejects_guid_collision_between_object_and_annotation(): + scene = Scene(context=None, _detect_context=False) + sceneobject = scene.add(Point(0, 0, 0)) + entry = SceneAnnotation(TextAnnotation("A", [0, 0, 0])) + entry._guid = sceneobject.guid + + with pytest.raises(ValueError, match="already stored"): + scene.add_annotation_entry(entry) + + +@pytest.mark.parametrize("field", ["line_width", "text_size", "arrow_size"]) +@pytest.mark.parametrize("value", [True, 0, -1, float("inf"), float("nan")]) +def test_dimension_style_rejects_invalid_positive_fields(field, value): + kwargs = {field: value} + with pytest.raises((TypeError, ValueError)): + DimensionStyle(**kwargs) + + +@pytest.mark.parametrize("value", [True, float("inf"), float("nan")]) +def test_dimension_style_rejects_invalid_label_offset(value): + with pytest.raises((TypeError, ValueError)): + DimensionStyle(label_offset=value) + + +def test_removed_or_unbound_components_are_explicitly_unresolved(): + graph = Graph() + graph.add_node("a", x=0, y=0, z=0) + graph.add_node("b", x=1, y=0, z=0) + graph.add_edge("a", "b") + scene = Scene(context=None, _detect_context=False) + graphobject = scene.add(graph) + anchor = ComponentAnchor(graphobject.guid, "edge", component=("a", "b"), parameter=0.5) + dimension = DistanceDimension(PointAnchor([0, 0, 0]), anchor) + + assert anchor.resolve(scene) == Point(0.5, 0, 0) + graph.delete_edge(("a", "b")) + assert anchor.resolve(scene) is None + assert dimension.resolve(scene) is None + assert dimension.distance(scene) is None + assert dimension.formatted_label(scene) is None + + restored_anchor = ComponentAnchor.from_jsonstring(anchor.to_jsonstring()) + assert restored_anchor == anchor + assert restored_anchor.resolve(scene) is None + + unbound_scene = Scene.from_jsonstring(scene.to_jsonstring()) + assert anchor.resolve(unbound_scene) is None + assert ComponentAnchor(uuid4(), "point").resolve(scene) is None + + +@pytest.mark.parametrize( + ("args", "error"), + [ + ((uuid4(), "point", 0, None), ValueError), + ((uuid4(), "vertex", None, None), TypeError), + ((uuid4(), "node", frozenset({0, 1}), None), TypeError), + ((uuid4(), "line", None, None), TypeError), + ((uuid4(), "line", None, -0.1), ValueError), + ((uuid4(), "edge", (0, 1), 1.1), ValueError), + ((uuid4(), "edge", (0,), 0.5), TypeError), + ], +) +def test_component_anchor_rejects_invalid_selector_schemas(args, error): + with pytest.raises(error): + ComponentAnchor(args[0], args[1], component=args[2], parameter=args[3]) + + +def test_annotation_validation_is_narrow_and_explicit(): + with pytest.raises(ValueError, match="positive"): + TextAnnotation("A", [0, 0, 0], height=0) + with pytest.raises(TypeError, match="number"): + TextAnnotation("A", [0, 0, 0], height=True) + with pytest.raises(ValueError, match="finite"): + TextAnnotation("A", [0, 0, 0], height=float("nan")) + with pytest.raises(ValueError, match="finite"): + TextAnnotation("A", [0, 0, 0], height=float("inf")) + with pytest.raises(ValueError, match="height mode"): + TextAnnotation("A", [0, 0, 0], height_mode="absolute") + with pytest.raises(ValueError, match="different"): + ArrowAnnotation([0, 0, 0], [0, 0, 0]) + with pytest.raises(ValueError, match="non-empty"): + DistanceDimension(PointAnchor([0, 0, 0]), PointAnchor([1, 0, 0]), unit="") + with pytest.raises(ValueError, match="non-negative"): + DistanceDimension(PointAnchor([0, 0, 0]), PointAnchor([1, 0, 0]), precision=-1) + with pytest.raises(TypeError, match="integer"): + DistanceDimension(PointAnchor([0, 0, 0]), PointAnchor([1, 0, 0]), precision=True) + + +def test_serialized_annotation_schemas_reject_unknown_fields(): + with pytest.raises(ValueError, match="Unknown text-annotation fields"): + TextAnnotation.__from_data__( + { + "text": "A", + "anchor": Point(0, 0, 0), + "height": 12.0, + "height_mode": "screen", + "horizontal_alignment": "left", + "vertical_alignment": "bottom", + "font": "renderer-specific.ttf", + } + ) + + with pytest.raises(ValueError, match="Unknown dimension-style fields"): + DimensionStyle.__from_data__( + { + **DimensionStyle().__data__, + "opacity": 0.5, + } + ) + + entry = SceneAnnotation(TextAnnotation("A", [0, 0, 0])) + with pytest.raises(ValueError, match="Unknown scene-annotation fields"): + SceneAnnotation.__from_data__( + { + **entry.__data__, + "parent": None, + } + ) diff --git a/tests/compas/scene/test_scene.py b/tests/compas/scene/test_scene.py index b7b61ff1a53..dd373231084 100644 --- a/tests/compas/scene/test_scene.py +++ b/tests/compas/scene/test_scene.py @@ -1,362 +1,562 @@ -import pytest # noqa: F401 -from compas.scene import context -from compas.scene import register -from compas.scene import Scene -from compas.scene import SceneObject -from compas.scene import SceneObjectNotRegisteredError +import subprocess +import sys +from typing import Any +from uuid import uuid4 + +import pytest + from compas.data import Data +from compas.datastructures import Graph +from compas.datastructures import VolMesh from compas.geometry import Box from compas.geometry import Frame +from compas.geometry import Plane +from compas.geometry import PlanarSurface +from compas.geometry import Point from compas.geometry import Translation -from compas.geometry import Transformation -from compas.scene import Group -from compas.datastructures import Tree -from compas.datastructures import Graph -from compas.datastructures import VolMesh - - -@pytest.fixture(autouse=True) -def reset_sceneobjects_registration(): - # before each test +from compas.geometry import Vector +from compas.scene import FrameObject +from compas.scene import GraphObject +from compas.scene import GeometryObject +from compas.scene import MeshObject +from compas.scene import PlaneObject +from compas.scene import Scene +from compas.scene import SceneAnnotation +from compas.scene import SceneNode +from compas.scene import SceneObject +from compas.scene import SceneOperationNotRegisteredError +from compas.scene import SceneStateError +from compas.scene import SceneStateField +from compas.scene import ShapeObject +from compas.scene import SurfaceObject +from compas.scene import TextAnnotation +from compas.scene import VectorObject +from compas.scene import VolMeshObject +from compas.scene import get_sceneobject_cls +from compas.scene import register_scene_operation +from compas.scene.context import SCENEOBJECT_TYPES +from compas.scene.context import SCENE_OPERATIONS +import compas.scene.context as scene_context + + +@pytest.fixture +def operation_registry(): + original = {context: {cls: dict(operations) for cls, operations in types.items()} for context, types in SCENE_OPERATIONS.items()} + discovered = scene_context._OPERATIONS_DISCOVERED + SCENE_OPERATIONS.clear() + scene_context._OPERATIONS_DISCOVERED = True yield - # after each test, reset scene objects - context.ITEM_SCENEOBJECT.clear() - - -def register_fake_context(): - register(FakeItem, FakeSceneObject, context="fake") - - -class FakeSceneObject(SceneObject): - def draw(self): - pass - - def clear(self): - pass + SCENE_OPERATIONS.clear() + SCENE_OPERATIONS.update(original) + scene_context._OPERATIONS_DISCOVERED = discovered -class FakeSubSceneObject(SceneObject): - def draw(self): - pass +def test_scene_add_returns_a_stable_semantic_type(): + box = Box() + scene = Scene(context="Viewer") - def clear(self): - pass + sceneobject = scene.add(box) + assert type(sceneobject) is ShapeObject + assert get_sceneobject_cls(box) is ShapeObject + assert sceneobject.item is box -class FakeItem(Data): - pass +@pytest.mark.parametrize( + ("item", "sceneobject_type"), + [ + (Point(1, 2, 3), GeometryObject), + (Box(), ShapeObject), + (PlanarSurface(), SurfaceObject), + (Frame.worldXY(), FrameObject), + (Plane.worldXY(), PlaneObject), + (Vector(1, 2, 3), VectorObject), + ], +) +def test_sceneobject_type_dispatch_is_exact_and_context_independent(item, sceneobject_type): + assert get_sceneobject_cls(item) is sceneobject_type + assert type(Scene(context="Viewer").add(item)) is sceneobject_type -class FakeSubItem(FakeItem): - pass +def test_semantic_fields_are_not_added_to_generic_geometry_objects(): + sceneobject = Scene().add(Point(1, 2, 3)) -def test_get_sceneobject_cls_with_orderly_registration(): - register(FakeItem, FakeSceneObject, context="fake") - register(FakeSubItem, FakeSubSceneObject, context="fake") - item = FakeItem() - sceneobject = SceneObject(item, context="fake") - assert isinstance(sceneobject, FakeSceneObject) + assert not hasattr(sceneobject, "u") + assert not hasattr(sceneobject, "v") - item = FakeSubItem() - sceneobject = SceneObject(item, context="fake") - assert isinstance(sceneobject, FakeSubSceneObject) +def test_plane_object_has_one_public_size_field(): + sceneobject = Scene().add(Plane.worldXY(), size=2.0) -def test_get_sceneobject_cls_with_out_of_order_registration(): - register(FakeSubItem, FakeSubSceneObject, context="fake") - register(FakeItem, FakeSceneObject, context="fake") - item = FakeItem() - sceneobject = SceneObject(item, context="fake") - assert isinstance(sceneobject, FakeSceneObject) + assert sceneobject.size == 2.0 + assert not hasattr(sceneobject, "planesize") - item = FakeSubItem() - sceneobject = SceneObject(item, context="fake") - assert isinstance(sceneobject, FakeSubSceneObject) +def test_scene_node_contains_hierarchy_only(): + scene = Scene() + sceneobject = scene.add(Box(), name="Box", show=False) -def test_sceneobject_auto_context_discovery(): - register_fake_context() + assert sceneobject.node.__data__ == {"object": str(sceneobject.guid), "children": []} + assert not hasattr(sceneobject.node, "item_guid") + assert not hasattr(sceneobject.node, "show") - item = FakeItem() - sceneobject = SceneObject(item) - assert isinstance(sceneobject, FakeSceneObject) +def test_scene_uses_sceneobject_guid_as_sole_hierarchy_key(): + scene = Scene() + parent = scene.add(Box()) + child = scene.add(Box(), parent=parent) + assert scene.node(parent.guid).object_guid == parent.guid + assert scene.node(child.guid).parent.object_guid == parent.guid + assert child.parent is parent + assert parent.children == (child,) -def test_sceneobject_auto_context_discovery_no_context(): - with pytest.raises(SceneObjectNotRegisteredError): - item = FakeSubItem() - _ = SceneObject(item) +def test_scene_rejects_a_second_node_for_one_object(): + scene = Scene() + sceneobject = scene.add(Box()) -def test_explicit_sceneobject_type_is_only_a_factory_option(): - sceneobject = SceneObject(FakeItem(), sceneobject_type=FakeSceneObject) + with pytest.raises(ValueError, match="already belongs"): + scene.add_object(sceneobject) - assert isinstance(sceneobject, FakeSceneObject) - assert "sceneobject_type" not in sceneobject.attributes +def test_remove_and_explicit_reattach_preserve_identity_and_state(): + scene = Scene() + sceneobject = scene.add(Box(), name="Box", opacity=0.25, show=False) + guid = sceneobject.guid -def test_context_detection_does_not_guess_between_registered_contexts(): - register(FakeItem, FakeSceneObject, context="first") - register(FakeItem, FakeSceneObject, context="second") + scene.remove(sceneobject) + assert sceneobject.scene is None + assert sceneobject.guid == guid + assert sceneobject.name == "Box" + assert sceneobject.opacity == 0.25 + assert sceneobject.show is False - assert context.detect_current_context() is None + other = Scene() + other.add_object(sceneobject) + assert sceneobject.scene is other + assert sceneobject.guid == guid -def test_sceneobject_transform(): +def test_group_children_use_only_explicit_state(): scene = Scene() - sceneobj1 = scene.add(Box()) - sceneobj1.transformation = Translation.from_vector([10.0, 0.0, 0.0]) - assert sceneobj1.worldtransformation == sceneobj1.transformation - assert sceneobj1.worldtransformation == Translation.from_vector([10.0, 0.0, 0.0]) - assert sceneobj1.frame == Frame([10.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]) - assert sceneobj1.frame.to_transformation() == Translation.from_vector([10.0, 0.0, 0.0]) - - sceneobj2 = scene.add(Box(), parent=sceneobj1) - sceneobj2.transformation = Translation.from_vector([10.0, 10.0, 0.0]) - assert sceneobj2.worldtransformation == sceneobj1.transformation * sceneobj2.transformation - assert sceneobj2.worldtransformation == Translation.from_vector([20.0, 10.0, 0.0]) - assert sceneobj2.frame == Frame([20.0, 10.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]) - assert sceneobj2.frame.to_transformation() == Translation.from_vector([20.0, 10.0, 0.0]) - - sceneobj3 = scene.add(Box(), parent=sceneobj2) - sceneobj3.transformation = Translation.from_vector([10.0, 10.0, 10.0]) - assert sceneobj3.worldtransformation == sceneobj1.transformation * sceneobj2.transformation * sceneobj3.transformation - assert sceneobj3.worldtransformation == Translation.from_vector([30.0, 20.0, 10.0]) - assert sceneobj3.frame == Frame([30.0, 20.0, 10.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]) - assert sceneobj3.frame.to_transformation() == Translation.from_vector([30.0, 20.0, 10.0]) - - -def test_sceneobject_settings_store_only_local_transformation(): - scene = Scene() - parent = scene.add(Box()) - child = scene.add(Box(), parent=parent) - parent.transformation = Translation.from_vector([10.0, 0.0, 0.0]) - child.transformation = Translation.from_vector([0.0, 5.0, 0.0]) + group = scene.add_group("Group", show=False) + child = group.add(Box()) - assert "frame" not in parent.settings - assert "frame" not in child.settings - assert parent.settings["transformation"] == parent.transformation - assert child.settings["transformation"] == child.transformation + assert group.show is False + assert child.show is True -def test_sceneobject_frame_and_worldtransformation_setters(): - """Test that frame and worldtransformation setters work correctly.""" - scene = Scene() +def test_draw_and_clear_resolve_context_operations_by_mro(operation_registry): + calls = [] - # Test on root object - root_obj = scene.add(Box()) - test_frame = Frame([10.0, 20.0, 30.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]) - root_obj.frame = test_frame - assert root_obj.frame == test_frame - assert root_obj.worldtransformation == Transformation.from_frame(test_frame) - - # Test worldtransformation setter on root object - test_transform = Translation.from_vector([5.0, 10.0, 15.0]) - root_obj.worldtransformation = test_transform - assert root_obj.worldtransformation == test_transform - assert root_obj.transformation == test_transform - - # Test with parent-child relationship - parent_obj = scene.add(Box()) - child_obj = scene.add(Box(), parent=parent_obj) - parent_obj.transformation = Translation.from_vector([10.0, 0.0, 0.0]) - - # Test frame setter with parent - child_frame = Frame([30.0, 20.0, 10.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]) - child_obj.frame = child_frame - assert child_obj.frame == child_frame - expected_local = parent_obj.worldtransformation.inverse() * Transformation.from_frame(child_frame) - assert child_obj.transformation == expected_local - - # Test worldtransformation setter with parent - child_world_transform = Translation.from_vector([50.0, 30.0, 20.0]) - child_obj.worldtransformation = child_world_transform - assert child_obj.worldtransformation == child_world_transform - expected_local = parent_obj.worldtransformation.inverse() * child_world_transform - assert child_obj.transformation == expected_local - - -def test_graphobject_coordinate_cache_tracks_ancestor_transformations(): - scene = Scene() - parent = scene.add_group("Parent") - graph = Graph.from_nodes_and_edges([(0, 0, 0)], []) - graphobject = scene.add(graph, parent=parent) + def draw(scene, sceneobject, runtime): + calls.append(("draw", sceneobject.guid, runtime)) + return ["handle"] - assert graphobject.node_xyz[0] == [0.0, 0.0, 0.0] + def clear(scene, sceneobject, runtime, resources): + calls.append(("clear", sceneobject.guid, runtime, resources)) - parent.transformation = Translation.from_vector([1.0, 2.0, 3.0]) + register_scene_operation("Test", SceneObject, "draw", draw) + register_scene_operation("Test", SceneObject, "clear", clear) + scene = Scene(context="Test") + sceneobject = scene.add(Box()) - assert graphobject.node_xyz[0] == [1.0, 2.0, 3.0] + assert sceneobject.draw(runtime="runtime") == ["handle"] + sceneobject.clear(runtime="runtime") + assert calls == [ + ("draw", sceneobject.guid, "runtime"), + ("clear", sceneobject.guid, "runtime", ("handle",)), + ] -def test_graphobject_explicit_coordinates_are_not_ancestor_transform_cache(): - scene = Scene() - parent = scene.add_group("Parent") - graph = Graph.from_nodes_and_edges([(0, 0, 0)], []) - graphobject = scene.add(graph, parent=parent) - graphobject.node_xyz = {0: [4.0, 5.0, 6.0]} +def test_annotation_draw_and_clear_use_shared_context_registry(operation_registry): + calls = [] - parent.transformation = Translation.from_vector([1.0, 2.0, 3.0]) + def draw(scene, entry, runtime): + calls.append(("draw", entry.guid, runtime)) + return ["annotation-handle"] - assert graphobject.node_xyz[0] == [4.0, 5.0, 6.0] + def clear(scene, entry, runtime, resources): + calls.append(("clear", entry.guid, runtime, resources)) + register_scene_operation("Test", SceneAnnotation, "draw", draw) + register_scene_operation("Test", SceneAnnotation, "clear", clear) + scene = Scene(context="Test") + entry = scene.add_annotation(TextAnnotation("A", [0, 0, 0])) -def test_graphobject_invalidate_refreshes_coordinates_after_graph_mutation(): - scene = Scene() - graph = Graph.from_nodes_and_edges([(0, 0, 0)], []) - graphobject = scene.add(graph) + assert entry.draw(runtime="runtime") == ["annotation-handle"] + entry.clear(runtime="runtime") + assert calls == [ + ("draw", entry.guid, "runtime"), + ("clear", entry.guid, "runtime", ("annotation-handle",)), + ] - assert graphobject.node_xyz[0] == [0.0, 0.0, 0.0] - graph.node_attributes(0, ["x", "y", "z"], [1.0, 2.0, 3.0]) - assert graphobject.node_xyz[0] == [0.0, 0.0, 0.0] +def test_context_changes_do_not_replace_scene_objects(operation_registry): + def draw(scene, sceneobject, runtime): + return [] - graphobject.invalidate() + register_scene_operation("A", SceneObject, "draw", draw) + register_scene_operation("B", SceneObject, "draw", draw) + scene = Scene(context="A") + sceneobject = scene.add(Box()) - assert graphobject.node_xyz[0] == [1.0, 2.0, 3.0] + scene.draw(context="A") + scene.draw(context="B") + assert scene.object(sceneobject.guid) is sceneobject -def test_volmeshobject_coordinate_cache_tracks_ancestor_transformations(): - scene = Scene() - parent = scene.add_group("Parent") - volmesh = VolMesh.from_meshgrid(1, 1, 1, 1, 1, 1) - volmeshobject = scene.add(volmesh, parent=parent) - vertex = next(volmesh.vertices()) - xyz = volmeshobject.vertex_xyz[vertex] - parent.transformation = Translation.from_vector([1.0, 2.0, 3.0]) +def test_duplicate_scene_operation_registration_fails(operation_registry): + def first(*args): + return [] - assert volmeshobject.vertex_xyz[vertex] == [xyz[0] + 1.0, xyz[1] + 2.0, xyz[2] + 3.0] + def second(*args): + return [] + register_scene_operation("Test", SceneObject, "draw", first) + with pytest.raises(ValueError, match="already registered"): + register_scene_operation("Test", SceneObject, "draw", second) -def test_volmeshobject_invalidate_refreshes_coordinates_after_volmesh_mutation(): - scene = Scene() - volmesh = VolMesh.from_meshgrid(1, 1, 1, 1, 1, 1) - volmeshobject = scene.add(volmesh) - vertex = next(volmesh.vertices()) - _ = volmeshobject.vertex_xyz - volmesh.vertex_attributes(vertex, ["x", "y", "z"], [1.0, 2.0, 3.0]) - volmeshobject.invalidate() +def test_missing_scene_operation_names_context_type_and_operation(operation_registry): + scene = Scene(context="Missing") + sceneobject = scene.add(Box()) - assert volmeshobject.vertex_xyz[vertex] == [1.0, 2.0, 3.0] + with pytest.raises(SceneOperationNotRegisteredError, match="draw.*ShapeObject.*Missing"): + sceneobject.draw() -def test_scene_clear(): - scene = Scene() - sceneobj1 = scene.add(Box()) - sceneobj2 = scene.add(Box(), parent=sceneobj1) - sceneobj3 = scene.add(Box(), parent=sceneobj2) # noqa: F841 +def test_scene_node_rejects_invalid_data(): + with pytest.raises(ValueError, match="Unknown scene-node fields: extra"): + SceneNode.__from_data__({"object": str(uuid4()), "children": [], "extra": True}) + with pytest.raises(ValueError, match="Missing scene-node fields: children"): + SceneNode.__from_data__({"object": str(uuid4())}) + with pytest.raises(ValueError, match="UUID string"): + SceneNode.__from_data__({"object": "invalid", "children": []}) + with pytest.raises(TypeError, match="children"): + SceneNode.__from_data__({"object": str(uuid4()), "children": ()}) + with pytest.raises(TypeError, match="object_guid should be a UUID"): + invalid_guid: Any = "invalid" + SceneNode(invalid_guid) - assert len(scene.objects) == 3 - scene.clear(clear_context=False, clear_scene=True) +def test_remove_clears_resources_for_every_context(operation_registry): + calls = [] - assert len(scene.objects) == 0 + def draw(scene, sceneobject, runtime): + return [f"{runtime}-handle"] + def clear(scene, sceneobject, runtime, resources): + calls.append((sceneobject.guid, runtime, resources)) -def test_scene_owns_tree_with_group_root(): - scene = Scene() + for context in ("A", "B"): + register_scene_operation(context, SceneObject, "draw", draw) + register_scene_operation(context, SceneObject, "clear", clear) + scene = Scene(context=None, _detect_context=False) + sceneobject = scene.add(Box()) + sceneobject.draw(context="A", runtime="a") + sceneobject.draw(context="B", runtime="b") - assert not isinstance(scene, Tree) - assert isinstance(scene.tree, Tree) - assert isinstance(scene.root, Group) - assert scene.root.tree is scene.tree - assert all(not isinstance(node, SceneObject) for node in scene.tree.nodes) + scene.remove(sceneobject) + assert calls == [ + (sceneobject.guid, "a", ("a-handle",)), + (sceneobject.guid, "b", ("b-handle",)), + ] -def test_scene_stores_objects_and_items_by_guid(): - scene = Scene() - box = Box() - boxobject = scene.add(box) - assert scene.object_store[boxobject.guid] is boxobject - assert scene.item_store[box.guid] is box - assert boxobject.item_guid == box.guid - assert boxobject.item is box - assert not hasattr(boxobject, "_detached_item") - assert not hasattr(boxobject, "_item") - assert scene.tree.root.children[0].object_guid == boxobject.guid +def test_repeated_draw_clears_the_previous_resource_before_replacing_it(operation_registry): + calls = [] + def draw(scene, sceneobject, runtime): + calls.append(("draw", runtime)) + return [f"{runtime}-handle"] -def test_scene_reuses_shared_item_and_prunes_it_after_last_reference(): - scene = Scene() - box = Box() - first = scene.add(box) - second = scene.add(box) - - assert first.item is second.item is box - assert list(scene.item_store) == [box.guid] + def clear(scene, sceneobject, runtime, resources): + calls.append(("clear", runtime, resources)) - scene.remove(first) - assert scene.item_store[box.guid] is box - assert first.scene is None - assert first.item is box + register_scene_operation("Test", SceneObject, "draw", draw) + register_scene_operation("Test", SceneObject, "clear", clear) + scene = Scene(context="Test") + sceneobject = scene.add(Box()) - scene.remove(second) - assert box.guid not in scene.item_store + sceneobject.draw(runtime="first") + sceneobject.draw(runtime="second") + sceneobject.clear() + assert calls == [ + ("draw", "first"), + ("clear", "first", ("first-handle",)), + ("draw", "second"), + ("clear", "second", ("second-handle",)), + ] -def test_scene_replaces_an_objects_item_in_the_store(): - scene = Scene() - original = Box(1.0) - replacement = Box(2.0) - sceneobject = scene.add(original) - - scene.replace_item(sceneobject, replacement) - assert sceneobject.item is replacement - assert sceneobject.item_guid == replacement.guid - assert replacement.guid in scene.item_store - assert original.guid not in scene.item_store +def test_clear_without_a_context_or_resources_is_backend_neutral(): + scene = Scene(context=None, _detect_context=False) + scene.add(Box()) + scene.add_annotation(TextAnnotation("A", [0, 0, 0])) + scene.clear() -def test_group_creation(): - scene = Scene() - group = scene.add_group("TestGroup") - assert isinstance(group, Group) - assert group.name == "TestGroup" - assert group.parent == scene.root + assert scene.objects == [] + assert scene.annotations == () -def test_group_add_item(): +def test_world_transformation_and_frame_setter_preserve_local_coordinates(): scene = Scene() - group = scene.add_group("TestGroup") - box = Box() - box_obj = group.add(box) - assert isinstance(box_obj, SceneObject) - assert box_obj.parent is group - assert box_obj.item is box + parent = scene.add(Box(), transformation=Translation.from_vector([1, 0, 0])) + child = scene.add(Box(), parent=parent, transformation=Translation.from_vector([0, 2, 0])) + assert child.frame.point == [1, 2, 0] + child.frame = Frame([4, 5, 6], [1, 0, 0], [0, 1, 0]) -def test_group_add_from_list(): - scene = Scene() - group = scene.add_group("TestGroup") - boxes = [Box() for _ in range(3)] - box_objs = group.add_from_list(boxes) - assert len(box_objs) == 3 - for box_obj in box_objs: - assert isinstance(box_obj, SceneObject) - assert box_obj.parent is group + assert child.transformation.translation_vector == [3, 5, 6] + assert child.frame.point == [4, 5, 6] -def test_group_kwargs_inheritance(): +def test_graph_and_volmesh_coordinates_invalidate_on_ancestor_transform(): + graph = Graph() + graph.add_node(0, x=0, y=0, z=0) + volmesh = VolMesh.from_vertices_and_cells([[0, 0, 0]], []) scene = Scene() - group = scene.add_group("TestGroup", show=False) - box = Box() - box_obj = group.add(box) - assert not box_obj.show # Should inherit show=False from group + parent = scene.add_group("Parent") + graphobject = scene.add(graph, parent=parent) + volmeshobject = scene.add(volmesh, parent=parent) + assert isinstance(graphobject, GraphObject) + assert isinstance(volmeshobject, VolMeshObject) + assert graphobject.node_xyz[0] == [0, 0, 0] + assert volmeshobject.vertex_xyz[0] == [0, 0, 0] + + parent.transformation = Translation.from_vector([1, 2, 3]) + assert graphobject.node_xyz[0] == [1, 2, 3] + assert volmeshobject.vertex_xyz[0] == [1, 2, 3] + + +def test_scene_state_field_declarations_are_fully_validated(): + invalid_editable: Any = "yes" + invalid_update: Any = "update" + + class InvalidDefault(SceneObject): + __scene_state_namespace__ = "test.invalid.default" + __scene_state_fields__ = (SceneStateField("value", int, default=1),) + + class InvalidOmission(SceneObject): + __scene_state_namespace__ = "test.invalid.omission" + __scene_state_fields__ = (SceneStateField("value", int, required=False, omit_default=True),) + + class DuplicateAttribute(SceneObject): + __scene_state_namespace__ = "test.duplicate.attribute" + __scene_state_fields__ = ( + SceneStateField("one", int, attribute_name="value"), + SceneStateField("two", int, attribute_name="value"), + ) + + class UpdateWithoutEditable(SceneObject): + __scene_state_namespace__ = "test.update.without.editable" + __scene_state_fields__ = (SceneStateField("value", int, update=lambda owner, value: None),) + + class InvalidEditable(SceneObject): + __scene_state_namespace__ = "test.invalid.editable" + __scene_state_fields__ = (SceneStateField("value", int, editable=invalid_editable),) + + class InvalidUpdate(SceneObject): + __scene_state_namespace__ = "test.invalid.update" + __scene_state_fields__ = (SceneStateField("value", int, editable=True, update=invalid_update),) + + with pytest.raises(SceneStateError, match="default and be required"): + InvalidDefault.scene_state_fields() + with pytest.raises(SceneStateError, match="undeclared default"): + InvalidOmission.scene_state_fields() + with pytest.raises(SceneStateError, match="Duplicate scene-state adapter attribute"): + DuplicateAttribute.scene_state_fields() + with pytest.raises(SceneStateError, match="cannot define update unless editable"): + UpdateWithoutEditable.scene_state_fields() + with pytest.raises(SceneStateError, match="Invalid editable flag"): + InvalidEditable.scene_state_fields() + with pytest.raises(SceneStateError, match="Invalid update callback"): + InvalidUpdate.scene_state_fields() + + +def test_editable_attribute_declarations_compose_state_and_non_state_fields(): + def update_replaced(owner, value): + owner.replaced = value + + class BaseObject(SceneObject): + __editable_attributes__ = { + "first": None, + "replaced": None, + } + + __scene_state_namespace__ = "test.editable.base" + __scene_state_fields__ = (SceneStateField("state", int, required=False, editable=True),) + + class DerivedObject(BaseObject): + __editable_attributes__ = { + "replaced": update_replaced, + "last": None, + } + + __scene_state_namespace__ = "test.editable.derived" + __scene_state_fields__ = (SceneStateField("derived_state", int, required=False, editable=True),) + + attributes = DerivedObject.editable_attributes() + + assert list(attributes) == ["name", "opacity", "first", "replaced", "state", "last", "derived_state"] + assert attributes["replaced"] is update_replaced + assert attributes["state"] is None + with pytest.raises(TypeError): + mutable_attributes: Any = attributes + mutable_attributes["extra"] = None + + +def test_editable_attribute_declarations_are_fully_validated(): + class InvalidContainer(SceneObject): + __editable_attributes__ = () + + class InvalidName(SceneObject): + __editable_attributes__ = {1: None} + + class EmptyName(SceneObject): + __editable_attributes__ = {"": None} + + class InvalidUpdate(SceneObject): + __editable_attributes__ = {"value": "invalid"} + + class DuplicateStateField(SceneObject): + __editable_attributes__ = {"value": None} + __scene_state_namespace__ = "test.editable.duplicate" + __scene_state_fields__ = (SceneStateField("value", int, required=False, editable=True),) + + with pytest.raises(TypeError, match="InvalidContainer.*mapping"): + InvalidContainer.editable_attributes() + with pytest.raises(TypeError, match="names.*strings"): + InvalidName.editable_attributes() + with pytest.raises(ValueError, match="cannot be empty"): + EmptyName.editable_attributes() + with pytest.raises(TypeError, match="update.*callable or None"): + InvalidUpdate.editable_attributes() + with pytest.raises(SceneStateError, match="duplicates"): + DuplicateStateField.editable_attributes() + + +def test_update_editable_attribute_uses_default_and_declared_data_mutation(): + calls = [] + + def update_value(owner, value): + calls.append((owner, value)) + owner.value = value * 2 + + def reject_value(owner, value): + raise ValueError("rejected") + + class EditableObject(SceneObject): + __editable_attributes__ = { + "name": None, + } + __scene_state_namespace__ = "test.editable.update" + __scene_state_fields__ = ( + SceneStateField("value", (int, float), required=False, editable=True, update=update_value), + SceneStateField("rejected", (int, float), required=False, editable=True, update=reject_value), + ) + + def __init__(self): + super().__init__() + self.value = 1 + self.rejected = 2 + + sceneobject = EditableObject() + sceneobject.update_editable_attribute("name", "Updated") + sceneobject.update_editable_attribute("value", 3) + + assert sceneobject.name == "Updated" + assert sceneobject.value == 6 + assert calls == [(sceneobject, 3)] + with pytest.raises(ValueError, match="rejected"): + sceneobject.update_editable_attribute("rejected", 4) + assert sceneobject.rejected == 2 + with pytest.raises(KeyError, match="not editable: show"): + sceneobject.update_editable_attribute("show", False) + + +def test_builtin_editable_attributes_match_stable_object_state(): + assert list(SceneObject.editable_attributes()) == ["name", "opacity"] + assert list(GeometryObject.editable_attributes()) == [ + "name", + "opacity", + "show_points", + "show_lines", + "show_surfaces", + "pointcolor", + "linecolor", + "surfacecolor", + "linewidth", + "pointsize", + ] + assert list(MeshObject.editable_attributes()) == [ + "name", + "opacity", + "show_vertices", + "show_edges", + "show_faces", + "vertexcolor", + "edgecolor", + "facecolor", + "edgewidth", + "vertexsize", + ] + assert list(GraphObject.editable_attributes()) == [ + "name", + "opacity", + "show_nodes", + "show_edges", + "nodecolor", + "edgecolor", + "edgewidth", + "nodesize", + ] + assert "u" not in ShapeObject.editable_attributes() + assert "size" not in FrameObject.editable_attributes() + assert "hide_coplanaredges" not in MeshObject.editable_attributes() + assert "show_vertices" not in VolMeshObject.editable_attributes() + assert "__editable_attributes__" not in GeometryObject.__dict__ + assert "__editable_attributes__" not in MeshObject.__dict__ + assert "__editable_attributes__" not in GraphObject.__dict__ + + +def test_editable_attribute_declarations_are_runtime_only_and_graphics_free(): + sceneobject = GeometryObject() + + assert "editable" not in sceneobject.__data__ + assert "update" not in sceneobject.__data__ + + code = "import sys; import compas.scene; assert 'PySide6' not in sys.modules; assert 'OpenGL' not in sys.modules" + subprocess.run([sys.executable, "-c", code], check=True) + + +def test_sceneobject_discovery_is_not_inferred_from_registry_emptiness(monkeypatch): + class Item(Data): + pass -def test_group_hierarchy(): - scene = Scene() - parent_group = scene.add_group("ParentGroup") - child_group = parent_group.add(Group("ChildGroup")) - box = Box() - box_obj = child_group.add(box) + class ItemObject(SceneObject): + pass - assert box_obj.parent is child_group - assert child_group.parent is parent_group - assert parent_group.parent is scene.root + original = dict(SCENEOBJECT_TYPES) + discovered = scene_context._SCENEOBJECTS_DISCOVERED + SCENEOBJECT_TYPES.clear() + SCENEOBJECT_TYPES[Box] = GeometryObject + scene_context._SCENEOBJECTS_DISCOVERED = False + + def discover(): + SCENEOBJECT_TYPES[Item] = ItemObject + + monkeypatch.setattr(scene_context, "register_scene_objects", discover) + try: + assert get_sceneobject_cls(Item()) is ItemObject + finally: + SCENEOBJECT_TYPES.clear() + SCENEOBJECT_TYPES.update(original) + scene_context._SCENEOBJECTS_DISCOVERED = discovered diff --git a/tests/compas/scene/test_scene_serialisation.py b/tests/compas/scene/test_scene_serialisation.py index 6f0cf5acf8c..71e31e4520f 100644 --- a/tests/compas/scene/test_scene_serialisation.py +++ b/tests/compas/scene/test_scene_serialisation.py @@ -1,222 +1,286 @@ -import compas +from uuid import uuid4 + +import pytest -import pytest # noqa: F401 -from compas.data import Data -from compas.scene import Scene from compas.geometry import Box -from compas.geometry import Capsule -from compas.geometry import Circle -from compas.geometry import Cone -from compas.geometry import Cylinder -from compas.geometry import Ellipse -from compas.geometry import Frame -from compas.geometry import Line -from compas.geometry import Point -from compas.geometry import Polygon -from compas.geometry import Polyhedron -from compas.geometry import Polyline -from compas.geometry import Sphere -from compas.geometry import Torus from compas.geometry import Translation -from compas.geometry import Vector -from compas.geometry import Plane -from compas.datastructures import Mesh from compas.datastructures import Graph +from compas.datastructures import Mesh from compas.datastructures import VolMesh -from compas.scene import Group - - -@pytest.fixture -def items(): - box = Box.from_width_height_depth(1, 1, 1) - capsule = Capsule(0.5, 1, Frame.worldXY()) - circle = Circle(1, Frame.worldXY()) - cone = Cone(1, 1, Frame.worldXY()) - cylinder = Cylinder(1, 1, Frame.worldXY()) - line = Line(Point(0, 0, 0), Point(1, 1, 1)) - point = Point(0, 0, 0) - polygon = Polygon.from_sides_and_radius_xy(5, 1) - polyhedron = Polyhedron.from_platonicsolid(4) - polyline = Polyline([[0, 0, 0], [1, 0, 0], [1, 0, 1]]) - sphere = Sphere(1) - torus = Torus(1, 0.3, Frame.worldXY()) - vector = Vector(0, 0, 1) - ellipse = Ellipse(1, 0.5, Frame.worldXY()) - frame = Frame.worldXY() - plane = Plane(Point(0, 0, 0), Vector(0, 0, 1)) - mesh = Mesh.from_polyhedron(8) - graph = Graph.from_nodes_and_edges([(0, 0, 0), (0, -1.5, 0), (-1, 1, 0), (1, 1, 0)], [(0, 1), (0, 2), (0, 3)]) - volmesh = VolMesh.from_meshgrid(1, 1, 1, 2, 2, 2) - group = Group(name="My Group") - - return [ - box, - capsule, - circle, - cone, - cylinder, - line, - point, - polygon, - polyhedron, - polyline, - sphere, - torus, - vector, - ellipse, - frame, - plane, - mesh, - graph, - volmesh, - group, - ] - +from compas.scene import GraphObject +from compas.scene import GeometryObject +from compas.scene import MeshObject +from compas.scene import FrameObject +from compas.scene import PlaneObject +from compas.scene import ShapeObject +from compas.scene import SurfaceObject +from compas.scene import VectorObject +from compas.scene import Scene +from compas.scene import SceneItemNotBoundError +from compas.scene import SceneObject +from compas.scene import SceneStateField +from compas.scene import TextAnnotation +from compas.scene import VolMeshObject + + +def test_scene_roundtrip_restores_stable_objects_and_hierarchy_without_items(): + scene = Scene("Reference only") + parent_item = Box(1) + child_item = Box(2) + parent = scene.add(parent_item, name="Parent", show=False) + scene.add(child_item, name="Child", parent=parent) + parent.transformation = Translation.from_vector([1, 0, 0]) + + restored = Scene.from_jsonstring(scene.to_jsonstring()) + + restored_parent = restored.find_by_name("Parent") + restored_child = restored.find_by_name("Child") + assert isinstance(restored_parent, GeometryObject) + assert restored_parent.guid == parent.guid + assert restored_parent.show is False + assert restored_parent.transformation == parent.transformation + assert restored_child.parent is restored_parent + assert restored.item_store == {} + with pytest.raises(SceneItemNotBoundError, match=str(parent_item.guid)): + _ = restored_parent.item + + +def test_independent_items_bind_with_shared_identity(): + box = Box() + scene = Scene() + scene.add(box, name="First") + scene.add(box, name="Second") + restored = Scene.from_jsonstring(scene.to_jsonstring()) -def assert_is_data_equal(obj1, obj2, path=""): - if type(obj1) is not type(obj2): - print("Type mismatch: {} != {} for {}:{} and {}:{}".format(type(obj1), type(obj2), path, obj1, path, obj2)) - return False + restored.bind(box) - if isinstance(obj1, (list, tuple)): - if len(obj1) != len(obj2): - print("Length mismatch: {} != {} for {} and {}".format(len(obj1), len(obj2), path, path)) - return False + assert restored.objects[0].item is restored.objects[1].item is box - for i, (item1, item2) in enumerate(zip(obj1, obj2)): - if not assert_is_data_equal(item1, item2, path="{}[{}]".format(path, i)): - return False - return True +def test_scene_serialization_separates_objects_from_hierarchy(): + scene = Scene() + box = scene.add(Box(), name="Box") + data = scene.__data__ - elif isinstance(obj1, dict): - if set(obj1.keys()) != set(obj2.keys()): - print("Key mismatch: {} != {} for {} and {}".format(set(obj1.keys()), set(obj2.keys()), path, path)) - return False + assert data["version"] == 3 + assert [obj.guid for obj in data["objects"]] == [scene.root.guid, box.guid] + assert data["annotations"] == [] + assert data["hierarchy"] == { + "object": str(scene.root.guid), + "children": [{"object": str(box.guid), "children": []}], + } - for key in obj1: - if not assert_is_data_equal(obj1[key], obj2[key], path='{}["{}"]'.format(path, key)): - return False - return True +def test_scene_serialization_keeps_ordered_annotations_outside_hierarchy(): + scene = Scene() + first = scene.add_annotation(TextAnnotation("First", [0, 0, 0])) + second = scene.add_annotation(TextAnnotation("Second", [1, 0, 0]), show=False) - elif isinstance(obj1, Data): - return assert_is_data_equal(obj1.__data__, obj2.__data__, path="{}.__data__".format(path)) + data = scene.__data__ + restored = Scene.from_jsonstring(scene.to_jsonstring()) - else: - if obj1 != obj2: - print("Value mismatch: {} != {} for {}:{} and {}:{}".format(obj1, obj2, path, obj1, path, obj2)) - return False - else: - return True + assert data["annotations"] == [first, second] + assert [entry.guid for entry in restored.annotations] == [first.guid, second.guid] + assert restored.annotations[1].show is False + assert all(entry.guid not in restored.object_store for entry in restored.annotations) -def test_scene_serialisation(items): - scene1 = Scene() - for item in items: - scene1.add(item) +def test_scene_schema_v3_is_a_clean_break(): + data = Scene().__data__ + data["version"] = 2 - scene2 = Scene.from_jsonstring(scene1.to_jsonstring()) - assert assert_is_data_equal(scene1, scene2) + with pytest.raises(ValueError, match="Unsupported scene schema version: 2"): + Scene.__from_data__(data) -def test_scene_serialisation_preserves_shared_items(): - box = Box() +def test_unknown_namespaced_sceneobject_state_roundtrips(): scene = Scene() - scene.add(box, name="First") - scene.add(box, name="Second") + obj = scene.add_reference( + uuid4(), + name="External", + extensions={"org.example": {"value": 7}}, + ) - reconstructed = Scene.from_jsonstring(scene.to_jsonstring()) + restored = Scene.from_jsonstring(scene.to_jsonstring()) + restored_obj = restored.object(obj.guid) - assert reconstructed.objects[0].item is reconstructed.objects[1].item + assert restored_obj.__data__["extensions"] == {"org.example": {"value": 7}} -def test_scene_serialisation_reconstructs_world_transform_from_local_transforms(): +def test_scene_rejects_duplicate_hierarchy_references(): scene = Scene() - parent = scene.add(Box(), name="Parent") - child = scene.add(Box(), name="Child", parent=parent) - parent.transformation = Translation.from_vector([10.0, 0.0, 0.0]) - child.transformation = Translation.from_vector([0.0, 5.0, 0.0]) + obj = scene.add(Box()) + data = scene.__data__ + data["hierarchy"]["children"].append({"object": str(obj.guid), "children": []}) - reconstructed = Scene.from_jsonstring(scene.to_jsonstring()) - reconstructed_parent = reconstructed.find_by_name("Parent") - reconstructed_child = reconstructed.find_by_name("Child") + with pytest.raises(ValueError, match="more than once"): + Scene.__from_data__(data) - assert reconstructed_parent is not None - assert reconstructed_child is not None - assert reconstructed_parent.transformation == parent.transformation - assert reconstructed_child.transformation == child.transformation - assert reconstructed_child.worldtransformation == child.worldtransformation - - -def test_scene_serialisation_empty(): - scene = Scene() - scene = compas.json_loads(compas.json_dumps(scene)) - assert isinstance(scene, Scene) +def test_nested_groups_and_world_transform_roundtrip(): + scene = Scene("Nested") + first = scene.add_group("First", transformation=Translation.from_vector([1, 0, 0])) + second = scene.add_group("Second", parent=first, transformation=Translation.from_vector([0, 2, 0])) + child = scene.add(Box(), parent=second, transformation=Translation.from_vector([0, 0, 3])) + restored = Scene.from_jsonstring(scene.to_jsonstring()) -def test_group_serialisation(): - scene1 = Scene() - group = scene1.add_group("TestGroup", show=False) - box = Box.from_width_height_depth(1, 1, 1) - group.add(box) + restored_child = restored.object(child.guid) + assert restored_child.parent.name == "Second" + assert restored_child.parent.parent.name == "First" + assert restored_child.worldtransformation == child.worldtransformation - scene2 = Scene.from_jsonstring(scene1.to_jsonstring()) - # Check if group was serialized correctly - group2 = scene2.find_by_name("TestGroup") - assert isinstance(group2, Group) - assert group2.name == "TestGroup" - assert not group2.show +def test_replace_item_and_shared_item_pruning(): + shared = Box(1) + replacement = Box(2) + scene = Scene() + first = scene.add(shared) + second = scene.add(shared) - # Check if box was serialized correctly - box2 = group2.children[0] - assert isinstance(box2.item, Box) - assert box2.parent is group2 + scene.replace_item(first, replacement) + assert shared.guid in scene.item_store + scene.remove(second) + assert shared.guid not in scene.item_store + assert first.item is replacement -def test_nested_group_serialisation(): - scene1 = Scene() - parent_group = scene1.add_group("ParentGroup", show=False) - child_group = parent_group.add(Group("ChildGroup", show=True)) - box = Box.from_width_height_depth(1, 1, 1) - child_group.add(box) - scene2 = Scene.from_jsonstring(scene1.to_jsonstring()) +def test_bind_many_is_atomic(): + first = Box(1) + second = Box(2) + unknown = Box(3) + scene = Scene() + scene.add(first) + scene.add(second) + restored = Scene.from_jsonstring(scene.to_jsonstring()) - # Check parent group - parent2 = scene2.find_by_name("ParentGroup") - assert isinstance(parent2, Group) - assert not parent2.show + with pytest.raises(KeyError): + restored.bind_many([first, unknown]) - # Check child group - child2 = parent2.children[0] - assert isinstance(child2, Group) - assert child2.name == "ChildGroup" - assert child2.show - assert child2.parent is parent2 + assert restored.item_store == {} - # Check box - box2 = child2.children[0] - assert isinstance(box2.item, Box) - assert box2.parent is child2 +def test_bind_rejects_a_distinct_item_with_the_same_guid(): + item = Box(1) + duplicate = Box(2) + duplicate._guid = item.guid + scene = Scene() + scene.add(item) + restored = Scene.from_jsonstring(scene.to_jsonstring()) + restored.bind(item) -def test_group_kwargs_serialisation(): - scene1 = Scene() - group = scene1.add_group("TestGroup", show=False, opacity=0.5) - box = Box.from_width_height_depth(1, 1, 1) - group.add(box) + with pytest.raises(ValueError, match="different data item"): + restored.bind(duplicate) - scene2 = Scene.from_jsonstring(scene1.to_jsonstring()) - # Check if group kwargs were serialized correctly - group2 = scene2.find_by_name("TestGroup") - assert not group2.show - assert group2.opacity == 0.5 +def test_type_specific_sceneobject_state_roundtrips(): + mesh = Mesh.from_vertices_and_faces([[0, 0, 0], [1, 0, 0], [0, 1, 0]], [[0, 1, 2]]) + graph = Graph() + graph.add_node(0, x=0, y=0, z=0) + volmesh = VolMesh.from_vertices_and_cells([[0, 0, 0]], []) + scene = Scene() + meshobject = scene.add( + mesh, + show_vertices=True, + vertexsize=3.0, + hide_coplanaredges=True, + use_vertexcolors=True, + ) + graphobject = scene.add(graph, show_nodes=False, edgewidth=2.0) + volmeshobject = scene.add(volmesh, show_cells=False, vertexsize=4.0) + + restored = Scene.from_jsonstring(scene.to_jsonstring()) + + restored_mesh = restored.object(meshobject.guid) + restored_graph = restored.object(graphobject.guid) + restored_volmesh = restored.object(volmeshobject.guid) + assert isinstance(restored_mesh, MeshObject) + assert restored_mesh.show_vertices is True + assert restored_mesh.vertexsize == 3.0 + assert restored_mesh.hide_coplanaredges is True + assert restored_mesh.use_vertexcolors is True + assert isinstance(restored_graph, GraphObject) + assert restored_graph.show_nodes is False + assert restored_graph.edgewidth == 2.0 + assert isinstance(restored_volmesh, VolMeshObject) + assert restored_volmesh.show_cells is False + assert restored_volmesh.vertexsize == 4.0 + + +def test_geometry_specific_sceneobject_state_roundtrips(): + from compas.geometry import Box + from compas.geometry import Frame + from compas.geometry import Plane + from compas.geometry import PlanarSurface + from compas.geometry import Point + from compas.geometry import Vector - # Check if box inherited kwargs correctly - box2 = group2.children[0] - assert not box2.show - assert box2.opacity == 0.5 + scene = Scene() + shapeobject = scene.add(Box(), u=8, v=12) + surfaceobject = scene.add(PlanarSurface(), u=5, v=7) + frameobject = scene.add(Frame.worldXY(), size=2.0) + planeobject = scene.add(Plane.worldXY(), size=3.0) + vectorobject = scene.add(Vector(1, 2, 3), anchor=Point(4, 5, 6)) + + restored = Scene.from_jsonstring(scene.to_jsonstring()) + + restored_shape = restored.object(shapeobject.guid) + restored_surface = restored.object(surfaceobject.guid) + restored_frame = restored.object(frameobject.guid) + restored_plane = restored.object(planeobject.guid) + restored_vector = restored.object(vectorobject.guid) + assert isinstance(restored_shape, ShapeObject) + assert (restored_shape.u, restored_shape.v) == (8, 12) + assert isinstance(restored_surface, SurfaceObject) + assert (restored_surface.u, restored_surface.v) == (5, 7) + assert isinstance(restored_frame, FrameObject) + assert restored_frame.size == 2.0 + assert isinstance(restored_plane, PlaneObject) + assert restored_plane.size == 3.0 + assert isinstance(restored_vector, VectorObject) + assert restored_vector.anchor == Point(4, 5, 6) + + +def test_scene_state_fields_compose_defaults_and_omitted_defaults(): + class BaseObject(SceneObject): + __scene_state_namespace__ = "test.base" + __scene_state_fields__ = (SceneStateField("size", int, default=1, required=False, omit_default=True),) + + def __init__(self, size=1, **kwargs): + super().__init__(**kwargs) + self.size = size + + class DerivedObject(BaseObject): + __scene_state_namespace__ = "test.derived" + __scene_state_fields__ = (SceneStateField("label", str, default="default", required=False),) + + def __init__(self, label="default", **kwargs): + super().__init__(**kwargs) + self.label = label + + original = DerivedObject(item_guid=uuid4(), label="kept") + data = original.__data__ + assert data["extensions"] == {"test.derived": {"label": "kept"}} + + restored = DerivedObject.__from_data__(data) + + assert restored.size == 1 + assert restored.label == "kept" + + +@pytest.mark.parametrize( + ("change", "message"), + [ + ({"unknown": True}, "Unknown scene fields"), + ({"version": 999}, "Unsupported scene schema version"), + ({"objects": ()}, "objects should be a list"), + ({"name": None}, "name"), + ], +) +def test_scene_rejects_invalid_closed_schema(change, message): + data = Scene().__data__ + data.update(change) + + with pytest.raises((TypeError, ValueError), match=message): + Scene.__from_data__(data) diff --git a/tests/typing/accepted.py b/tests/typing/accepted.py index bfedd8ae6fa..068db480cd9 100644 --- a/tests/typing/accepted.py +++ b/tests/typing/accepted.py @@ -1,4 +1,5 @@ from collections.abc import Iterator +from collections.abc import Mapping from decimal import Decimal from typing import SupportsFloat from typing import assert_type @@ -57,6 +58,9 @@ from compas.geometry.triangulation import triangulate_polygon from compas.datastructures import Graph from compas.datastructures import Mesh +from compas.scene import SceneAttributeUpdate +from compas.scene import SceneObject +from compas.scene import SceneStateField class CustomCoordinate: @@ -298,3 +302,27 @@ def numpy_triangulator(vertices: PointsLike) -> np.ndarray[tuple[int, int], np.d constraints=np.asarray([vertices32[:2]], dtype=np.float64), points=np.asarray([[0.25, 0.25, 0]], dtype=np.int64), ) + + +def update_sceneobject(owner: "CustomSceneObject", value: object) -> None: + if not isinstance(value, (int, float)): + raise TypeError + owner.value = float(value) + + +class CustomSceneObject(SceneObject): + __scene_state_namespace__ = "test.typing.CustomSceneObject" + __scene_state_fields__ = (SceneStateField("value", (int, float), required=False, editable=True, update=update_sceneobject),) + + def __init__(self) -> None: + super().__init__() + self.value = 1.0 + + +custom_sceneobject = CustomSceneObject() +custom_update: SceneAttributeUpdate[CustomSceneObject] = update_sceneobject +assert_type( + custom_sceneobject.editable_attributes(), + Mapping[str, SceneAttributeUpdate[CustomSceneObject] | None], +) +custom_sceneobject.update_editable_attribute("value", 2.0) diff --git a/tests/typing/installed_consumer.py b/tests/typing/installed_consumer.py index 48ac1443f15..31a32a2407a 100644 --- a/tests/typing/installed_consumer.py +++ b/tests/typing/installed_consumer.py @@ -26,6 +26,9 @@ from compas.typing import PointLike from compas.typing import RealInput from compas.typing import VerticesFaces +from compas.scene import SceneAttributeUpdate +from compas.scene import SceneObject +from compas.scene import SceneStateField vertices = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]] @@ -53,6 +56,19 @@ class CustomMesh(Mesh): custom_mesh = CustomMesh.from_vertices_and_faces(vertices, triangles) + +def update_sceneobject(owner: "CustomSceneObject", value: object) -> None: + owner.name = str(value) + + +class CustomSceneObject(SceneObject): + __scene_state_namespace__ = "test.typing.CustomSceneObject" + __scene_state_fields__ = (SceneStateField("value", object, required=False, editable=True, update=update_sceneobject),) + + +custom_sceneobject = CustomSceneObject() +custom_update: SceneAttributeUpdate[CustomSceneObject] = update_sceneobject + assert_type(Point(0.0, 0.0, 0.0).x, float) assert_type(tessellation.number_of_triangles, int) assert_type(tessellation.to_vertices_and_triangles(), tuple[list[list[float]], list[list[int]]]) @@ -65,6 +81,10 @@ class CustomMesh(Mesh): assert_type(planar_region.triangulated(), Tessellation) assert_type(mesh.triangulated(), Mesh) assert_type(custom_mesh.triangulated(), CustomMesh) +assert_type( + custom_sceneobject.editable_attributes()["value"], + SceneAttributeUpdate[CustomSceneObject] | None, +) assert_type(triangulate_polygon(vertices), list[list[int]]) assert_type(triangulate_polygon_earclip(vertices), list[list[int]]) assert_type(triangulate_polygon_minimum_area(vertices), list[list[int]])