diff --git a/.github/scene-candidates/core-requirements.txt b/.github/scene-candidates/core-requirements.txt new file mode 100644 index 0000000..d88b052 --- /dev/null +++ b/.github/scene-candidates/core-requirements.txt @@ -0,0 +1 @@ +compas @ git+https://github.com/compas-dev/compas.git@70aeb1e408772f0a84213c280658d4d594bf12ea diff --git a/.github/scene-candidates/test_scene_integration.py b/.github/scene-candidates/test_scene_integration.py new file mode 100644 index 0000000..479cb4c --- /dev/null +++ b/.github/scene-candidates/test_scene_integration.py @@ -0,0 +1,721 @@ +import json +import os +import subprocess +import sys +from importlib import import_module +from importlib.metadata import distribution +from math import pi +from unittest.mock import Mock +from uuid import uuid4 + +import pytest +from compas.colors import Color +from compas.data import json_dumps +from compas.data import json_loads +from compas.datastructures import Graph +from compas.datastructures import Mesh +from compas.geometry import Box +from compas.geometry import Line +from compas.geometry import Point +from compas.geometry import Rotation +from compas.geometry import Scale +from compas.geometry import Translation +from compas.geometry import distance_point_point +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 SceneItemNotBoundError +from compas.scene import SceneObject +from compas.scene import ShapeObject +from compas.scene import TextAnnotation +from compas.scene import register_scene_operation +from compas_viewer import ScaleBarOverlay +from compas_viewer import ScreenTextOverlay +from compas_viewer import Viewer +from compas_viewer.commands import builtin_commands +from compas_viewer.config import Config +from compas_viewer.forms import REMOVE_EDITABLE_ATTRIBUTE +from compas_viewer.forms import register_scene_attribute_contribution +from compas_viewer.forms import scene_editable_attributes +from compas_viewer.measurement import DistanceInspection +from compas_viewer.measurement import MeasurementState +from compas_viewer.overlays import _OverlayLayer +from compas_viewer.scene import BufferGeometry +from compas_viewer.scene import ViewerScene +from compas_viewer.scene.annotationobject import ArrowAnnotationRenderObject +from compas_viewer.scene.annotationobject import DistanceDimensionRenderObject +from compas_viewer.scene.annotationobject import TextAnnotationRenderObject +from compas_viewer.selection import Selection +from compas_viewer.snapping import ProjectedPoint +from compas_viewer.snapping import SnapKind +from compas_viewer.snapping import SnapQuery +from compas_viewer.snapping import SnapResult +from compas_viewer.snapping import query_snaps +from compas_viewer.uidefinitions import default_menu_items +from compas_viewer.uidefinitions import default_sidebar_items +from compas_viewer.uidefinitions import default_toolbar_items +from PySide6.QtWidgets import QSplitter + +CORE_COMMIT = "70aeb1e408772f0a84213c280658d4d594bf12ea" +VIEWER_COMMIT = "efbb7991c9f60aef2e8225813c5050190b5cfb0b" + + +def _installed_commit(distribution_name: str) -> str: + direct_url = distribution(distribution_name).read_text("direct_url.json") + assert direct_url is not None + metadata = json.loads(direct_url) + return metadata["vcs_info"]["commit_id"] + + +def test_exact_source_candidates_are_installed(): + if os.environ.get("COMPAS_SCENE_SOURCE_CHECKOUTS") == "1": + pytest.skip("Direct-source local check; exact installed revisions are verified by framework CI.") + assert _installed_commit("compas") == CORE_COMMIT + assert _installed_commit("compas_viewer") == VIEWER_COMMIT + + +def test_plugin_discovery_does_not_import_graphics_modules(): + code = """ +import sys + +from compas.plugins import PluginManager + +manager = PluginManager() +manager.load_plugins() +from compas_viewer.config import Config +from compas_viewer.uidefinitions import default_sidebar_items, default_toolbar_items + +assert Config().schema_version == 3 +assert not any(item.get("type") == "DatastructureAttributes" for item in default_sidebar_items()) +assert any(item.get("type") == "AnnotationPanel" for item in default_sidebar_items()) +assert any(item.get("type") == "GridUnitSetting" for item in default_sidebar_items()) +assert not any(item.get("type") == "MeasurementSetting" for item in default_sidebar_items()) +assert [item.get("type") for item in default_toolbar_items()] == ["select", "select"] +modules = tuple(sys.modules) +assert "compas_viewer.plugins" in modules +assert not any(name == "PySide6" or name.startswith("PySide6.") for name in modules) +assert not any(name == "OpenGL" or name.startswith("OpenGL.") for name in modules) +""" + environment = os.environ.copy() + if os.environ.get("COMPAS_SCENE_SOURCE_CHECKOUTS") != "1": + environment.pop("PYTHONPATH", None) + subprocess.run([sys.executable, "-c", code], check=True, env=environment) + + +def test_viewer_configuration_and_sidebar_contracts(): + defaults = Config() + config = Config.from_dict( + { + "schema_version": 3, + "window": {"title": "Framework Viewer"}, + "renderer": {"view": "ortho"}, + "measurement": {"unit": "mm", "precision": 2}, + } + ) + payload = config.to_dict() + + assert defaults.window.title == "COMPAS Viewer" + assert defaults.window.icon is None + assert defaults.ui.toolbar.show is True + assert config.schema_version == 3 + assert config.window.title == "Framework Viewer" + assert config.window.icon is None + assert config.renderer.view == "ortho" + assert config.measurement.unit == "mm" + assert config.measurement.precision == 2 + assert set(payload) == {"schema_version", "vectorsize", "ui", "window", "renderer", "camera", "measurement"} + assert "about" not in payload["window"] + assert "opacity" not in payload["renderer"] + assert "show_widgets" not in payload["ui"]["sidebar"] + assert "sceneform" not in payload["ui"]["sidebar"] + assert [item["type"] for item in default_sidebar_items()] == [ + "SceneTree", + "AnnotationPanel", + "ObjectSetting", + "CameraSetting", + "DisplaySetting", + "GridUnitSetting", + ] + toolbar_items = default_toolbar_items() + assert [(item["title"], item["state"]) for item in toolbar_items] == [ + ("Render Mode", "renderer.rendermode"), + ("View", "renderer.view"), + ] + assert [option["value"] for option in toolbar_items[0]["items"]] == [ + "shaded", + "ghosted", + "lighted", + "wireframe", + ] + assert [option["value"] for option in toolbar_items[1]["items"]] == [ + "perspective", + "top", + "front", + "right", + "ortho", + ] + + with pytest.raises(ValueError, match=r"window\.about"): + Config.from_dict({"schema_version": 3, "window": {"about": "retired"}}) + with pytest.raises(ValueError, match=r"window\.icon"): + Config.from_dict({"schema_version": 3, "window": {"icon": "relative.png"}}) + with pytest.raises(ValueError, match=r"window\.width"): + Config.from_dict({"schema_version": 3, "window": {"width": 0}}) + + +def test_viewer_sidebar_separates_scene_annotation_and_system_domains(): + viewer = Viewer() + sidebar = viewer.ui.sidebar + + assert [sidebar.widget.tabText(index) for index in range(sidebar.widget.count())] == [ + "Scene", + "Annotations", + "System", + ] + assert sidebar.widget.findChildren(QSplitter) == [] + + sidebar.set_current_tab("Annotations") + assert sidebar.widget.tabText(sidebar.widget.currentIndex()) == "Annotations" + + sidebar.focus_system_section("Camera") + assert sidebar.widget.tabText(sidebar.widget.currentIndex()) == "System" + sidebar.focus_system_section("Grid and Units") + assert sidebar.widget.tabText(sidebar.widget.currentIndex()) == "System" + + with pytest.raises(ValueError, match="Unsupported sidebar tab"): + sidebar.set_current_tab("Other") # type: ignore[arg-type] + with pytest.raises(ValueError, match="Unsupported system section"): + sidebar.focus_system_section("Other") # type: ignore[arg-type] + with pytest.raises(ValueError, match="Unsupported system section"): + sidebar.focus_system_section("Units and Measurement") # type: ignore[arg-type] + + +def test_core_annotations_serialize_and_resolve_without_fallbacks(): + scene = ViewerScene() + point_object = scene.add(Point(1, 2, 3), transformation=Translation.from_vector([10, 0, 0])) + line_object = scene.add(Line([0, 0, 0], [4, 0, 0]), transformation=Translation.from_vector([0, 5, 0])) + mesh = Mesh.from_vertices_and_faces( + [[0, 0, 0], [4, 0, 0], [0, 4, 0]], + [[0, 1, 2]], + ) + mesh_object = scene.add(mesh, transformation=Translation.from_vector([0, 0, 2])) + + point_anchor = PointAnchor([1, 2, 3]) + component_anchor = ComponentAnchor(point_object.guid, "point") + line_anchor = ComponentAnchor(line_object.guid, "line", parameter=0.25) + vertex_anchor = ComponentAnchor(mesh_object.guid, "vertex", component=1) + edge_anchor = ComponentAnchor(mesh_object.guid, "edge", component=(0, 1), parameter=0.5) + text = TextAnnotation("Origin", [0, 0, 0]) + arrow = ArrowAnnotation([0, 0, 0], [1, 0, 0]) + fixed = DistanceDimension(point_anchor, PointAnchor([4, 6, 3]), unit="mm", precision=2) + mixed = DistanceDimension(PointAnchor([0, 0, 0]), component_anchor) + associative = DistanceDimension(line_anchor, edge_anchor) + + for value in ( + point_anchor, + component_anchor, + text, + arrow, + fixed, + mixed, + associative, + ): + assert json_loads(json_dumps(value)) == value + + assert fixed.resolve(scene, Translation.from_vector([2, 0, 0])) == ( + Point(3, 2, 3), + Point(6, 6, 3), + ) + assert mixed.resolve(scene, Translation.from_vector([2, 0, 0])) == ( + Point(2, 0, 0), + Point(11, 2, 3), + ) + assert associative.resolve(scene) == ( + Point(1, 5, 0), + Point(2, 0, 2), + ) + assert vertex_anchor.resolve(scene) == Point(4, 0, 2) + + missing_object = DistanceDimension(PointAnchor([0, 0, 0]), ComponentAnchor(uuid4(), "point")) + missing_vertex = DistanceDimension(PointAnchor([0, 0, 0]), ComponentAnchor(mesh_object.guid, "vertex", component=99)) + assert missing_object.resolve(scene) is None + assert missing_vertex.resolve(scene) is None + + style = DimensionStyle( + color=Color.red(), + line_width=5, + text_size=18, + arrow_size=20, + label_offset=7, + ) + text_entry = scene.add_annotation(text, name="Origin note") + arrow_entry = scene.add_annotation(arrow, name="Direction") + dimension_entry = scene.add_annotation(fixed, name="Span", style=style) + + assert Scene.SCHEMA_VERSION == 3 + assert scene.__data__["version"] == 3 + assert scene.annotations == (text_entry, arrow_entry, dimension_entry) + assert text_entry not in scene.objects + assert set(scene.object_store) == {scene.root.guid, point_object.guid, line_object.guid, mesh_object.guid} + with pytest.raises(KeyError): + scene.node(text_entry.guid) + with pytest.raises(TypeError, match="Scene.add_annotation"): + scene.add(TextAnnotation("Wrong path", [0, 0, 0])) + + payload = scene.to_jsonstring() + restored_scene = Scene.from_jsonstring(payload) + assert restored_scene.__data__["version"] == 3 + assert len(restored_scene.objects) == 3 + assert [entry.name for entry in restored_scene.annotations] == ["Origin note", "Direction", "Span"] + assert restored_scene.annotations[2].style == style + assert isinstance(restored_scene.annotations[2], SceneAnnotation) + assert restored_scene.item_store == {} + with pytest.raises(SceneItemNotBoundError, match=str(text.guid)): + _ = restored_scene.annotations[0].item + + restored_scene.bind_many([text, arrow, fixed]) + assert restored_scene.annotations[0].item is text + assert restored_scene.annotations[1].item is arrow + assert restored_scene.annotations[2].item is fixed + assert json_loads(json_dumps(style)) == style + + +def test_viewer_dispatches_canonical_annotations_without_legacy_types(): + scene = ViewerScene() + annotations = ( + (TextAnnotation("Note", [0, 0, 0]), TextAnnotationRenderObject), + (ArrowAnnotation([0, 0, 0], [1, 0, 0]), ArrowAnnotationRenderObject), + ( + DistanceDimension(PointAnchor([0, 0, 0]), PointAnchor([1, 0, 0])), + DistanceDimensionRenderObject, + ), + ) + + for annotation, render_type in annotations: + entry = scene.add_annotation(annotation) + render_object = scene.annotation_render_object(entry) + assert isinstance(render_object, render_type) + assert render_object.item is annotation + + assert scene.objects == [] + assert len(scene.annotations) == 3 + assert scene.render_objects == {} + assert tuple(scene.annotation_render_objects) == tuple(entry.guid for entry in scene.annotations) + + with pytest.raises(ModuleNotFoundError): + import_module("compas.scene.annotationobject") + + with pytest.raises(ModuleNotFoundError): + import_module("compas_viewer.scene.tagobject") + with pytest.raises(ModuleNotFoundError): + import_module("compas_viewer.scene.arrowoverlayobject") + + +def test_measurement_state_preserves_mode_semantics_and_dimension_settings(): + state = MeasurementState() + point_guid = uuid4() + vertex_guid = uuid4() + first = SnapResult(Point(0, 0, 0), point_guid, SnapKind.POINT, 0.0) + second = SnapResult(Point(3, 4, 0), vertex_guid, SnapKind.VERTEX, 0.0, component=2) + + state.start("inspection") + assert state.accept(SnapQuery(first), unit="m", precision=1) is None + inspection = state.accept(SnapQuery(second), unit="m", precision=1) + assert isinstance(inspection, DistanceInspection) + assert inspection.distance == 5.0 + assert state.completed_inspection is inspection + assert not state.active + + unsupported = SnapResult( + Point(8, 8, 8), + uuid4(), + SnapKind.NODE, + 0.0, + association_error="The snapped component does not have a stable serializable key.", + ) + state.start("fixed") + assert state.accept(SnapQuery(first), unit="mm", precision=4) is None + fixed = state.accept(SnapQuery(unsupported), unit="mm", precision=4) + assert isinstance(fixed, DistanceDimension) + assert fixed.start == PointAnchor(first.point) + assert fixed.end == PointAnchor(unsupported.point) + assert (fixed.unit, fixed.precision) == ("mm", 4) + + state.start("associative") + assert state.accept(SnapQuery(first), unit="cm", precision=3) is None + assert state.accept(SnapQuery(unsupported), unit="cm", precision=3) is None + assert state.first_snap is first + assert state.rejection == "The snapped component does not have a stable serializable key." + associative = state.accept(SnapQuery(second), unit="cm", precision=3) + assert isinstance(associative, DistanceDimension) + assert associative.start == ComponentAnchor(point_guid, "point") + assert associative.end == ComponentAnchor(vertex_guid, "vertex", component=2) + assert (associative.unit, associative.precision) == ("cm", 3) + assert not state.active + + +def test_viewer_measurement_creates_and_selects_a_nonspatial_annotation(monkeypatch): + viewer = Viewer() + viewer.scene.clear() + first = SnapResult(Point(0, 0, 0), uuid4(), SnapKind.POINT, 0.0) + second = SnapResult(Point(3, 4, 0), uuid4(), SnapKind.POINT, 0.0) + monkeypatch.setattr( + viewer.renderer, + "query_snap_context_at", + Mock(side_effect=[SnapQuery(first), SnapQuery(second)]), + ) + + viewer.start_distance_dimension("fixed") + viewer._accept_measurement_at((10.0, 10.0)) + viewer._accept_measurement_at((20.0, 20.0)) + + assert len(viewer.scene.annotations) == 1 + entry = viewer.scene.annotations[0] + assert isinstance(entry.item, DistanceDimension) + assert entry.item.distance() == 5.0 + assert isinstance(entry.style, DimensionStyle) + assert viewer.scene.objects == [] + assert viewer.state.annotation_selection.objects == (entry,) + assert not viewer.state.selection + + spatial = viewer.scene.add(Box(1.0)) + viewer.state.selection.add(spatial) + viewer.scene.remove_annotation(entry) + assert viewer.scene.annotations == () + assert viewer.scene.objects == [spatial] + assert viewer.state.annotation_selection.objects == () + assert viewer.state.selection.objects == (spatial,) + viewer.scene.clear() + + +def test_measurement_hover_exposes_discrete_points_and_one_winner(): + mesh = Mesh.from_vertices_and_faces( + [[0, 0, 0], [4, 0, 0], [4, 3, 0], [0, 3, 0]], + [[0, 1, 2, 3]], + ) + sceneobject = SceneObject(mesh) + + query = query_snaps( + [sceneobject], + (0.1, 0.1), + radius=0.5, + project=lambda point: ProjectedPoint(point.x, point.y, 0.0), + ) + + assert query.winner is not None + assert query.winner.kind == SnapKind.VERTEX + assert query.winner.component == 0 + assert [snap.kind for snap in query.points] == [SnapKind.VERTEX] * 4 + assert [snap.component for snap in query.points] == [0, 1, 2, 3] + + mesh_edge = query_snaps( + [sceneobject], + (2.0, 0.0), + radius=0.1, + project=lambda point: ProjectedPoint(point.x, point.y, 0.0), + ) + + assert mesh_edge.winner is None + assert len(mesh_edge.points) == 4 + + opposite = query_snaps( + [sceneobject], + (4.0, 3.0), + radius=0.1, + project=lambda point: ProjectedPoint(point.x, point.y, 0.0), + ) + state = MeasurementState() + state.start("fixed") + assert state.accept(query, unit="m", precision=2) is None + dimension = state.accept(opposite, unit="m", precision=2) + assert isinstance(dimension, DistanceDimension) + resolved = dimension.resolve() + assert resolved is not None + assert distance_point_point(*resolved) == 5.0 + + line = SceneObject(Line([0, 0, 0], [4, 0, 0])) + line_query = query_snaps( + [line], + (2.0, 0.0), + radius=0.1, + project=lambda point: ProjectedPoint(point.x, point.y, 0.0), + ) + assert line_query.winner is None + assert line_query.points == () + + graph = Graph() + graph.add_node("a", x=0, y=0, z=0) + graph.add_node("b", x=4, y=0, z=0) + graph.add_edge("a", "b") + graph_query = query_snaps( + [SceneObject(graph)], + (2.0, 0.0), + radius=0.1, + project=lambda point: ProjectedPoint(point.x, point.y, 0.0), + ) + assert graph_query.winner is None + assert [snap.kind for snap in graph_query.points] == [SnapKind.NODE, SnapKind.NODE] + + +def test_measure_menu_and_commands_have_one_stable_public_path(): + measure_menus = [item for item in default_menu_items() if item.get("title") == "Measure"] + assert len(measure_menus) == 1 + command_ids = [item["command"] for item in measure_menus[0]["items"] if "command" in item] + assert command_ids == [ + "viewer.inspect_distance", + "viewer.inspect_selected_area", + "viewer.inspect_selected_volume", + "viewer.add_fixed_distance_dimension", + "viewer.add_associative_distance_dimension", + "viewer.cancel_measurement", + ] + assert set(command_ids) <= builtin_commands().keys() + + edit_menu = next(item for item in default_menu_items() if item.get("title") == "Edit") + edit_commands = [item["command"] for item in edit_menu["items"] if "command" in item] + assert edit_commands.count("viewer.delete_selected") == 1 + assert builtin_commands()["viewer.delete_selected"].keybinding == "Delete" + + +def test_selected_scalar_measurements_use_exact_world_scale_and_declared_units(monkeypatch): + viewer = Viewer() + previous_unit = viewer.config.measurement.unit + previous_precision = viewer.config.measurement.precision + dialogs = [] + + def record_dialog(_parent, title, text): + dialogs.append((title, text)) + + monkeypatch.setattr("compas_viewer.commands.QMessageBox.information", record_dialog) + + viewer.state.selection.clear() + viewer.state.annotation_selection.clear() + viewer.scene.clear() + try: + sceneobject = viewer.scene.add( + Box(1.0), + transformation=Scale.from_factors([2.0, 2.0, 2.0]), + ) + viewer.state.selection.replace((sceneobject,)) + viewer.state.set_measurement_unit("mm") + viewer.state.set_measurement_precision(2) + + viewer.start_distance_inspection() + assert viewer.inspect_selected_area() == pytest.approx(24.0) + assert not viewer.state.measurement.has_transient_state + assert viewer.inspect_selected_volume() == pytest.approx(8.0) + + commands = builtin_commands() + assert commands["viewer.inspect_selected_area"].callback(viewer) == pytest.approx(24.0) + assert commands["viewer.inspect_selected_volume"].callback(viewer) == pytest.approx(8.0) + assert dialogs == [ + ("Selected Area", "Area: 24.00 mm²"), + ("Selected Volume", "Volume: 8.00 mm³"), + ] + assert viewer.scene.objects == [sceneobject] + assert viewer.state.selection.objects == (sceneobject,) + assert viewer.scene.annotations == () + finally: + viewer.cancel_measurement() + viewer.state.selection.clear() + viewer.state.annotation_selection.clear() + viewer.scene.clear() + viewer.state.set_measurement_unit(previous_unit) + viewer.state.set_measurement_precision(previous_precision) + + +def test_viewer_overlays_remain_outside_serialized_scene_data(): + viewer = object.__new__(Viewer) + viewer._overlay_layer = _OverlayLayer() + viewer._scene = ViewerScene() + viewer.running = False + overlays = ( + ScaleBarOverlay(), + ScreenTextOverlay( + "Viewport status", + (0.5, 0.25), + horizontal_alignment="center", + ), + ) + before = viewer.scene.__data__ + + for overlay in overlays: + viewer.add_overlay(overlay) + + assert viewer.overlays == overlays + assert viewer.scene.__data__ == before + assert viewer.scene.objects == [] + assert viewer.remove_overlay(overlays[0]) + assert viewer.remove_overlay(overlays[1]) + assert viewer.overlays == () + + +def test_indexed_buffer_geometry_stays_indexed_and_roundtrips(): + geometry = BufferGeometry.from_vertices_and_triangles( + [[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]], + [[0, 1, 2], [1, 3, 2]], + ) + + restored = json_loads(json_dumps(geometry)) + + assert isinstance(restored, BufferGeometry) + assert restored.vertices.shape == (4, 3) + assert restored.triangles is not None + assert restored.triangles.shape == (2, 3) + assert restored.triangles.tolist() == [[0, 1, 2], [1, 3, 2]] + + +def test_viewer_transform_history_and_refresh_contract(): + viewer = Viewer() + + parent = viewer.scene.add_group( + "Rotated parent", + transformation=Rotation.from_axis_and_angle([0, 0, 1], pi / 2), + ) + child = viewer.scene.add( + Box(1.0), + parent=parent, + transformation=Translation.from_vector([1, 0, 0]), + ) + previous_local = child.transformation.copy() + previous_world = child.worldtransformation.copy() + delta = Translation.from_vector([2, 0, 0]) + + viewer.transform_objects([child], delta) + + assert child.worldtransformation == delta * previous_world + assert child.transformation == parent.worldtransformation.inverse() * delta * previous_world + viewer.refresh_geometry([child]) + viewer.refresh_appearance([child]) + assert viewer.undo() + assert child.transformation == previous_local + assert viewer.redo() + + child.transformation = previous_local + viewer.refresh_transform([child]) + assert not viewer.undo() + + +def test_contextual_editable_scene_state_is_graphics_free_and_not_serialized(): + sceneobject = ShapeObject(item=Box(1.0), u=7, v=9) + original_payload = sceneobject.to_jsonstring() + + geometry_fields = sceneobject.scene_state_fields()["compas.scene.GeometryObject"] + editable_state = {field.attribute for field in geometry_fields if field.editable} + assert editable_state == { + "linecolor", + "linewidth", + "pointcolor", + "pointsize", + "show_lines", + "show_points", + "show_surfaces", + "surfacecolor", + } + assert editable_state <= sceneobject.editable_attributes().keys() + assert "u" not in sceneobject.editable_attributes() + + def update_resolution(obj: ShapeObject, value: object) -> None: + obj.u = int(value) + + register_scene_attribute_contribution( + "FrameworkIntegration", + ShapeObject, + "shape-resolution", + { + "name": REMOVE_EDITABLE_ATTRIBUTE, + "u": update_resolution, + }, + ) + resolved = scene_editable_attributes("FrameworkIntegration", sceneobject) + + assert "name" not in resolved + assert resolved["u"] is update_resolution + assert sceneobject.to_jsonstring() == original_payload + + resolved["u"](sceneobject, 11) + assert type(sceneobject) is ShapeObject + assert sceneobject.u == 11 + payload = sceneobject.to_jsonstring() + assert "shape-resolution" not in payload + assert "FrameworkIntegration" not in payload + assert "FormField" not in payload + + +def test_stable_scene_roundtrip_operations_and_explicit_binding(): + box = Box(1.0) + transformation = Translation.from_vector([2.0, 0.0, 0.0]) + scene = ViewerScene() + original = scene.add( + box, + name="Box", + show=False, + transformation=transformation, + u=7, + v=9, + ) + selection = Selection(scene.object) + selection.add(original) + + assert type(original) is ShapeObject + assert selection.objects == (original,) + assert original.node.object_guid == original.guid + assert original.node.__data__ == {"object": str(original.guid), "children": []} + + calls = [] + runtime = object() + + def draw(scene, sceneobject, active_runtime): + calls.append(("draw", sceneobject, active_runtime)) + return ["opaque-handle"] + + def clear(scene, sceneobject, active_runtime, resources): + calls.append(("clear", sceneobject, active_runtime, resources)) + + register_scene_operation("FrameworkIntegration", SceneObject, "draw", draw) + register_scene_operation("FrameworkIntegration", SceneObject, "clear", clear) + original.show = True + assert original.draw(context="FrameworkIntegration", runtime=runtime) == ["opaque-handle"] + assert scene.object(original.guid) is original + assert type(original) is ShapeObject + + payload = scene.to_jsonstring() + assert str(box.guid) in payload + assert "compas.geometry/Box" not in payload + assert "opaque-handle" not in payload + assert "FrameworkIntegration" not in payload + assert "is_selected" not in payload + assert '"selection"' not in payload + assert "render_objects" not in payload + assert "instance_colors" not in payload + + restored_scene = Scene.from_jsonstring(payload) + restored_box = Box.from_jsonstring(box.to_jsonstring()) + assert isinstance(restored_scene, ViewerScene) + assert restored_box.guid == box.guid + assert restored_box.volume() == box.volume() + + restored = restored_scene.find_by_name("Box") + assert type(restored) is ShapeObject + assert restored.guid == original.guid + assert restored.item_guid == restored_box.guid + assert restored.transformation == transformation + assert restored.show is True + assert (restored.u, restored.v) == (7, 9) + assert restored_scene.item_store == {} + assert not Selection(restored_scene.object) + with pytest.raises(SceneItemNotBoundError, match=str(restored_box.guid)): + _ = restored.item + + restored_scene.bind(restored_box) + assert restored.item is restored_box + original.clear(context="FrameworkIntegration") + assert calls == [ + ("draw", original, runtime), + ("clear", original, runtime, ("opaque-handle",)), + ] + assert restored_scene.instance_colors == {} diff --git a/.github/scene-candidates/viewer-requirements.txt b/.github/scene-candidates/viewer-requirements.txt new file mode 100644 index 0000000..88b989e --- /dev/null +++ b/.github/scene-candidates/viewer-requirements.txt @@ -0,0 +1 @@ +compas_viewer @ git+https://github.com/compas-dev/compas_viewer.git@efbb7991c9f60aef2e8225813c5050190b5cfb0b diff --git a/.github/workflows/scene-candidate-integration.yml b/.github/workflows/scene-candidate-integration.yml new file mode 100644 index 0000000..77ab49c --- /dev/null +++ b/.github/workflows/scene-candidate-integration.yml @@ -0,0 +1,62 @@ +name: scene-candidate-integration + +on: + pull_request: + branches: [c3-upgrade] + paths: + - .github/scene-candidates/** + - .github/workflows/scene-candidate-integration.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: scene-candidate-integration-${{ github.ref }} + cancel-in-progress: true + +jobs: + source-installed-candidates: + runs-on: ubuntu-24.04 + env: + PYTHONDONTWRITEBYTECODE: "1" + QT_QPA_PLATFORM: offscreen + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install Linux EGL/OpenGL runtime + run: | + sudo apt-get update + sudo apt-get install --yes libegl1 python3-opengl + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.12" + - uses: astral-sh/setup-uv@ae62891fec2bb8e7d6c99fc78c9fec3a63790f8d # v10.0.0 + with: + version: "0.12.7" + - name: Install test tools and exact source candidates + run: | + uv venv + uv pip install --python .venv/bin/python pytest==9.0.2 pyright==1.1.414 + uv pip install --python .venv/bin/python compas_viewer==2.0.2 + uv pip install \ + --python .venv/bin/python \ + --reinstall \ + --requirements .github/scene-candidates/core-requirements.txt + uv pip install \ + --python .venv/bin/python \ + --no-deps \ + --reinstall \ + --requirements .github/scene-candidates/viewer-requirements.txt + - name: Check installed scene typing boundary + run: >- + uv run --no-sync pyright + --pythonversion 3.12 + .github/scene-candidates/test_scene_integration.py + - name: Exercise installed scene and Viewer behavior + run: >- + uv run --no-sync pytest + --basetemp "${RUNNER_TEMP}/scene-candidate-pytest" + -o cache_dir="${RUNNER_TEMP}/scene-candidate-cache" + .github/scene-candidates/test_scene_integration.py diff --git a/initiatives/scene-viewer-visualisation/README.md b/initiatives/scene-viewer-visualisation/README.md new file mode 100644 index 0000000..8319059 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/README.md @@ -0,0 +1,59 @@ +# Scene, Viewer, and Visualisation + +This initiative aligns backend-neutral scene infrastructure with Viewer +rendering, interaction, state, and UI composition. + +Current phase: **Phase 3 ADRs 036 and 040–042 implemented and verified**. + +- [Objective](objective.md) +- [Inventory](inventory.md) +- [Proposal](proposal.md) +- [Architecture decisions](decisions/README.md) +- [Implementation plan](implementation-plan.md) +- [Current handoff](handoff.md) + +The stable scene architecture correction in Accepted ADRs 013–014 is +implemented and verified: nodes are hierarchy-only, durable scene objects are +stable, and backend operations are context-keyed. Amended Accepted ADRs +015–016 now govern `SceneStateField`-backed editability, narrowly declared +non-state editable attributes, and Viewer-owned contextual forms. Scene +remains reference-only, and optional aggregation is reserved for a separate +future Session design. + +Accepted ADRs 017–020 govern lazy Mesh/Graph element-attribute tables, their +editing semantics, configured Viewer identity, and configuration lifecycle. +They are implemented, locally verified, and independently approved. Hosted +Viewer and framework checks passed. ADR 003 object selection and ADR 004 +transformations, categorized refresh, and Viewer-level transform history are +also implemented and fully verified. Accepted ADRs 021–028 and 030 are +implemented for durable Core annotations, Viewer rendering and overlays, +measurement snapping and interaction, unit/precision presentation, +discrete-only point acquisition, and an always-visible persistent-dimension +pass. The latest measurement follow-up is verified in Viewer package CI and the +framework exact source-installed gate. Accepted ADRs 029 and 031 now authorize +the separate annotation collection and UI, narrow durable dimension style, and +discoverable spatial-object deletion. Their Core and Viewer implementations +and refreshed package and exact source-installed framework integration pass. +Direct-use evidence exposed an unstable and ambiguous stacked sidebar, so ADR +032 accepts a three-domain Scene, Annotations, and System replacement. Its +implementation, documentation, local verification, independent review, +hosted package CI, and the exact source-installed framework gate pass. Two +direct-use regressions in annotation visibility refresh and numeric field +editing are fixed and verified in hosted Viewer and framework CI. Further +direct use has produced ADRs 033–039 for a resizable Scene inspector, +hidden-glyph vertex snapping, spatial dimension layout, viewport text, +annotation label backgrounds, contextual deletion, and moving the existing +geometry Add hierarchy under Scene. ADR 036 accepts the programmatic-first +screen-text overlay. Accepted ADRs 040–042 add synchronized toolbar selectors, +a coherent Grid and Units System section with consistent field alignment, and +transient selected-object area and volume inspection. The remaining ADRs are +Proposed. ADRs 036 and 040–042 are implemented on the Viewer initiative branch +and pass the complete local and hosted Viewer gates plus the exact +source-installed framework gate. Exact candidate-artifact compatibility has +not been run and is not implied by the existing results. + +The refined initial package scope is `compas`, `compas_viewer`, and +`compas_framework`. The current `compas_model.ModelViewer` is draft evidence +and a later redesign consumer, not a behavior contract. Session persistence, +notebook visualisation, and CAD-host adapters are compatibility-review +consumers until an approved decision admits them to implementation scope. diff --git a/initiatives/scene-viewer-visualisation/decisions/001-ownership-boundaries.md b/initiatives/scene-viewer-visualisation/decisions/001-ownership-boundaries.md new file mode 100644 index 0000000..5c81733 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/001-ownership-boundaries.md @@ -0,0 +1,86 @@ +# ADR 001: Ownership and State Boundaries + +## Status + +Accepted. + +## Context + +Core scene objects currently combine durable content with context-adapter +state, while Viewer selection, GPU identity, configuration, tool state, and UI +refresh paths are distributed across objects, renderer, commands, and widgets. +Moving everything into core would make Qt/rendering concerns framework +dependencies; leaving ownership implicit perpetuates coupling. + +## Options + +1. Keep core responsible for durable scene content and place renderer and + interaction state in Viewer. +2. Add rendering, selection, and reactive application state to core Scene. +3. Keep all current ownership and coordinate behavior through conventions. +4. Move durable scene content into Viewer and reduce core Scene to adapters. + +## Recommendation + +Choose option 1. + +- Core owns scene items, hierarchy, scene-object GUIDs, local transformations, + visibility, durable appearance, and serialization. +- Viewer configuration owns persistent application preferences. +- Viewer session state owns selection, hover, tools, gestures, and transient + results. +- Viewer rendering owns indexed buffers, pick IDs, GPU resources, and refresh. +- Domain packages own authoritative domain hierarchies and caches and project + them into core scenes through public Viewer operations. + +GUIDs connect durable scene objects to Viewer state. Pick IDs and transient +state are never serialized. Do not add Qt signals or GPU contracts to core. + +## Consequences + +- Core remains usable by notebook and host adapters without Viewer. +- Selection and tools stop leaking into serialized scene-object settings. +- Viewer must provide explicit public state and synchronization operations. +- Domain packages retain their own data authority rather than duplicating it + in a generic application store. +- Existing Viewer code that reaches its singleton, renderer, or widgets must + migrate gradually after the public boundary exists. + +## Compatibility + +ADR 008 proposes replacing the current incomplete scene serialization without +a compatibility loader. Removing transient Viewer fields and introducing the +new scene-node schema therefore form a deliberate C3 serialization break. + +## Verification + +- Round-trip core scenes without Viewer installed. +- Prove Viewer selection, hover, tools, and pick IDs are absent from scene + serialization. +- Verify domain objects resolve through stable scene-object GUIDs after UI + rebuilds. + +## Affected packages + +Initial implementation: `compas`, `compas_viewer`, and `compas_framework`. + +Later redesign/regression consumer: `compas_model`. + +## Dependencies + +- Geometry-tessellation ADRs 022 and 024 +- Plugin-implementations ADR 002 + +## Pending amendments + +Verified round-trip failures showed that this decision did not distinguish the +durable scene node/state from the context-specific runtime `SceneObject` +adapter precisely enough. Accepted [ADR 008](008-scene-nodes-and-runtime-adapters.md) +and [ADR 009](009-scene-state-fields.md) amend that boundary. Accepted +[ADR 010](010-scene-description-and-item-bundling.md) defines item ownership +and the later Session aggregation boundary. + +The generic principle that domain packages retain their own data authority +does not preserve the current draft `ModelViewer` controller, projections, +selection behavior, or cache shape. Explicit user correction moves that draft +to a later redesign phase. diff --git a/initiatives/scene-viewer-visualisation/decisions/002-indexed-buffer-geometry.md b/initiatives/scene-viewer-visualisation/decisions/002-indexed-buffer-geometry.md new file mode 100644 index 0000000..cf552f3 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/002-indexed-buffer-geometry.md @@ -0,0 +1,75 @@ +# ADR 002: Indexed Viewer Buffer Geometry + +## Status + +Accepted. + +## Context + +Viewer can batch geometry efficiently but its general `BufferGeometry` +requires expanded line and triangle vertices. This duplicates arrays and makes +callers manually expand vertices plus edges or triangles. Core numerical APIs +already accept structural Python and NumPy buffers, and Viewer-specific GPU +layout should not become a compulsory core geometry representation. + +## Options + +1. Add one Viewer-owned shared-vertex indexed `BufferGeometry` contract and + convenience constructors. +2. Put a GPU-oriented buffer type in core. +3. Require `Tessellation`, `PolygonalSurface`, or `Mesh` for every input. +4. Preserve expanded arrays and add only helper functions that duplicate them. + +## Recommendation + +Choose option 1. Use shared `vertices` plus optional point, edge, and triangle +index channels. Provide: + +```python +BufferGeometry.from_points(vertices) +BufferGeometry.from_vertices_and_edges(vertices, edges) +BufferGeometry.from_vertices_and_triangles(vertices, triangles) +``` + +Accept structural Python sequences and NumPy arrays. Normalize once to Viewer +dtypes and check rank, column count, and index bounds. Preserve indices through +the buffer manager and do not create one scene object per primitive. + +Keep styling on scene objects. Do not add a universal render geometry to core +or make this contract an input to geometry algorithms. + +## Consequences + +- Large edge and triangle datasets avoid Python-object and vertex-expansion + overhead. +- Viewer adapters gain one common path for indexed geometry. +- Geometry with independent point/line/triangle vertex pools must combine + them into one vertex table with offset indices at the Viewer boundary. +- Per-channel or per-primitive color arrays beyond current behavior require + evidence and a separate refinement rather than speculative fields. + +## Compatibility + +The existing expanded `points`, `lines`, and `faces` constructor is replaced +in a coordinated Viewer change. Examples and adapters migrate together; no +parallel deprecated constructor is proposed. + +## Verification + +- Test list and NumPy inputs, exact shapes/dtypes, bounds, empty channels, and + input non-mutation. +- Assert indices remain indexed in CPU/GPU assembly. +- Exercise large input without per-edge or per-triangle scene objects. +- Compare rendering semantics with current points, lines, and faces. + +## Affected packages + +Initial implementation: `compas_viewer` and `compas_framework`. + +Later redesign consumer: `compas_model`; its current render-cache shape is not +preserved by this decision. + +## Dependencies + +- [ADR 001](001-ownership-boundaries.md) +- Accepted structural numerical-input decisions from typing alignment diff --git a/initiatives/scene-viewer-visualisation/decisions/003-viewer-state-and-selection.md b/initiatives/scene-viewer-visualisation/decisions/003-viewer-state-and-selection.md new file mode 100644 index 0000000..de0febb --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/003-viewer-state-and-selection.md @@ -0,0 +1,76 @@ +# ADR 003: Viewer State and Object Selection + +## Status + +Accepted. + +## Context + +Selection currently lives in mutable `ViewerSceneObject.is_selected` flags. +Viewport commands, tree widgets, shaders, and programmatic consumers mutate or +poll those flags and then trigger imperative refreshes. `ViewerState` observes +persistent configuration but not selection or tool state. + +## Options + +1. Add one Viewer-owned observable object-selection model and separate + persistent configuration from transient state. +2. Keep scene-object flags and add selection-change signals around them. +3. Put selection into core Scene and serialize it. +4. Adopt a generic third-party reactive state store for all Viewer data. + +## Recommendation + +Choose option 1. + +`Viewer.state.selection` stores ordered scene-object GUIDs and provides +replace, add, remove, toggle, clear, membership, and ordered-resolution +operations. It emits one batched change notification per operation. Viewport, +rectangle selection, scene tree, commands, shaders, and programmatic consumers use +this model exclusively. + +Keep `Viewer.config` for persistent preferences. Keep hover, active tool, +gesture, and temporary tool values in small explicit Viewer state fields. Use a +Qt-neutral Python model with a Qt bridge. Remove `is_selected` rather than +retaining a second writable authority. + +Initial selection is scene-object-level only. Do not invent a generic vertex, +edge, face, or domain-component token until an approved editing workflow +requires it. + +## Consequences + +- Tree, viewport, code, and renderer observe one mutation + path. +- Selection no longer participates in scene serialization. +- Batch changes avoid repeated renderer/UI updates. +- Existing selection APIs and tests require a coordinated breaking migration. +- Sub-object selection remains explicitly unsupported in the initial wave. + +## Compatibility + +Remove Viewer `is_selected` constructor/settings behavior. Later integrations +may consume the selection model but do not define its contract. + +## Verification + +- Exercise replace/add/remove/toggle/clear from viewport, rectangle, tree, and + programmatic paths. +- Assert one notification and one render/UI synchronization per batch. +- Verify stable ordering, removed-object cleanup, and serialization exclusion. + +## Affected packages + +`compas_viewer` and `compas_framework`. `compas_model` is a later redesign +consumer. + +## Dependencies + +- [ADR 001](001-ownership-boundaries.md) + +## Refinement after acceptance + +The current `compas_model.ModelViewer` is a draft and does not promise a +model-order selection contract that this ADR must preserve. The accepted +decision remains one Viewer-owned selection model; model-specific preservation +language has been removed by explicit user correction. diff --git a/initiatives/scene-viewer-visualisation/decisions/004-transform-refresh-undo.md b/initiatives/scene-viewer-visualisation/decisions/004-transform-refresh-undo.md new file mode 100644 index 0000000..fa49950 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/004-transform-refresh-undo.md @@ -0,0 +1,76 @@ +# ADR 004: Transformations, Refresh, and Undo + +## Status + +Accepted. + +## Context + +Core already owns local/world transformations and Viewer can update transform +buffers efficiently, but there is no public multi-object transformation +operation, gizmo contract, or undo behavior. Geometry, selection, sidebar, and +renderer refreshes are invoked through concrete internals. A universal core +event bus would make every mutable property observable before its semantics are +known. + +## Options + +1. Add explicit Viewer transform transactions, undo/redo, and categorized + refresh operations while retaining core transformations. +2. Add a generic observable mutation/event system to core Scene. +3. Mutate scene objects directly and require callers to refresh internals. +4. Move transformations and history entirely into Viewer state. + +## Recommendation + +Choose option 1. + +Expose `viewer.transform_objects(objects, transformation, space="world")`. +Apply one world-space delta to each pre-operation world transformation and +derive each new local transformation through its parent. Reject requests that +contain both an ancestor and its descendant in the initial version. Validate +the entire request before mutation and leave all objects unchanged on failure. + +Record before/after local transformations as one reversible Viewer +transaction. Add a small undo/redo stack for explicit reversible Viewer +transactions; do not absorb general session or domain history. + +Expose explicit geometry, appearance, transform, and hierarchy refresh +operations. Do not add a core scene event bus in this wave. Direct external +mutation requires the matching Viewer refresh call. + +## Consequences + +- Code, commands, and a future gizmo use identical transformation semantics. +- Atomic transactions provide predictable undo and efficient transform-buffer + updates. +- Ancestor/descendant simultaneous transforms remain unsupported until their + intended group semantics are decided. +- Arbitrary item mutation is not magically detected; synchronization remains + explicit and testable. + +## Compatibility + +Existing direct transformation mutation remains a core operation, but Viewer +consumers migrate to the public transaction when they require refresh or undo. +Existing callback commands remain valid and simply do not enter history unless +they produce a reversible transaction. + +## Verification + +- Test world/local conversion under transformed parents. +- Test multiple independent objects, atomic validation failure, ancestor/ + descendant rejection, undo, redo, and redo invalidation after new work. +- Assert transform-only refresh does not rebuild geometry buffers. +- Verify failed commands do not create history entries. + +## Affected packages + +Initial implementation: `compas`, `compas_viewer`, and `compas_framework`. + +Later redesign consumer: `compas_model`. + +## Dependencies + +- [ADR 001](001-ownership-boundaries.md) +- [ADR 003](003-viewer-state-and-selection.md) diff --git a/initiatives/scene-viewer-visualisation/decisions/005-annotations-and-overlays.md b/initiatives/scene-viewer-visualisation/decisions/005-annotations-and-overlays.md new file mode 100644 index 0000000..24f87b5 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/005-annotations-and-overlays.md @@ -0,0 +1,92 @@ +# ADR 005: Annotations, Measurements, and Overlays + +## Status + +Accepted, amended by ADRs 024 and 028. + +## Context + +Viewer has concrete `Tag` and `ArrowOverlay` rendering paths but no general +measurement, dimension, scale, or legend behavior. Treating every visual aid +as a scene item would serialize view-dependent UI; treating every annotation +as an overlay would lose world anchoring and durable intent. + +## Options + +1. Separate durable world annotations from transient screen overlays. +2. Make every annotation and overlay a core scene item. +3. Keep every visual aid as a renderer-special-cased Viewer class. +4. Add a framework-wide overlay plugin registry before adding features. + +## Recommendation + +Choose option 1. + +- World text annotations and distance dimensions are serializable scene items + with Viewer adapters. Distance dimensions store two anchors, unit, + precision, and optional label override; distance is derived. +- Scale indicators and legends are transient screen-space Viewer overlays and + are not serialized or picked initially. +- Measurement preview state belongs to the active Viewer tool. Completing a + transient inspection does not mutate Scene. Completing an explicitly + persistent dimension-annotation mode creates a durable distance dimension; + cancelling either mode creates nothing. +- Fixed and associative persistent dimension modes both use snapping. Fixed + acquisition stores a point; associative acquisition stores a supported + component reference and never silently falls back to a point. + +Align current Tag/Arrow behavior with these paths. Use one Viewer overlay layer +for the approved screen types and ordinary scene adapter registration for +world annotations. Do not add a general overlay registry. + +## Consequences + +- Persistence follows user intent rather than rendering technique. +- World annotations participate in hierarchy and transformations. +- View-dependent overlays remain independent of scene files. +- Current concrete renderer checks can be consolidated behind the two paths. +- Dimension editing, angular dimensions, and arbitrary overlay plugins remain + later requirements. Initial snap targets and acquisition behavior are + governed by ADR 026. + +## Compatibility + +Accepted ADR 023 records the completed migration audit and chooses a clean +break. `Tag`, `ArrowOverlay`, their aliases, and their serialized dtype paths +are removed when the canonical types land. Old payloads are unsupported and no +compatibility decoder silently reinterprets them. + +## Verification + +- Test distance derivation, units, precision, label override, transformed + parents, serialization, and reload. +- Test transient inspection and persistent dimension preview/cancel/complete + state transitions, including their different scene-mutation behavior. +- Test fixed and associative snapping, mixed anchors, and explicit unresolved + component references without silent fallback. +- Assert scale and legend overlays are absent from scene serialization. +- Verify renderer ordering, resize behavior, and no concrete type checks in + the main render loop for approved types. + +## Affected packages + +`compas`, `compas_viewer`, and `compas_framework`. + +## Dependencies + +- [ADR 001](001-ownership-boundaries.md) +- [ADR 002](002-indexed-buffer-geometry.md) +- [ADR 003](003-viewer-state-and-selection.md) + +## Amendment + +Accepted ADR 024 refines measurement outcomes after the user identified two +distinct intents. Live inspection is transient and never creates scene +content. Persistent dimension-annotation mode may share acquisition and +preview infrastructure, but only its completion creates a durable +`DistanceDimension`. + +Accepted ADR 028 adds explicit fixed and associative persistent dimension +anchors. Both modes use snapping, but only Associative mode stores a component +reference. Missing components become unresolved rather than silently falling +back or displaying stale coordinates. diff --git a/initiatives/scene-viewer-visualisation/decisions/006-viewer-integration-facade.md b/initiatives/scene-viewer-visualisation/decisions/006-viewer-integration-facade.md new file mode 100644 index 0000000..597fd63 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/006-viewer-integration-facade.md @@ -0,0 +1,88 @@ +# ADR 006: Public Viewer Integration Facade + +## Status + +Accepted. + +## Context + +Viewer-owned commands and components reach into concrete renderer and widget +objects. Viewer has command and menu composition but no equally clear public +dock or synchronization boundary. Optional consoles or assistants should not +force shell, network, or credential behavior into the Viewer core. + +## Options + +1. Expose a small public Viewer facade for scene, state, refresh, history, + commands, docks, annotations, and overlays. +2. Let integrations continue using renderer and widget internals. +3. Define a large abstract Viewer/controller framework for every domain. +4. Design the facade around the current draft `ModelViewer` controller. + +## Recommendation + +Choose option 1. Provide public operations for: + +- scene access and GUID resolution; +- selection and transient state; +- categorized refresh; +- transform transactions and undo/redo; +- command registration and menu placement; +- dock addition/removal; and +- annotation and overlay addition/removal. + +The facade is defined only by approved Viewer-owned tools, commands, state, +annotations, overlays, refresh, and UI composition. Do not create a generic +controller base class or add operations solely to match a current external +consumer. + +A future console, terminal, or assistant may use a dock and registered command +API. Arbitrary Python/shell execution, subprocesses, credentials, network +transport, and assistant policy require a separate security ADR and are not +implemented in this wave. + +## Consequences + +- Viewer-owned components gain a stable, testable integration surface that + later consumers may reuse. +- Viewer internals can change without coordinated domain rewrites. +- Public API growth is limited to demonstrated Viewer feature needs. +- Dock content remains Viewer/Qt-specific; core stays UI-independent. +- Console/chat presentation becomes possible without prematurely authorizing + execution or remote services. + +## Compatibility + +The current draft `ModelViewer` has no compatibility requirements under this +ADR. Its later redesign may consume the proven facade but may not enlarge it +without a demonstrated requirement and approval. + +## Verification + +- Test facade behavior with a lightweight fake UI/renderer boundary. +- Forbid private renderer/widget access in Viewer-owned command, tool, and + component tests. +- Verify dock and command registration/removal and duplicate-ID failures. +- Verify plugin discovery imports no Qt/OpenGL or optional-consumer + implementation modules. + +## Affected packages + +`compas_viewer` and `compas_framework`. `compas_model` is a later redesign +consumer. + +## Dependencies + +- [ADR 001](001-ownership-boundaries.md) +- [ADR 003](003-viewer-state-and-selection.md) +- [ADR 004](004-transform-refresh-undo.md) +- [ADR 005](005-annotations-and-overlays.md) + +## Refinement after acceptance + +The original context and compatibility clauses relied too heavily on the +current `compas_model.ModelViewer`. Explicit user correction establishes that +controller as a draft that may be redesigned freely. The accepted decision is +therefore narrowed to a small Viewer-owned public boundary justified by +Viewer's own approved capabilities; no ModelViewer behavior or controller +shape is preserved. diff --git a/initiatives/scene-viewer-visualisation/decisions/007-scope-and-verification.md b/initiatives/scene-viewer-visualisation/decisions/007-scope-and-verification.md new file mode 100644 index 0000000..97ea306 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/007-scope-and-verification.md @@ -0,0 +1,89 @@ +# ADR 007: Initial Scope and Verification + +## Status + +Accepted. + +## Context + +Core Scene is consumed by Viewer, model, notebook, session, and CAD-host +packages. Expanding the first implementation across every backend would mix +runtime-specific migrations and make completion evidence unavailable. Package +tests alone do not prove installed cross-package behavior. + +## Options + +1. Implement an initial core/Viewer/framework wave and compatibility- + review adjacent consumers. +2. Migrate every visualisation and host package in one wave. +3. Change Viewer only and defer core scene alignment. +4. Accept package-local source tests as completion evidence. + +## Recommendation + +Choose option 1. + +Initial implementation packages are `compas`, `compas_viewer`, and +`compas_framework`. Review `compas_model`, `compas_session`, +`compas_notebook`, Rhino, Grasshopper, and Blender for compatibility with core +changes, but do not modify them without a scope amendment and approval. + +Require: + +- focused and full applicable local tests, Ruff, Pyright, and strict docs; +- clean package CI and built-wheel checks at exact heads; +- framework CI installing exact candidates and exercising plugin discovery, + scene and Viewer construction, indexed buffers, selection, transformations, + annotations, serialization, and graphics-free discovery; and +- candidate-artifact CI for claims about independently built distributable + compatibility. + +Coordinate the plugin initiative's installed model/viewer registry gate rather +than creating a second competing test. + +## Consequences + +- The first wave remains verifiable on ordinary CI with offscreen Viewer + support. +- Host-specific behavior remains unverified and unmodified, not implicitly + passed. +- Core compatibility risks are still inspected before implementation. +- Later session, notebook, host, sub-object selection, advanced transform, + and console/assistant waves require explicit decisions. + +## Compatibility + +Any approved core change must preserve current public scene contracts for +compatibility-only consumers or identify a concrete blocker and return for +scope/compatibility approval before implementation proceeds. + +## Verification + +- Record local, package, framework-integration, and candidate-artifact + evidence separately in the handoff. +- Pin exact commit and artifact identities. +- Treat unavailable required runtime evidence as unverified, not passing. +- Keep generated files in isolated temporary directories. + +## Affected packages + +Initial: `compas`, `compas_viewer`, and `compas_framework`. + +Later redesign consumer and regression evidence: `compas_model`. + +Compatibility review only: `compas_session`, `compas_notebook`, Rhino, +Grasshopper, and Blender scene adapters. + +## Dependencies + +- [ADRs 001–006](README.md) +- Plugin-implementations ADR 005 + +## Refinement after acceptance + +The initial package list previously included `compas_model` as though the +current `ModelViewer` behavior constrained this initiative. Explicit user +correction moves it to a later redesign phase. Its current serialization +failure remains valid evidence for core scene reconstruction, but its +hierarchy projections, selection behavior, cache, controller shape, and facade +usage are not initial-wave completion criteria. diff --git a/initiatives/scene-viewer-visualisation/decisions/008-scene-nodes-and-runtime-adapters.md b/initiatives/scene-viewer-visualisation/decisions/008-scene-nodes-and-runtime-adapters.md new file mode 100644 index 0000000..ea845f3 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/008-scene-nodes-and-runtime-adapters.md @@ -0,0 +1,180 @@ +# ADR 008: Serializable Scene Nodes and Runtime Adapters + +## Status + +Superseded by ADRs 013–014. + +## Context + +ADR 001 correctly separates durable scene content from Viewer interaction and +renderer state, but it still treats `SceneObject` as both durable node and +context-specific runtime adapter. Current serialization stores an item's GUID +plus `sceneobject.settings`, then calls `Scene.add(..., **settings)` during +load. Factory dispatch chooses a runtime subclass and executes its constructor +before that object is attached to the reconstructed hierarchy. + +Two verified regressions expose the consequences: + +1. A Viewer Box/ShapeObject with local translation `[2, 0, 0]` reloads with + `transformation is None` because `ViewerSceneObject.settings` replaces + rather than extends core settings. In a headless ShapeObject case, `u=7`, + `v=9`, and a face color reload as the defaults `16`, `16`, and the default + face color. +2. A `ModelViewer` scene cannot reload. The controller originally creates + `ModelObject(add_elements=False)` and `ElementObject(add_children=False)`, + but those construction controls are absent from serialized settings. + Reload dispatches `ModelObject` with `add_elements=True`; its constructor + calls `self.add(...)` before attachment and raises `RuntimeError: A detached + scene object cannot own child objects.` Render caches are transient and + should not be serialized, but hierarchy reconstruction must not depend on + them or on constructor side effects. + +The shared item store already preserves identity when multiple nodes reference +one item GUID. Scene-object/node GUIDs are not preserved across round trips. +Context also determines which runtime subclass is constructed, even though a +serialized scene should remain loadable without that backend. + +## Options + +1. Separate a serializable scene-owned node/state value from context-specific + runtime adapters and reconstruct them in two phases. +2. Keep `SceneObject` as both node and adapter and expand every subclass's + `settings` property until current tests pass. +3. Serialize complete runtime adapter objects, including their concrete class + and context. +4. Serialize only items and hierarchy and discard all per-node appearance and + transformations. + +## Recommendation + +Choose option 1. + +`Scene` owns a serializable node/state record for every hierarchy entry. The +closed base record contains: + +- a durable node GUID; +- node kind (`item` or `group`); +- optional item GUID; +- name; +- local transformation; +- visibility, opacity, and base appearance; and +- explicitly declared extension state governed by ADR 009. + +Items remain separate and keyed by item GUID, preserving shared item identity. +Accepted ADR 010 requires a serialized scene description to reference those +items without embedding them. Node GUIDs are serialized +and restored so selection references, domain indexes, and external scene +references have durable identity. Runtime adapter instances are not durable +identities. + +Deserialize in two phases: + +1. validate and create nodes, state, GUIDs, and the complete hierarchy without + requiring item bindings, context dispatch, or adapter constructors; +2. bind adapters for an explicitly requested or detected runtime context only + after the scene is structurally complete, either eagerly for drawing or + lazily on first use. + +`SceneObject` becomes the runtime adapter bound to a scene, node, and optional +item. Its constructor must not populate hierarchy or own serialized state. +Application/domain projection creates nodes explicitly through an owning +controller; adapter binding never recreates children. The current draft +`ModelViewer` is evidence of why constructor-driven hierarchy creation fails, +not a controller contract to preserve. + +Scene context is runtime binding configuration, not authoritative serialized +content. A scene may record a non-binding context hint for user experience, +but loading must not require that context or silently select a different one. +Drawing without a usable context raises a precise runtime error after the +backend-neutral scene has loaded. + +Known extension fields are activated only by a compatible adapter. Unknown +extension namespaces and fields are preserved losslessly as inactive node +state and written back unchanged. Unknown required base schema versions fail +validation; unknown adapter state is not passed blindly to constructors. + +## Refinement of ADR 001 + +This ADR preserves ADR 001's package boundaries but refines these clauses: + +- "Core owns scene items, hierarchy, scene-object GUIDs..." becomes: core + owns durable node/state GUIDs and stable item references; runtime adapter + identity is not serialized. Accepted ADR 010 defines the non-owning runtime + binding boundary for items. +- "GUIDs connect durable scene objects to Viewer state" becomes: durable node + GUIDs connect scene content to Viewer state and domain indexes. +- Core still owns transformations, visibility, durable appearance, and + serialization, but those values live on node state rather than being + discovered from a runtime adapter's constructor/settings implementation. + +ADR 001's durable identity and serialization boundary is amended by this +Accepted decision and ADR 009. Accepted ADR 010 defines item ownership and +packaging. + +## Consequences + +- Scenes load without Viewer, model adapters, or another visualization backend. +- Runtime constructors no longer execute hierarchy-building side effects during + deserialization. +- Switching or omitting runtime contexts does not destroy durable node state. +- Shared item identity and durable node identity have separate, explicit GUIDs. +- Core Scene/SceneObject APIs require a coordinated redesign and compatibility + review; this is larger than patching two `settings` properties. +- Adapter binding and lifecycle need focused tests, but no universal renderer + abstraction or event bus is introduced. + +## Compatibility + +The new node schema replaces the existing serialized scene shape. The initial +implementation does not include a compatibility loader because current files +omit required state and cannot be migrated reliably without guessing. If +concrete legacy files later require recovery, migration tooling needs separate +evidence, scope, and approval. + +Existing public code may continue to receive a `SceneObject` adapter from +`Scene.add`, but code that treats adapter identity or constructor side effects +as durable must migrate. Exact compatibility is part of the Phase 1 audit. + +## Verification + +- Reproduce the Viewer regression as a focused test and retain the draft + ModelViewer failure as evidence. +- Round-trip local transformations, `u=7`, `v=9`, face color, shared items, + node GUIDs, groups, and hierarchy without a visualization backend installed. +- Use a minimal test adapter with constructor-side-effect behavior to prove + hierarchy deserialization never invokes runtime construction; redesign and + test the actual ModelViewer later. +- Load and re-save unknown extension state without loss or constructor use. +- Verify missing/unknown context permits load but produces a precise binding or + draw error. +- Verify duplicate item or node GUIDs and unsupported base schema versions fail + atomically. + +## Affected packages + +Initial implementation: `compas`, `compas_viewer`, and `compas_framework`. + +Later redesign/regression consumer: `compas_model`. + +Compatibility review only: `compas_session`, `compas_notebook`, and CAD-host +scene adapters. + +## Dependencies + +- [ADR 001](001-ownership-boundaries.md), refined by this decision + +ADR 009 supplies the serialization field policy required to implement this +decision. ADR 010 separately decides that referenced items remain external to +Scene and defines the boundary for later Session aggregation. + +## Decision + +Accepted on 2026-11-07. The user additionally required a separate decision +ensuring that independently serializable `Data` objects are not forced to live +inside a scene. Accepted ADR 010 records that packaging refinement without +changing this decision's accepted node/adapter separation. + +Superseded on 2026-11-07 after implementation exposed duplicate detached/bound +state and backend-dependent object types. Accepted ADRs 013–014 retain +backend-independent loading and reference-only data binding while assigning +durable state to stable scene objects and backend behavior to operations. diff --git a/initiatives/scene-viewer-visualisation/decisions/009-scene-state-fields.md b/initiatives/scene-viewer-visualisation/decisions/009-scene-state-fields.md new file mode 100644 index 0000000..93752df --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/009-scene-state-fields.md @@ -0,0 +1,113 @@ +# ADR 009: Explicit Scene-State Serialization Fields + +## Status + +Superseded in part by ADR 013. + +## Context + +Current scene serialization depends on each runtime adapter's `settings` +property and reconstructs state by replaying that mapping as constructor +arguments. Subclasses can accidentally replace base settings, as demonstrated +by the lost transformation regression. Required subclass state can be omitted, +as demonstrated by lost ShapeObject resolution and face color. Conversely, +serializing `__dict__`, every property, annotations, or constructor parameters +would capture caches, renderer handles, item/scene backreferences, derived +values, and construction commands such as `add_elements`. + +The durable node proposed by ADR 008 needs an explicit field policy that +supports inheritance without treating Python introspection as persistence. + +## Options + +1. Use a closed base node-state schema plus explicit MRO-composed extension + field declarations. +2. Serialize every entry in `__dict__` except a growing denylist. +3. Serialize every public property, type annotation, or constructor parameter + discovered through introspection. +4. Require every subclass to replace and manually merge a free-form + `settings` dictionary. +5. Allow only the closed base schema and prohibit all adapter/domain extension + state. + +## Recommendation + +Choose option 1. + +Base node state is a closed value-object schema owned by core. A class that +owns additional durable scene state declares only its local fields through an +explicit class-level declaration. The serializer composes declarations across +the MRO from base to subclass, rejects duplicate or incompatible declarations, +and stores extension values under a stable owning namespace. + +Declarations specify the serialized name, expected value contract, default or +required status, and whether omission is allowed. They do not execute arbitrary +getters during schema discovery. The implementation may use annotations, +constructor signatures, descriptors, and properties only to validate a +declaration or generate editor/documentation metadata; introspection never +decides that a field is persistent. + +Unrestricted `__dict__`, public-property, constructor-parameter, or annotation +serialization is forbidden. Derived values, scene/item backreferences, +renderer/GPU handles, pick IDs, caches, selection, hover, tools, and command +history are not durable fields. `ModelObject.add_elements` and +`ElementObject.add_children` are construction commands, not state. Model render +caches are transient. Shape resolution and durable colors are serialized only +through explicit declarations. + +Deserialization validates the closed base state and known declarations without +passing a free-form mapping to adapter constructors. Unknown namespaced +extension values remain inactive and round-trip unchanged under ADR 008. + +## Consequences + +- Base transformations and subclass fields cannot disappear because a + subclass forgot `super().settings`. +- Persistence changes are visible in code review and independently testable. +- Runtime caches and constructor side effects are excluded by default. +- Subclasses must deliberately declare every durable field and migration. +- Editor tooling can reuse schema metadata without becoming the source of + truth for persistence. +- A small schema/version and migration mechanism is required for renamed or + removed fields; it remains data-focused rather than adapter-constructor + compatibility code. + +## Compatibility + +Legacy `settings` mappings are not accepted by the new serializer. They are +incomplete, unversioned, and cannot be mapped into declared base/extension +fields reliably. The new implementation reads and writes only the explicit +schema. Any later recovery tool remains separate from runtime serialization. + +## Verification + +- Assert MRO composition preserves base transformation plus declared subclass + `u`, `v`, and face color. +- Assert duplicate field declarations, invalid values, missing required fields, + and unknown base fields fail with precise paths. +- Prove caches, Viewer handles, pick IDs, selection, and construction commands + are absent from serialized state. +- Prove unknown namespaced extension state round-trips byte-for-value without + importing or constructing its adapter. +- Use introspection-based validation tests to detect a declaration that names a + missing/incompatible attribute, without auto-serializing undeclared members. + +## Affected packages + +Initial implementation: `compas`, `compas_viewer`, and `compas_framework`. + +Later redesign/regression consumer: `compas_model`. + +## Dependencies + +- [ADR 008](008-scene-nodes-and-runtime-adapters.md) + +## Decision + +Accepted on 2026-11-07. Persistent fields use the closed base schema and +explicit MRO-composed declarations described above. Item ownership and +serialization packaging are decided separately by Accepted ADR 010. + +Superseded in part on 2026-11-07. Accepted ADR 013 retains the closed-schema, +explicit-field principle but moves durable state from node extensions onto +ordinary stable scene-object attributes and rejects attribute interception. diff --git a/initiatives/scene-viewer-visualisation/decisions/010-scene-description-and-item-bundling.md b/initiatives/scene-viewer-visualisation/decisions/010-scene-description-and-item-bundling.md new file mode 100644 index 0000000..0b7fe72 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/010-scene-description-and-item-bundling.md @@ -0,0 +1,144 @@ +# ADR 010: Scene Description, Item Bindings, and Aggregation Boundary + +## Status + +Accepted. + +## Context + +ADRs 008–009 separate durable scene node state from runtime adapters and define +its serialization fields. They do not yet decide whether referenced domain +items must be embedded in a serialized scene. + +A geometry or other `Data` object may need to be serialized independently for +later algorithmic processing while also being referenced by one or more scene +nodes. It must not be forced to live inside the scene or require extraction +from a scene file before ordinary data processing. Conversely, users sometimes +need an aggregate containing data, one or more scenes, settings, and history. + +The current item table preserves shared identity inside one scene file, but +conflates a scene description, runtime bindings, and packaging. + +## Options + +1. Keep Scene reference-only and treat a redesigned Session as the likely + optional aggregate under a separate decision and scope. +2. Always embed every referenced item in the scene serialization. +3. Add a dedicated `SceneBundle` containing one scene plus its items. +4. Introduce a general asset catalog with URIs, search paths, network loading, + and resolver plugins. + +## Recommendation + +Choose option 1. + +Define one Scene role, its runtime bindings, and one later aggregation boundary: + +- `Scene` is the durable, backend-neutral visual description from ADRs 008–009. + Its serialized node hierarchy contains stable item GUID references only. + At runtime it may hold a nonserialized binding table from those GUIDs to + already loaded `Data` objects. A binding is a reference, not ownership; the + same object remains independently usable and serializable. +- A redesigned `compas_session.Session` is the likely optional aggregate for + independently serialized data, one or more scene descriptions, settings, + history, and their shared identity. Its exact schema, ownership, and loading + behavior require a separate dependent decision and explicit scope approval. + Do not add Session implementation to the current wave. + +A later Viewer/Session integration may provide convenient new, open, and save +operations. Viewer remains a client of Session persistence: it does not own the +aggregate format, and session support remains optional and lazily loaded. The +exact convenience API follows the separately approved Session redesign. + +The intended runtime operations are conceptually: + +```python +scene = Scene.from_json(...) +scene.bind(item) +scene.bind_many(items) +``` + +Exact method naming may follow established core conventions during +implementation. Scene serialization remains reference-only; it is not +controlled by an `include_items` boolean. + +Loading a Scene succeeds when item references are unresolved. Hierarchy, +node state, and reference inspection remain available. Binding an item uses +its existing GUID. Binding the same instance again is idempotent; binding a +different object with the same GUID is rejected. All nodes referencing one +GUID resolve to the same bound object instance. + +Drawing, adapter binding, or another operation that requires an +unresolved item raises a precise error containing the node GUID and item GUID. +The caller may bind the item later and retry. Serialization and inspection of +the reference-bearing description do not require bindings. + +Do not add URIs, filesystem lookup, network loading, an asset registry, or a +resolver plugin. Callers load `Data` objects through existing serialization and +bind them explicitly. A concrete external-resource requirement would need a +separate decision. + +## Refinement of ADR 008 + +ADR 008's separate item store is refined into a runtime binding table. Core +owns the Scene description and stable references, but it does not claim +exclusive ownership of bound `Data` objects. Aggregation belongs outside Scene; +a future Session design may package objects without making that aggregate their +only valid serialization path. + +## Consequences + +- Domain data remains independently serializable and directly available for + algorithms. +- Scenes can be stored, compared, or transmitted without + duplicating large items. +- A future self-contained aggregate can support multiple scenes, settings, and + history without introducing a redundant one-scene bundle type now. +- Shared identity is deterministic within a runtime Scene and must remain so + in any future approved Session aggregate. +- Unresolved references become a normal, inspectable state with precise + failure at item-dependent operations. +- Cross-file discovery remains the caller's responsibility; no speculative + asset system is introduced. + +## Compatibility + +The new Scene format is reference-only. Existing `Data` serialization remains +unchanged. A future Session aggregate and any legacy recovery tooling remain +outside Scene runtime serialization and require separate approval. + +## Verification + +- Serialize and load one `Data` object independently, bind it to a separately + loaded Scene, and run an algorithm on the original/bound object + without extraction or copying. +- Round-trip a reference-only Scene while items remain unresolved. +- Bind later and prove every node sharing one item GUID resolves to the same + object instance. +- Reject a different object with a duplicate GUID atomically. +- Raise precise node/item errors for draw and adapter operations that + require unresolved items. +- Prove description serialization needs no bound items and no URI/network + resolver is invoked. +- In a separate future Session decision, verify data and multiple scenes share + identity without requiring extraction from Scene. + +## Affected packages + +Initial implementation: `compas` and `compas_framework`. + +Consumer: `compas_viewer`. + +Separate later design/scope: `compas_session`, followed by `compas_model`, +notebook, and CAD-host integrations as applicable. + +## Dependencies + +- [ADR 008](008-scene-nodes-and-runtime-adapters.md) +- [ADR 009](009-scene-state-fields.md) + +## Amendment + +Accepted ADR 013 amended this decision on 2026-11-07: item GUID references live +on stable scene objects rather than hierarchy nodes. Items remain independently +serializable, explicitly bound, and outside the serialized scene description. diff --git a/initiatives/scene-viewer-visualisation/decisions/011-node-first-scene-adapters.md b/initiatives/scene-viewer-visualisation/decisions/011-node-first-scene-adapters.md new file mode 100644 index 0000000..8980f81 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/011-node-first-scene-adapters.md @@ -0,0 +1,102 @@ +# ADR 011: Node-First Scene Construction and Adapter Lifetime + +## Status + +Superseded by ADRs 013–014 before acceptance. + +## Context + +ADR 008 correctly separates durable scene nodes from runtime adapters, but its +first implementation still constructs a detached `SceneObject` before creating +the node. The adapter temporarily owns the item reference, GUID, name, +transformation, appearance, and extension values. Binding then changes those +properties to read from the node. + +This creates two object modes, duplicate storage, and identity whose meaning +changes after binding. Verified probes show that removal can expose stale +provisional values and a different GUID. Context rebinding replaces adapters +and leaves external references detached with the same stale fallback state. +The implementation therefore contradicts ADR 008's requirement that an +adapter constructor must not own serialized state. + +## Options + +1. Create the node first and construct a permanently node-bound runtime + adapter from `(scene, node)`. +2. Retain detached and bound adapter modes while hiding the transition behind + additional helpers. +3. Put runtime drawing behavior directly on `SceneNode`. +4. Preserve detached adapters through a compatibility wrapper. + +## Recommendation + +Choose option 1. + +`SceneNode` remains the sole durable authority for identity, hierarchy, item +GUID, name, local transformation, appearance, visibility, and extension state. +`SceneObject` becomes a plain runtime adapter rather than a `Data` object. It +is constructed only from an existing scene and node and owns only context +handles, derived caches, drawing behavior, and invalidation. + +Keep the convenient public call: + +```python +sceneobject = scene.add(mesh, color=Color.red(), show=True) +``` + +Internally, `Scene.add` resolves the adapter type, validates node and extension +arguments, creates and attaches the node, records the item binding, and only +then creates `adapter_type(scene, node)`. Failure rolls back the node and item +binding atomically. + +Deserialization remains node-only. `Scene.bind_context` constructs a complete +replacement adapter table after hierarchy and required items exist, then swaps +it in atomically. Adapter construction never creates hierarchy or durable +state. + +Remove detached adapter construction, `Scene.add(sceneobject)`, adapter +serialization, adapter-owned temporary GUIDs and presentation fallbacks, and +constructor-driven child creation. Registry dispatch moves from +`SceneObject.__new__` to `Scene`. + +Removed or context-replaced adapters become invalid runtime references. They +do not transition to a detached reusable mode. Re-adding content means adding +the `Data` item or retaining and explicitly rebinding an existing node. + +## Compatibility + +This intentionally breaks direct `SceneObject(item, ...)`, +`Scene.add(sceneobject)`, reusable removed adapters, and one-shot +`SceneObject(item).draw()`. Core and Viewer tests migrate to `Scene.add`. +GhPython one-shot conversion requires a small explicit context helper or local +scene. CAD-host adapters require audit before their later migration. + +`Scene.add(data, ...)`, registry/context dispatch, durable node GUIDs, +reference-only serialization, unresolved loading, explicit item binding, and +shared item identity remain public behavior. + +Direct `Group(...)` construction and arbitrary group constructor keywords as +future child defaults are removed. `scene.add_group(...)` creates the node +first; callers pass child presentation explicitly. + +## Verification + +- Prove the node exists before adapter construction. +- Prove adapter constructors receive only scene and node. +- Prove construction and context-binding failures roll back atomically. +- Prove GUID meaning and durable property storage never switch. +- Prove removed and replaced adapters fail precisely. +- Prove deserialization and unknown extension round trips need no adapters. +- Preserve Viewer round trips and `compas_model` compatibility through the + public `Scene.add(data, ...)` path. + +## Dependencies + +- Supersedes the construction, adapter identity, and compatibility clauses of + Accepted [ADR 008](008-scene-nodes-and-runtime-adapters.md). +- Preserves Accepted [ADR 010](010-scene-description-and-item-bundling.md). +- Works with Proposed [ADR 012](012-explicit-node-backed-adapter-state.md). + +## Decision + +Not accepted. Superseded on 2026-11-07 by Accepted ADRs 013–014. diff --git a/initiatives/scene-viewer-visualisation/decisions/012-explicit-node-backed-adapter-state.md b/initiatives/scene-viewer-visualisation/decisions/012-explicit-node-backed-adapter-state.md new file mode 100644 index 0000000..3f41682 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/012-explicit-node-backed-adapter-state.md @@ -0,0 +1,79 @@ +# ADR 012: Explicit Node-Backed Adapter State + +## Status + +Superseded by ADR 013 before acceptance. + +## Context + +ADR 009 correctly requires a closed base schema and explicit namespaced +extension declarations. Its implementation, however, uses +`SceneObject.__getattribute__` and `__setattr__` to scan declarations and +redirect attributes dynamically. Other durable fields use individual +node-or-local properties, and color uses a special descriptor. The result is +three different state-routing mechanisms whose behavior changes when an +adapter binds to a node. + +The declarations should define persistence and validation, not invisibly +change normal Python attribute access. + +## Options + +1. Keep declarations as schema metadata and implement ordinary explicit + node-backed adapter properties. +2. Replace interception with a general descriptor or state-proxy framework. +3. Store durable adapter state in a third state object. +4. Keep the current interception and add documentation. + +## Recommendation + +Choose option 1. + +Keep `SceneStateField`-style declarations only for stable names, namespaces, +types, defaults, required fields, validation, and preservation of unknown +extension state. `Scene.add` validates declared keyword arguments and writes +them directly to `SceneNode.extensions`. Deserialization validates known state +without constructing adapters. + +Adapters expose ordinary properties whose implementation visibly reads and +writes the node. A small typed `SceneNode.extension(namespace, field)` and +`set_extension(...)` helper may remove repetitive mapping access. Do not add a +general descriptor, proxy, reflection layer, or global attribute interception. +Property setters perform required invalidation explicitly. + +Remove extension capture/apply operations, declaration-driven +`__getattribute__`/`__setattr__`, detached attribute validation, and all local +durable fallbacks. Base properties such as name, transformation, color, +opacity, and visibility are likewise direct node-backed properties on an +always-bound adapter. + +## Consequences + +- Durable state has one storage location and one visible access path. +- Persistence remains explicit and reviewable. +- Adapter classes contain some repetitive properties, which is preferable to + hidden control flow. +- Unknown namespaced state remains serializable without importing its adapter. +- Constructor signatures no longer double as persistence or editor schemas. + +## Verification + +- Prove each declared property reads and writes its node extension. +- Prove setters trigger their documented cache invalidation. +- Reject unknown, missing, duplicate, and invalid declared fields precisely. +- Preserve unknown namespaces without adapter imports. +- Prove caches, selection, context handles, and construction commands are not + durable. +- Assert no runtime adapter class uses persistence interception or capture. + +## Dependencies + +- Supersedes the runtime interception and capture mechanism introduced under + Accepted [ADR 009](009-scene-state-fields.md), while retaining its closed + schema and explicit declarations. +- Depends on Proposed [ADR 011](011-node-first-scene-adapters.md). +- Preserves Accepted [ADR 010](010-scene-description-and-item-bundling.md). + +## Decision + +Not accepted. Superseded on 2026-11-07 by Accepted ADR 013. diff --git a/initiatives/scene-viewer-visualisation/decisions/013-hierarchy-nodes-and-stable-sceneobjects.md b/initiatives/scene-viewer-visualisation/decisions/013-hierarchy-nodes-and-stable-sceneobjects.md new file mode 100644 index 0000000..c57b732 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/013-hierarchy-nodes-and-stable-sceneobjects.md @@ -0,0 +1,125 @@ +# ADR 013: Hierarchy-Only Nodes and Stable Scene Objects + +## Status + +Accepted. + +## Context + +Accepted ADR 008 separated durable scene nodes from runtime adapters, but the +implementation duplicated state across detached and bound adapter modes. +Proposed ADR 011 removes that dual lifecycle, but still makes `SceneNode` own +both hierarchy and all durable visual state while `SceneObject` is only a +runtime projection. This leaves two public concepts that appear to describe +the same scene entry and makes backend-specific replacement classes central to +ordinary object access. + +A simpler separation is possible: nodes describe only hierarchy; stable scene +objects describe everything durable about a visualized item; backends provide +operations rather than replacement object classes. + +## Options + +1. Use hierarchy-only nodes and durable, stable scene objects. +2. Keep durable state on nodes and make scene objects always-bound adapters as + proposed by ADRs 011–012. +3. Merge hierarchy and durable state back into one tree-node class. +4. Keep the implemented detached/bound adapter model. + +## Recommendation + +Choose option 1. + +`SceneObject` is a backend-neutral `Data` object with a stable Python type and +GUID. It owns: + +- the referenced item GUID, if any; +- name and local transformation; +- visibility, opacity, and durable backend-neutral appearance; and +- stable semantic type-specific state. + +Stable subclasses such as `GroupObject`, `GeometryObject`, `ShapeObject`, +`MeshObject`, `GraphObject`, and `VolMeshObject` express durable semantics. +Installing Viewer, Rhino, Blender, or another backend never changes an +object's class. + +`SceneNode` owns only ordered parent/child relationships and a reference to one +scene-object GUID. Enforce exactly one node per scene object in one scene. +Instancing is not included. Multiple appearances of one data item use multiple +scene objects referencing the same item GUID. + +Do not serialize a second durable node GUID. The scene-object GUID is the +hierarchy key. The root is an ordinary `GroupObject` with a corresponding root +node rather than a special identity model. + +`Scene` owns separate object and hierarchy stores. `scene.add(item, **state)` +creates the stable semantic scene object, attaches its hierarchy node, and +returns the object. `scene.add_object(sceneobject, parent=...)` explicitly +attaches an existing durable scene object; `Scene.add` is not overloaded with +runtime adapters. + +Scene serialization contains a version, name, stable scene-object records, +and a hierarchy of scene-object GUID references. Referenced `Data` items remain +external under ADR 010. Loading requires no visualization backend and leaves +item references unresolved until explicitly bound. + +Durable type-specific state follows ADR 009's useful rule: a closed base schema +plus explicit fields. State lives as ordinary `SceneObject` attributes, not in +node extensions and not behind attribute interception. Unknown namespaced +state may be retained solely for lossless forward round trips. Backend plugins +may not add durable fields. + +Selection, picking, UI state, renderer configuration, generated buffers, +handles, and caches remain runtime/application state outside `SceneObject`. + +## Consequences + +- Nodes, scene objects, represented data, and backend operations have distinct + and explainable roles. +- Scene-object type and GUID remain stable through attachment, removal, + serialization, and context changes. +- A durable scene object may exist detached without acquiring a second storage + mode; attachment adds only a nonserialized scene backreference. +- Removing and explicitly reattaching an object never reveals stale fallback + values or changes identity. +- The scene schema changes from nested stateful nodes to object records plus a + hierarchy of references. +- Backend-specific replacement classes are removed under ADR 014. + +## Compatibility + +Preserve `scene.add(data, ...)`, shared item identity, unresolved scene loading, +explicit item binding, stable object GUIDs, and hierarchy operations through +returned scene objects. + +Remove backend adapter serialization, constructor-driven child creation, and +implicit group child defaults. `GroupObject` is durable and backend-neutral. +`compas_model`'s maintained controller path already uses `scene.add`; its custom +scene-object redesign remains a later phase. + +## Verification + +- Prove nodes serialize only hierarchy references. +- Prove one node per scene object and reject accidental instancing. +- Preserve scene-object GUIDs through add, move, remove, reattach, reload, and + visualization-context changes. +- Prove durable state has one storage location. +- Load, inspect, edit, and serialize a scene without backend plugins. +- Bind independently loaded items with shared identity. +- Round-trip multiple scene objects referencing one item. +- Exclude selection, handles, buffers, caches, and context from serialization. + +## Dependencies + +- Intended to supersede Accepted ADR 008 and ADR 009's placement of extension + state if approved. +- Retains ADR 009's closed-schema principle. +- Preserves Accepted ADR 010, with item references moving from nodes to scene + objects. +- Works with Proposed [ADR 014](014-context-keyed-scene-operations.md). + +## Decision + +Accepted on 2026-11-07. The user approved hierarchy-only nodes, stable durable +scene objects, one-to-one node/object cardinality without instancing, and the +scene-object GUID as the sole durable hierarchy key. diff --git a/initiatives/scene-viewer-visualisation/decisions/014-context-keyed-scene-operations.md b/initiatives/scene-viewer-visualisation/decisions/014-context-keyed-scene-operations.md new file mode 100644 index 0000000..6e50e8a --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/014-context-keyed-scene-operations.md @@ -0,0 +1,128 @@ +# ADR 014: Context-Keyed Scene Operation Plugins + +## Status + +Accepted. + +## Context + +Current visualization plugins register replacement `SceneObject` subclasses by +represented item type and context. `SceneObject.__new__` may therefore return a +Viewer, Rhino, Blender, Grasshopper, or Notebook subclass. This changes object +type based on installed plugins and mixes durable scene semantics with backend +runtime behavior. + +The general COMPAS pluggable dispatcher identifies extension points globally +by domain, category, and function name. It does not select an implementation +from a call's explicit context or represented object type. Directly registering +multiple `draw` plugins would therefore conflict when several backends are +installed. + +## Options + +1. Register operation functions in a small scene-specific registry keyed by + context, stable scene-object type, and operation. +2. Extend the general plugin manager with argument-aware dispatch. +3. Use one global backend plugin that switches internally on context and type. +4. Retain backend-specific replacement classes. + +## Recommendation + +Choose option 1. + +Backend packages expose lightweight registration plugins that register +functions rather than classes: + +```python +register_scene_operation( + context="Viewer", + sceneobject_type=MeshObject, + operation="draw", + implementation=draw_meshobject, +) +``` + +Lookup is deterministic by `(context, scene-object type MRO, operation)`. +Duplicate registrations for one exact key fail clearly. Heavy Qt, OpenGL, +Rhino, Blender, or other host imports remain inside operation bodies. + +The initial public operation surface is only: + +- `draw`; +- `clear`. + +Backend-private buffer extraction, host-object creation, component drawing, +refresh strategies, and cache structures do not become speculative public +operations. Additional operations require demonstrated cross-backend need and +approval. + +Conceptually: + +```python +scene.draw(context="Viewer", runtime=viewer) +meshobject.draw(context="Viewer", runtime=viewer) +``` + +The selected implementation receives the owning scene, stable scene object, +and optional transient backend runtime. It may return opaque handles. Runtime +resources live in a nonserialized context store keyed by context and +scene-object GUID, never on the durable object. + +There is no adapter-binding phase. Changing context selects different +operations and resources without replacing scene objects. Automatic context +selection is permitted only when exactly one compatible context is available. +Missing operations report context, scene-object type, and operation. + +Keep the general COMPAS plugin manager unchanged. Its existing lightweight +`register_scene_objects` pattern may be renamed or replaced by +`register_scene_operations`, but discovery must remain graphics-free. + +## Consequences + +- Several visualization backends can coexist without class or plugin + conflicts. +- Backend implementations become ordinary functions with explicit inputs. +- Stable scene-object classes remain backend-neutral. +- Runtime ownership is explicit and serialization-safe. +- Viewer requires a coordinated migration because its renderer currently + consumes concrete `ViewerSceneObject` buffer APIs rather than only `draw`. +- CAD, notebook, robots, and domain backends require later coordinated + migrations before they are admitted as compatible C3 candidates. + +## Compatibility + +Remove context-specific scene-object class registration, +`SceneObject(item, context=...)` factory substitution, `sceneobject_type=`, +`Scene.bind_context`, and direct one-shot `SceneObject(item).draw()`. + +Preserve explicit context selection, automatic selection when unambiguous, +graphics-free plugin discovery, `scene.add(data, ...)`, and deterministic +resource clearing. + +The initial coordinated implementation remains core, Viewer, and framework. +Other backends are recorded as incompatible until migrated; no compatibility +factory should retain type substitution. + +## Verification + +- Install Viewer and a fake second backend simultaneously and select each + explicitly. +- Verify deterministic MRO fallback and duplicate-registration errors. +- Verify missing-operation diagnostics. +- Prove discovery imports no graphics modules. +- Prove context changes never replace or mutate durable scene objects. +- Prove draw/clear resource handling does not enter serialized state. +- Preserve indexed Viewer buffers, picking by stable scene-object GUID, and + exact-candidate framework integration. + +## Dependencies + +- Depends on Proposed [ADR 013](013-hierarchy-nodes-and-stable-sceneobjects.md). +- Replaces context-specific class registration if approved. +- Leaves the general plugin dispatcher unchanged. + +## Decision + +Accepted on 2026-11-07. The user approved context-keyed operation functions, +the initial `draw`/`clear` surface, backend-neutral durable state, and +coordinated later migration of visualization hosts. diff --git a/initiatives/scene-viewer-visualisation/decisions/015-contextual-scene-form-contributions.md b/initiatives/scene-viewer-visualisation/decisions/015-contextual-scene-form-contributions.md new file mode 100644 index 0000000..8b75f75 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/015-contextual-scene-form-contributions.md @@ -0,0 +1,119 @@ +# ADR 015: Editable Scene-Object Attributes + +## Status + +Accepted, amended on 2026-11-08. + +## Context + +Viewer's object-settings form currently infers editable controls from private +render-helper attributes. The first accepted correction introduced a separate +class-level editable-attribute declaration for every editable property. That +would duplicate durable semantic attribute names already declared by +`SceneStateField`, allowing persistence and editability declarations to drift. + +Core needs one normalized answer to “which stable scene-object attributes are +editable?” without acquiring labels, editor choices, form layout, rendering +refresh policy, or other Viewer concerns. + +## Options + +1. Mark durable semantic fields editable on their existing `SceneStateField` + and reserve a separate name-only declaration for editable attributes that + are not scene state fields. +2. Duplicate every editable attribute in a separate class-level declaration. +3. Infer editable fields from annotations, constructors, or `hasattr` checks. +4. Put form descriptors or widget metadata on scene-object classes. + +## Decision + +Choose option 1. + +`SceneStateField` gains only: + +- `editable: bool = False`; and +- an optional synchronous atomic data-only `update(owner, value) -> None` + callback. + +A state field with `update` and `editable=False` is invalid. Without `update`, +an editable field uses `setattr(owner, name, value)`. The callback exists only +for a data-side update that cannot be expressed by direct assignment. It must +leave the owner unchanged if it raises. It is not a Viewer, form, rendering, +refresh, context, or asynchronous hook. + +Durable semantic editable state uses its existing `SceneStateField` as the +single source of both persistence and editability. Subclasses do not repeat +those attribute names in a separate editable declaration. + +`SceneObject.__editable_attributes__` remains a class-level mapping only for +genuinely editable attributes that are not `SceneStateField` entries. Its +initial core entries are `name` and `opacity`, matching the existing inspector. +Each mapping value is only an optional synchronous atomic data-only update +callback; `None` means ordinary `setattr`. + +`SceneObject.editable_attributes()` composes both sources across the class MRO +and returns one normalized ordered mapping: + +```text +attribute name -> optional update callback +``` + +MRO composition must not duplicate subclass names. A name resolves once in the +normalized result, with the most specific applicable definition governing its +callback while retaining deterministic order. + +Core contains no label, editor, arbitrary metadata/data, form identifier, +refresh category, or context metadata. Viewer infers presentation from the +resolved object and owns every form and post-mutation refresh decision. + +The initial scope contains only attributes owned by stable `SceneObject` +instances. Represented-item parameters remain on the existing `ParameterForm` +path. + +## Consequences + +- Durable semantic fields have one declaration rather than parallel state and + editable inventories. +- Non-state editable attributes remain explicit and narrowly scoped. +- All consumers receive the same normalized name-to-callback mapping. +- Core remains free of form presentation and rendering refresh policy. +- Arbitrary widgets, item parameters, dotted paths, asynchronous callbacks, + and refresh callbacks remain outside this contract. + +## Compatibility + +The uncommitted separate `EditableAttribute`/declaration design is superseded +before it becomes public. The current public `FormField` implementation and +parallel hardcoded Viewer field inventory must also be replaced. Existing +represented-item `ParameterForm` behavior remains separate and unchanged. + +## Verification + +- Compose editable `SceneStateField` entries and non-state + `__editable_attributes__` entries across the MRO into one ordered mapping. +- Verify durable subclass fields are not duplicated in + `__editable_attributes__` or the normalized result. +- Reject a `SceneStateField` with `update` and `editable=False`. +- Verify default mutation uses `setattr` and callbacks receive exactly + `(owner, value)` synchronously and atomically. +- Verify the initial non-state entries are `name` and `opacity`. +- Prove core declarations and resolution contain no UI, form, context, or + refresh metadata and import no graphics modules. +- Prove editability declarations and resolved mappings are absent from scene + serialization. +- Verify represented-item parameters continue through `ParameterForm`. + +## Dependencies + +- Depends on Accepted ADR 013 for stable scene-object types and durable scene + state. +- Respects ADR 014's restricted `draw`/`clear` operation surface. +- Context-specific normalized mapping changes are governed by Accepted ADR + 016. + +## Amendment + +Approved on 2026-11-08. This amendment supersedes both the earlier accepted +public `FormField`/item-target/refresh design and the first uncommitted +class-level design that separately redeclared durable editable attributes. +`SceneStateField` is now the single source for durable semantic editable state. diff --git a/initiatives/scene-viewer-visualisation/decisions/016-scene-form-field-bindings.md b/initiatives/scene-viewer-visualisation/decisions/016-scene-form-field-bindings.md new file mode 100644 index 0000000..4d67a8a --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/016-scene-form-field-bindings.md @@ -0,0 +1,121 @@ +# ADR 016: Contextual Editable-Attribute Overrides and Mutation + +## Status + +Accepted, amended on 2026-11-08. + +## Context + +ADR 015 makes `SceneStateField` and narrowly scoped +`__editable_attributes__` declarations the sources of one normalized editable +attribute mapping. A visualization context may still need to expose an +additional scene-object attribute, replace its data-side update callback, or +hide an otherwise editable attribute. This must operate on that normalized +mapping without reintroducing a second public field type or putting +presentation and rendering refresh instructions in core. + +## Options + +1. Let context plugins extend, replace, or remove entries in the resolved + class declaration mapping. +2. Let context plugins return public form-field or widget objects. +3. Add refresh callbacks or context protocols to core declarations. +4. Keep context-specific hardcoded field inventories in Viewer components. + +## Decision + +Choose option 1. + +Context plugins register graphics-free contributions under the exact key +`(context, stable SceneObject type, contribution ID)`. A contribution modifies +the normalized `attribute name -> optional update callback` mapping: + +- a new attribute with an optional callback appends; +- an existing attribute's callback is replaced while retaining its position; + and +- an explicit removal marker removes the attribute. + +The removal marker is distinct from `None`, because `None` means the attribute +uses ordinary `setattr`. + +Resolution starts with the base-to-derived class declarations from ADR 015 and +then applies applicable context contributions by stable scene-object MRO from +general to specific. At each MRO specificity, contributions are applied in +lexical contribution-ID order while preserving each contribution mapping's +insertion order. This makes the append order deterministic. Duplicate exact +registration keys are errors. Two contributions at the same specificity that +both edit or remove the same attribute are also errors; registration order +never silently resolves a conflict. + +Class declarations and plugin discovery remain graphics-free. Contributions +and their resolved mappings are runtime-only and are never serialized. + +Viewer introspects the final mapping and owns form construction. It determines +presentation from the current value, checks writability, and applies the +default assignment or synchronous data-side callback defined by ADR 015. +There is no public `FormField` object and the mapping contains no labels, +editors, arbitrary data, form metadata, or refresh instructions. + +Mutation is atomic from the form's perspective. If assignment or the callback +raises, the owner remains unchanged under ADR 015's callback contract, the +control is restored to the previous value, the original failure is reported, +and no view refresh occurs. After a successful mutation, Viewer exclusively +decides which render-data rebuild, redraw, and UI refresh operations are +required. Context plugins only filter, extend, or replace normalized attribute +names and callbacks. Core declarations contain no refresh callback, refresh +category, or context protocol. + +The initial scope is only stable `SceneObject` attributes in object settings. +Represented-item parameters continue to use the existing `ParameterForm` and +are not extended or overridden through this registry. + +## Consequences + +- Contexts customize the same authoritative attribute mapping instead of + maintaining parallel form schemas. +- Conflict handling is deterministic and independent of plugin load order. +- Core remains unaware of rendering and UI refresh policy. +- Viewer may refresh conservatively first and optimize only with measured + evidence. +- Arbitrary widgets, item parameters, dotted paths, asynchronous callbacks, + and plugin-provided refresh hooks remain outside the mechanism. + +## Compatibility + +The former `FormField`-based context registry, represented-item targets, and +field-level `draw`/`geometry` refresh modes were removed. Built-in object +settings migrated to class declarations; only genuinely contextual differences +remain plugin contributions. Existing `ParameterForm` behavior is preserved. + +## Verification + +- Compose class declarations and general-to-specific context contributions in + lexical contribution-ID and mapping-insertion order, preserving positions + for replacements and deterministically appending new attributes. +- Verify the explicit removal marker removes class-owned or inherited context + attributes while `None` selects ordinary `setattr`. +- Reject duplicate exact registrations and same-specificity attribute + conflicts with diagnostics naming context, scene-object type, and attribute. +- Verify two contexts may resolve different mappings for the same stable + scene-object type. +- Verify failed assignment/callback leaves the owner unchanged, restores the + control, and performs no render, redraw, or UI refresh. +- Verify successful mutation causes Viewer—not core metadata or context + plugins—to select conservative render rebuild, redraw, and UI refresh. +- Prove plugin discovery imports no graphics or UI modules. +- Prove contributions and resolved mappings are absent from serialization. +- Verify represented-item parameters remain on the existing `ParameterForm` + path. + +## Dependencies + +- Depends on Accepted ADR 015 for class-owned declarations and mutation. +- Reuses ADR 014's context/type registration principles without extending its + public `draw`/`clear` operation surface. + +## Amendment + +Approved on 2026-11-08. This amendment supersedes the earlier accepted flat +`FormField` binding contract, including item targets and field-level refresh +semantics. The implementation of that earlier design was replaced by the +implemented and verified amendment. diff --git a/initiatives/scene-viewer-visualisation/decisions/017-lazy-datastructure-attribute-tables.md b/initiatives/scene-viewer-visualisation/decisions/017-lazy-datastructure-attribute-tables.md new file mode 100644 index 0000000..e0f2a3e --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/017-lazy-datastructure-attribute-tables.md @@ -0,0 +1,106 @@ +# ADR 017: Lazy Datastructure Element-Attribute Tables + +## Status + +Accepted. + +## Context + +Viewer can inspect a selected scene object's presentation attributes, but it +does not provide a scalable view of attributes stored on Mesh or Graph +elements. Building one widget per value would be slow for large structures, +while copying all sparse element dictionaries would increase startup cost and +could invent columns that have no declared domain meaning. + +COMPAS datastructures already expose domain defaults such as +`default_vertex_attributes` and singular domain APIs for retrieving element +attributes. The initial table design can use those public contracts without a +new core abstraction. + +## Options + +1. Add Viewer-owned lazy table models for declared Mesh and Graph element + domains. +2. Materialize every element attribute into ordinary table widgets. +3. Add a generic tabular-inspection API to core. +4. Scan sparse per-element dictionaries to infer every observed column. + +## Recommendation + +Choose option 1. + +Viewer owns a lazy `QAbstractTableModel` for datastructure element attributes. +The initial supported types are Mesh and Graph. Domains are discovered from +their existing `default_*_attributes` mappings and corresponding singular +element APIs: Mesh vertex, edge, and face domains; Graph node and edge domains. +The default mapping's insertion order defines the initial column order. + +The model stores element identifiers and reads effective cell values lazily +through the singular getter. It does not build one component per cell or copy +the complete attribute table. Sparse undeclared attributes found only in local +element dictionaries are omitted; the table does not scan the datastructure to +invent columns. + +Viewer adds a tab only for a supported domain whose default-attribute mapping +declares at least one column. A declared domain with no elements may therefore +show a zero-row table with its declared columns. A domain with no declared +attribute columns is omitted. + +## Accepted amendment: opt-in sidebar placement + +Accepted on 2026-11-09 after direct use of the default sidebar. The +`DatastructureAttributes` component remains available to explicitly configured +custom sidebars, but it is not part of the built-in sidebar composition. The +table model and editing contracts remain unchanged. + +This is a Viewer feature. It requires no changes to Mesh, Graph, or core +datastructure APIs and does not make Qt a core dependency. + +## Consequences + +- Large Mesh and Graph attribute sets can be inspected without eagerly + constructing all cell widgets or values. +- The visible schema is stable and follows datastructure-declared defaults. +- Undeclared sparse attributes remain available through datastructure APIs but + are not exposed by this initial table. +- Additional datastructure types or domains require evidence and a later + amendment. + +## Compatibility + +The table is an opt-in Viewer sidebar surface. It does not change datastructure +serialization, element attribute semantics, object settings, or the existing +represented-item `ParameterForm`. + +## Verification + +- Discover the supported Mesh and Graph domains from default mappings and + singular APIs. +- Preserve default mapping insertion order in columns. +- Verify data is read lazily and no per-cell component collection is created. +- Omit sparse undeclared attributes without scanning all local dictionaries. +- Create tabs only for domains with declared attribute columns, including a + zero-row table when such a domain has no elements. +- Verify empty datastructures, large datastructures, and effective default + values. +- Verify the built-in sidebar omits the component and an explicitly configured + custom sidebar can still instantiate it. +- Prove importing Viewer plugins remains graphics-free. + +## Dependencies + +- Uses the Viewer-owned sidebar boundary from ADR 006. +- Independent of ADRs 015–016; object settings and element tables edit + different owners. +- Implementation must coordinate sidebar file ownership with ADRs 019–020 and + other Viewer UI work. + +## Decision + +Approved on 2026-11-08. Viewer owns lazy Mesh and Graph element-attribute table +models whose domains and columns come from declared defaults and existing +singular datastructure APIs. The rationale is to keep large tables scalable and +their schema explicit without copying all values, scanning sparse dictionaries, +adding per-cell components, or introducing a new core abstraction. Amended on +2026-11-09 to keep the component opt-in rather than adding it to the default +sidebar. diff --git a/initiatives/scene-viewer-visualisation/decisions/018-datastructure-attribute-editing.md b/initiatives/scene-viewer-visualisation/decisions/018-datastructure-attribute-editing.md new file mode 100644 index 0000000..a5f201b --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/018-datastructure-attribute-editing.md @@ -0,0 +1,93 @@ +# ADR 018: Datastructure Element-Attribute Editing + +## Status + +Accepted. + +## Context + +ADR 017 defines lazy Viewer tables for declared Mesh and Graph element +attributes. Editing needs a narrow value-type, mutation, selection, and refresh +contract. Without one, delegates could silently change types, bypass +datastructure semantics, or couple table selection to viewport object +selection. + +## Options + +1. Edit supported declared values through singular datastructure APIs and keep + table interaction local. +2. Write directly into internal element dictionaries. +3. Add batch editing, default-schema editing, undo, and viewport selection in + the first version. +4. Treat all values as editable text. + +## Recommendation + +Choose option 1. + +Editor choice follows the declared default value's exact supported type: + +- `bool`; +- `int`; +- `float`; and +- `str`. + +Other default types are displayed read-only. The table shows effective values +through the singular getter, including inherited defaults. A successful edit +uses the matching singular setter. Reset uses the singular unset operation so +the effective value falls back to its declared default rather than copying the +default into local storage. + +Table row/cell selection is local to the table. It does not mutate Viewer +object selection, viewport picking, or a future component-selection model. + +After a successful mutation, Viewer conservatively refreshes the affected +scene object's render data, redraw, and relevant UI. Failed validation or +mutation leaves the datastructure and displayed value unchanged and triggers +no refresh. + +The initial version does not edit default attribute definitions, scan or add +sparse undeclared attributes, batch-edit cells, add undo/redo transactions, or +link table selection to viewport selection. + +## Consequences + +- Editing preserves datastructure validation and default/local semantics. +- Unsupported values remain visible without unsafe coercion. +- Conservative refresh favors correctness before optimization. +- Bulk operations, history, and component selection remain separately + decidable features. + +## Compatibility + +No core API or serialized data format changes. Existing singular getters, +setters, and unset operations remain authoritative. + +## Verification + +- Select Boolean, integer, float, and text editors from default value types, + distinguishing `bool` from `int`. +- Display unsupported types read-only. +- Mutate through each singular setter and reset through each singular unset + operation. +- Display effective inherited defaults without inserting local values. +- Keep table selection independent of Viewer and viewport selection. +- Verify failed edits are atomic and successful edits invoke one conservative + Viewer refresh path. +- Verify no default editing, sparse scan, batch edit, undo, or viewport + component-selection behavior appears in the initial implementation. + +## Dependencies + +- Depends on Accepted ADR 017 for the lazy table model and declared columns. +- Uses Viewer refresh ownership established by ADRs 006 and 016 without + extending the scene-object editable-attribute mechanism. + +## Decision + +Approved on 2026-11-08. The initial editor supports only declared Boolean, +integer, float, and text values; mutations and resets use the existing singular +datastructure APIs, table selection remains local, and successful changes use +one conservative Viewer refresh path. The rationale is to preserve declared +types and default/local semantics without unsafe coercion, direct dictionary +writes, batch operations, undo, or viewport component-selection coupling. diff --git a/initiatives/scene-viewer-visualisation/decisions/019-configured-viewer-identity.md b/initiatives/scene-viewer-visualisation/decisions/019-configured-viewer-identity.md new file mode 100644 index 0000000..c343baa --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/019-configured-viewer-identity.md @@ -0,0 +1,74 @@ +# ADR 019: Configured Viewer Identity + +## Status + +Accepted. + +## Context + +Viewer configuration has a `WindowConfig.title`, but application identity and +startup window behavior are not consistently applied before Qt application +construction. Icon selection also needs a clear packaged-default and +custom-file contract. + +## Options + +1. Use startup-only `WindowConfig` fields as the single configured Viewer + identity. +2. Add separate application-name, display-name, and window-title fields. +3. Keep identity hardcoded and let callers mutate Qt objects after startup. + +## Recommendation + +Choose option 1. + +The existing `WindowConfig.title` supplies all three startup identity values: + +- Qt application name; +- Qt application display name; and +- main window title. + +`WindowConfig.icon` is either: + +- `None`, which selects the packaged Viewer icon; or +- an absolute filesystem path to a custom icon. + +Relative paths are invalid. Identity, icon, dimensions, and fullscreen are +startup-only configuration. Viewer validates and applies the configuration +before constructing `QApplication` and the main window. The existing +`fullscreen` field is honored during startup rather than remaining inert. + +This decision does not add a runtime identity mutation API. + +## Consequences + +- One title cannot diverge across application and window identity surfaces. +- Packaged applications get a default icon without configuring a path. +- Custom identity is deterministic but cannot be changed live. + +## Compatibility + +Existing title, width, height, and fullscreen values keep their startup +meaning. The optional icon is additive startup configuration. + +## Verification + +- Apply title to application name, display name, and window title before the + window is shown. +- Use the packaged icon for `None` and an existing absolute path for a custom + icon. +- Reject relative or invalid icon paths with a precise configuration path. +- Honor configured width, height, and fullscreen at startup. +- Verify no runtime identity mutation API is added. + +## Dependencies + +- Independent of scene, object-settings, and configuration-cleanup ADRs. + +## Decision + +Approved on 2026-11-08. `WindowConfig.title` is the single startup identity for +the Qt application and main window, while `WindowConfig.icon` selects either +the packaged icon or an existing absolute custom path. The rationale is to +make identity and startup window behavior deterministic without duplicate +names, post-construction mutation, or a separate runtime identity API. diff --git a/initiatives/scene-viewer-visualisation/decisions/020-viewer-config-lifecycle-and-audit.md b/initiatives/scene-viewer-visualisation/decisions/020-viewer-config-lifecycle-and-audit.md new file mode 100644 index 0000000..5cceefb --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/020-viewer-config-lifecycle-and-audit.md @@ -0,0 +1,116 @@ +# ADR 020: Viewer Configuration Lifecycle and Field Audit + +## Status + +Accepted. + +## Context + +Viewer uses nested dataclasses for configuration, but deserialization currently +performs limited structural migration rather than explicit validation. Several +fields are inert, duplicate transient runtime state, or retain residues of +earlier sidebar and display designs. The cleanup needs a complete disposition +without replacing the simple dataclass model with another framework. + +## Options + +1. Retain typed dataclasses, add explicit path-aware validation, and remove or + connect fields according to demonstrated ownership. +2. Replace configuration with Pydantic models. +3. Store arbitrary plugin dictionaries and validate them inside consumers. +4. Turn all configuration into a live reactive state store. + +## Recommendation + +Choose option 1. + +Retain the nested configuration dataclasses and add explicit `validate()` +behavior that reports the complete field path for every invalid value. Validate +after construction/deserialization and before Viewer creates `QApplication`. + +Separate startup configuration from transient state: + +- startup configuration includes window identity and geometry, appearance, + UI component visibility, renderer/camera defaults, and `vectorsize`; +- transient selection, hover, active tools, live view interaction, and other + session values remain outside serialized configuration. + +Apply this field audit for schema version 2: + +- connect `window.fullscreen` to startup behavior; +- connect `ui.statusbar.show` to status-bar visibility; +- remove `window.about`; +- remove obsolete sidebar residues `show_widgets` and `sceneform`; +- remove `renderer.opacity` because effective renderer opacity is derived from + render mode; +- remove the root `display` group and its duplicated scene-object defaults; +- remove root `unit` until a unit-aware workflow has an approved owner and + lifecycle; +- add `ortho` to the accepted renderer view values; and +- keep root `vectorsize` as an active render default. + +Unknown or invalid schema fields fail with their full path; migration must not +silently preserve removed fields as runtime attributes. Schema version 2 also +implements ADR 019's identity and icon contract. + +Typed Viewer subclasses may extend configuration with typed dataclass fields +and validation. Do not add untyped plugin dictionaries, automatic plugin +configuration merging, Pydantic, or a promise that configuration is reactive. + +Direct dataclass mutation is supported only while assembling configuration +before Viewer construction. Post-construction mutation has no reactive +guarantee, and replacing `viewer.config` is unsupported. Existing dotted-path +`ViewerState` access is transitional internal wiring, not a configuration or +extension target. + +## Consequences + +- Configuration remains simple Python data with explicit validation. +- Removed fields stop suggesting unsupported behavior. +- Startup and transient ownership become testable. +- Typed subclass extensions remain possible without a generic plugin schema. +- Schema version 2 is an intentional compatibility boundary. + +## Compatibility + +Serialized schema version 2 removes `about`, sidebar residues, renderer +`opacity`, the `display` group, and root `unit`. Loading schema 1 drops known +retired fields and preserves every retained value. Unknown schema-1 fields are +rejected. Schema 2 rejects retired fields when they are supplied explicitly, +rather than silently accepting or storing them. + +## Verification + +- Validate nested types, literals, ranges, icon paths, and unknown fields with + complete configuration paths. +- Apply configuration before `QApplication` and window construction. +- Verify fullscreen and status-bar fields affect startup UI. +- Verify every removed field is absent from schema-2 serialization and rejected + when explicitly supplied in schema 2. +- Verify schema-1 migration drops known retired fields, preserves retained + values, and rejects unknown fields. +- Verify renderer view accepts `ortho` and rejects other unknown modes. +- Verify `vectorsize` remains active. +- Verify transient state changes do not mutate serialized startup + configuration. +- Verify setup-time direct mutation is honored, post-construction mutation has + no reactive contract, replacing `viewer.config` is unsupported, and + dotted-path `ViewerState` access is not presented as an extension API. +- Verify a typed subclass can add and validate typed dataclass fields without + untyped plugin dictionaries. + +## Dependencies + +- Depends on Accepted ADR 019 for the identity fields that schema 2 validates + and applies at startup. +- Independent of ADRs 015–018, but sidebar implementation must coordinate file + ownership with ADRs 017–018. + +## Decision + +Approved on 2026-11-08. Viewer retains typed nested dataclasses, adds explicit +path-aware validation, separates startup configuration from transient state, +and applies the complete schema-version-2 field audit and migration contract. +The rationale is to keep configuration simple and truthful without Pydantic, +untyped plugin dictionaries, reactive-state promises, or silent preservation +of removed and unknown fields. diff --git a/initiatives/scene-viewer-visualisation/decisions/021-durable-annotation-ownership.md b/initiatives/scene-viewer-visualisation/decisions/021-durable-annotation-ownership.md new file mode 100644 index 0000000..4506809 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/021-durable-annotation-ownership.md @@ -0,0 +1,94 @@ +# ADR 021: Durable Annotation Ownership and Schema + +## Status + +Accepted. + +## Context + +Accepted ADR 005 separates durable world annotations from transient Viewer +overlays, but it does not assign the durable data types to a package. The +current `Tag` and `ArrowOverlay` types live in `compas_viewer`, so a scene that +references them cannot load without the visualization backend installed. +Core has no neutral text, arrow, or distance-annotation data types. + +The durable schema must express annotation intent without storing Viewer +resources, editor state, or rendering implementation details. + +## Options + +1. Define neutral annotation data in `compas.scene`; Viewer provides only the + rendering operations. +2. Keep serializable annotation data in `compas_viewer`. +3. Define annotation data in `compas.geometry`. + +## Recommendation + +Choose option 1. + +Add three backend-neutral data types to `compas.scene`: + +- `TextAnnotation` stores text, a local anchor, height, height mode, and + horizontal and vertical alignment; +- `ArrowAnnotation` stores local start and end anchors; and +- `DistanceDimension` stores two anchors governed by Accepted ADR 028, plus + unit, precision, and an optional label override. + +Keep the first schemas narrow. Color, opacity, visibility, hierarchy, and +transformation remain scene-object state. Font files, background rendering, +padding, screen offsets, arrowhead styles, snapping metadata, editor state, and +Viewer configuration do not enter the neutral data schema. + +Fixed annotation anchors use the annotation item's local coordinates. A +root-level fixed dimension initially stores `PointAnchor` values equal to +acquired world points. A fixed pair can derive its local-coordinate distance +directly; associative and mixed pairs require their `ComponentAnchor` +references to resolve and otherwise report unresolved state. Viewer derives +the displayed distance from resolved anchors after applying the owning scene +object's world transformation where applicable. + +Viewer registers ordinary rendering operations for these stable core types. +Core loading, inspection, transformation, and serialization never import Qt, +OpenGL, font libraries, or `compas_viewer`. + +## Consequences + +- Durable scene intent loads without a visualization backend. +- One canonical data model serves Viewer and future visualization contexts. +- The initial annotation schema deliberately omits existing Viewer-specific + typography and arrow styling. +- Adding later semantic fields requires evidence and a separate approved + change rather than copying renderer options into core. + +## Compatibility + +ADR 023 governs removal of the current Viewer-owned `Tag` and `ArrowOverlay` +paths. This ADR defines their proposed canonical replacements but does not add +a compatibility loader. + +## Verification + +- Serialize and load every annotation type without `compas_viewer` installed. +- Verify local anchors, transformations, hierarchy, and independently bound + item identity. +- Verify local distance derivation and transformed-world display distance. +- Verify core plugin discovery imports no Viewer, Qt, OpenGL, or font modules. +- Verify Viewer rendering uses registered scene operations rather than core + renderer dependencies. + +## Dependencies + +- Refines Accepted ADR 005. +- Implements Accepted ADR 028's fixed and associative anchor model. +- Respects Accepted ADRs 010, 013, and 014 for item references, stable scene + objects, and context-keyed rendering operations. + +## Decision + +Approved on 2026-11-08. Durable `TextAnnotation`, `ArrowAnnotation`, and +`DistanceDimension` data belong to `compas.scene`; Viewer provides rendering +operations only. The schemas remain narrow and backend-neutral, with +presentation, hierarchy, and transformation owned by scene objects. The +rationale is that durable scene intent must load and serialize without a +visualization backend or renderer-specific resources. + diff --git a/initiatives/scene-viewer-visualisation/decisions/022-distance-dimension-units.md b/initiatives/scene-viewer-visualisation/decisions/022-distance-dimension-units.md new file mode 100644 index 0000000..5a8a4bc --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/022-distance-dimension-units.md @@ -0,0 +1,98 @@ +# ADR 022: Distance-Dimension Unit Semantics + +## Status + +Accepted. + +## Context + +Accepted ADR 005 requires a distance dimension to store a unit and precision. +The user also requires Viewer-level unit, precision, and tolerance settings +with UI exposure. The framework currently has no approved scene-unit owner or +conversion service, and Accepted ADR 020 deliberately removed the old Viewer +root `unit` field until a coordinated unit-aware workflow has an approved owner +and lifecycle. + +Treating a unit label as an implicit conversion request would therefore hide +an unknown source unit and produce unverifiable values. + +## Options + +1. Snapshot the active Viewer measurement unit and precision when a persistent + dimension is created; the unit declares the coordinates' unit and performs + no conversion. +2. Require unit and precision explicitly for every persistent dimension, + independent of Viewer settings. +3. Add separate source and display units with conversion infrastructure in + this phase. + +## Recommendation + +Choose option 1, dependent on approval of ADR 027. + +Persistent dimensions snapshot unit and precision at creation so their durable +labels do not change when Viewer preferences change later. Explicit +construction arguments may override the current settings. Transient +inspections use the current Viewer unit and precision without creating a +durable snapshot. + +`DistanceDimension.unit` is `str | None`. For example, `unit="mm"` declares +that the stored coordinate distance is already expressed in millimetres. It +appends `mm` to the formatted value but never rescales coordinates. + +`precision` is a non-negative number of decimal places. The derived label uses +fixed-point formatting and separates a non-empty unit from the value with one +space. A non-`None` explicit label is displayed verbatim instead of the +derived value. + +Tolerance remains Viewer measurement behavior governed by ADR 027; it is not +stored on every dimension. Do not add a supported-unit registry, spelling +normalization, localization, source-unit inference, or conversion factor in +this phase. Actual conversion depends on a separate framework-wide unit +decision. + +## Consequences + +- Formatting is deterministic and honest about the available information. +- Callers and Viewer remain responsible for supplying coordinates in the + declared unit. +- The unit string is descriptive rather than computational. +- Durable dimensions remain stable when Viewer measurement preferences change. +- Later conversion infrastructure may extend construction explicitly, but it + must not silently change existing serialized meaning. + +## Compatibility + +There is no existing distance-dimension payload. This decision establishes the +initial serialized semantics without reviving the removed Viewer root unit. + +## Verification + +- Derive and format distances with no unit and with an explicit unit. +- Verify zero and multiple precision values. +- Reject negative precision and invalid unit values precisely. +- Verify an explicit label bypasses derived numeric and unit formatting. +- Verify serialization preserves unit, precision, and label without adding a + conversion factor or source-unit field. +- Verify persistent creation snapshots Viewer settings while transient + inspection reads their current values. +- Verify later Viewer-setting changes do not rewrite existing dimensions. + +## Dependencies + +- Depends on proposed ADR 021 for `DistanceDimension` ownership and schema. +- Depends on proposed ADR 027 for Viewer measurement-setting ownership. +- Refines Accepted ADR 005. +- Respects Accepted ADR 020's removal of the unowned Viewer root unit. + +## Decision + +Approved on 2026-11-08. Persistent dimensions snapshot the active Viewer unit +and precision at creation, while transient inspections use their current +values. The unit declares the coordinates' existing unit and formats a suffix; +it never performs implicit conversion. Durable dimensions retain their +snapshot when Viewer preferences change, and tolerance is not duplicated on +each dimension. The rationale is deterministic, honest formatting without an +unowned source unit or hidden conversion. + + diff --git a/initiatives/scene-viewer-visualisation/decisions/023-annotation-clean-break.md b/initiatives/scene-viewer-visualisation/decisions/023-annotation-clean-break.md new file mode 100644 index 0000000..93a9fdc --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/023-annotation-clean-break.md @@ -0,0 +1,78 @@ +# ADR 023: Clean Break for Legacy Viewer Annotations + +## Status + +Accepted. + +## Context + +The current Viewer-owned `Tag` is a durable camera-facing text item. +`TextAnnotation` is only an alias, so serialized data still records the `Tag` +dtype. `ArrowOverlay` is also durable, world-anchored, transformable, and +serialized despite its transient-sounding name. No committed legacy JSON +fixtures exist, but current tests, documentation, and examples use both names. + +Keeping aliases or legacy decoders would leave multiple public paths and retain +the misleading use of “overlay” for durable scene content. + +## Options + +1. Remove both legacy public types and their decoding paths when the canonical + annotation types land. +2. Keep the old types only as aliases and serialized-data decoders. +3. Retain the old names indefinitely and add new types alongside them. + +## Recommendation + +Choose option 1. + +Remove `Tag`, `ArrowOverlay`, and their old serialized dtype paths. Update all +package tests, examples, and documentation to the canonical types approved by +ADR 021. Do not add aliases, deprecation shims, dtype remapping, or a legacy +scene loader. + +Old payloads containing `compas_viewer.scene/Tag` or +`compas_viewer.scene/ArrowOverlay` are unsupported after the change and fail +through the normal unknown-type loading boundary. Release notes and migration +documentation state the replacement construction paths explicitly. + +Reserve “annotation” for durable world-anchored content and “overlay” for the +transient, non-serialized Viewer layer. + +## Consequences + +- The public vocabulary has one clear path per concept. +- Core and Viewer carry no permanent compatibility layer for experimental + annotation types. +- Existing source imports and serialized payloads using the old types break + intentionally. +- Implementation can remove obsolete concrete renderer branches instead of + preserving parallel behavior. + +## Compatibility + +This is an intentional breaking change. The current initiative branches and +draft pull requests are the migration boundary. No release or main branch is +modified without the initiative's later explicit merge approval. + +## Verification + +- Verify old names are absent from public exports, examples, and documentation. +- Verify no legacy alias, dtype remapping, or decoder remains. +- Verify canonical annotations cover the approved visible behavior. +- Verify old serialized dtype strings fail clearly rather than being silently + reinterpreted. + +## Dependencies + +- Depends on proposed ADR 021 for the canonical replacement ownership and + names before implementation can begin. +- Refines the migration requirement of Accepted ADR 005. + +## Decision + +Approved on 2026-11-08. The annotation migration is a clean break: obsolete +public names and serialized-data paths are removed rather than preserved as +aliases or compatibility decoders. The rationale is to keep the system clean, +simple, efficient, and transparent, with one canonical path per concept. + diff --git a/initiatives/scene-viewer-visualisation/decisions/024-measurement-outcomes-and-persistence.md b/initiatives/scene-viewer-visualisation/decisions/024-measurement-outcomes-and-persistence.md new file mode 100644 index 0000000..0933d1d --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/024-measurement-outcomes-and-persistence.md @@ -0,0 +1,80 @@ +# ADR 024: Measurement Outcomes and Persistence + +## Status + +Accepted. + +## Context + +A measurement interaction may serve two different intentions. A user may want +to inspect a value temporarily while working, or may want to create a durable +dimension annotation that remains part of the scene. Treating every completed +measurement as persistent would mutate the scene during ordinary inspection; +treating every result as transient would prevent intentional documentation. + +The two workflows may share point acquisition and preview rendering, but their +results need different ownership and persistence. + +## Options + +1. Provide distinct transient inspection and persistent dimension-annotation + modes that may share acquisition and preview infrastructure. +2. Make every completed measurement create a durable scene item. +3. Keep every measurement transient and require manual dimension construction. + +## Recommendation + +Choose option 1. + +Transient inspection derives and displays the live measurement in Viewer tool +state. It does not add, remove, select, or serialize scene content. Completion +may retain the result only for the lifetime defined by the active inspection +tool; cancellation clears it. + +Persistent dimension-annotation mode may use the same anchor acquisition and +preview path. Completing it creates exactly one durable `DistanceDimension` in +the scene using the explicit fixed or associative anchors governed by Accepted +ADR 028. Cancellation creates nothing. The exact acquisition, snapping, +repetition, activation, and post-completion lifecycles remain governed by +proposed ADR 026. + +The mode is explicit before completion. Viewer never infers persistence from +the number of acquired points or silently promotes a transient result into a +scene item. + +## Consequences + +- Ordinary measurement does not pollute or mutate the scene. +- Users can intentionally preserve dimensions when they need documentation. +- Shared acquisition and preview code does not imply shared result ownership. +- Session history for transient inspections remains outside Scene and outside + the Viewer transform-transaction stack. + +## Compatibility + +There is no existing measurement workflow. This decision establishes two +clear public outcomes without preserving an earlier behavior. + +## Verification + +- Verify transient inspection never mutates scene objects, hierarchy, + selection, serialization, or transform history. +- Verify persistent completion creates exactly one durable dimension. +- Verify cancellation in either mode creates no durable content. +- Verify switching modes clears incompatible transient result state rather + than reinterpreting it. + +## Dependencies + +- Refines Accepted ADR 005. +- Persistent results depend on proposed ADRs 021 and 022. +- Persistent anchor semantics are governed by Accepted ADR 028. +- Interaction details depend on proposed ADR 026. + +## Decision + +Approved on 2026-11-08. Viewer provides separate transient inspection and +persistent dimension-annotation outcomes. They may share acquisition and +preview infrastructure, but transient measurements never mutate or serialize +Scene, while persistent completion creates a durable `DistanceDimension`. + diff --git a/initiatives/scene-viewer-visualisation/decisions/025-scale-and-legend-overlays.md b/initiatives/scene-viewer-visualisation/decisions/025-scale-and-legend-overlays.md new file mode 100644 index 0000000..cf0a4ff --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/025-scale-and-legend-overlays.md @@ -0,0 +1,102 @@ +# ADR 025: Scale and Legend Overlay Contracts + +## Status + +Accepted. + +## Context + +Accepted ADR 005 assigns scale indicators and legends to a transient, +non-serialized Viewer overlay layer, but it does not define the meaning of the +scale or the initial legend content model. The first contract should be useful +without introducing a colormap framework or a general overlay registry. + +## Options + +1. Add a camera-target scale bar and an ordered categorical legend. +2. Limit scale display to orthographic view and add continuous numeric legends. +3. Add one generalized overlay and legend schema for every future use. + +## Recommendation + +Choose option 1. + +Viewer owns one ordered overlay collection exposed through +`viewer.add_overlay()` and `viewer.remove_overlay()`. It accepts only the +approved concrete overlay types; it is not a plugin registry. + +`ScaleBarOverlay` represents world distance at the camera-target plane. It is +globally exact in orthographic projection and explicitly local to that depth in +perspective projection. It selects a readable `1–2–5 × 10ⁿ` bar length near a +target pixel width. + +`LegendOverlay` stores an optional title and ordered categorical +`(label, color)` entries. Continuous ranges, normalization, interpolation, +colormaps, and out-of-range behavior are deferred. + +Both overlay types are Viewer-owned, screen-space, unpicked, and absent from +scene serialization. + +## Implementation note: one widget overlay canvas + +Recorded on 2026-11-09 after direct use of the measurement preview exposed +missing transient graphics and an intermittent `QPainter` failure on macOS. + +Viewer renders scale, legend, and measurement feedback on one transparent, +mouse-transparent `QWidget` canvas stacked above the OpenGL renderer. The +renderer remains a pure OpenGL surface. `QPainter` is created, used, and ended +only during the overlay widget's ordinary `paintEvent`. A completed renderer +frame and a direct change to overlay or measurement state both schedule a +canvas repaint. + +The canvas remains Viewer-owned, screen-space, unpicked, and absent from scene +serialization. This mechanism implements the already approved overlay +ownership and lifecycle; it does not introduce a general widget, snapping, or +plugin framework. + +## Consequences + +- The scale bar has precise, testable meaning in both projection modes. +- Perspective display states its depth-dependent limitation rather than + implying a global scale. +- Categorical legends cover a concrete initial need without speculative scalar + normalization behavior. +- One narrow ordered layer replaces concrete main-loop checks without becoming + a framework-wide extension registry. +- One ordinary widget paint lifecycle keeps transient UI painting separate + from the OpenGL renderer and its context lifecycle. + +## Compatibility + +These are new transient Viewer APIs. They do not preserve the obsolete durable +`ArrowOverlay` behavior removed by ADR 023. + +## Verification + +- Verify overlay insertion order, removal, resize behavior, and serialization + exclusion. +- Verify orthographic scale and perspective target-depth scale, including the + `1–2–5 × 10ⁿ` choice. +- Verify categorical legend order, title, and colors. +- Verify overlays do not participate in scene selection or instance picking. +- Verify the canvas is transparent to pointer input, is stacked above the + renderer, and repaints after frame swaps and direct transient-state changes. +- Verify `QPainter` ownership begins and ends inside the canvas `paintEvent`. + +## Dependencies + +- Refines Accepted ADR 005. +- Uses Accepted ADR 006 for the public Viewer facade. +- Respects Accepted ADR 023's annotation/overlay vocabulary boundary. + +## Decision + +Approved on 2026-11-08. Viewer owns one ordered, concrete overlay layer with +public add/remove operations. The initial `ScaleBarOverlay` reports world scale +at the camera-target plane using readable `1–2–5 × 10ⁿ` lengths, with its +perspective depth limitation explicit. The initial `LegendOverlay` contains an +optional title and ordered categorical label/color entries. Both remain +screen-space, unpicked, and absent from Scene serialization. The rationale is a +small useful contract without a general overlay registry, continuous-colormap +semantics, or misleading global perspective scale. + diff --git a/initiatives/scene-viewer-visualisation/decisions/026-measurement-interaction-and-acquisition.md b/initiatives/scene-viewer-visualisation/decisions/026-measurement-interaction-and-acquisition.md new file mode 100644 index 0000000..aedce74 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/026-measurement-interaction-and-acquisition.md @@ -0,0 +1,204 @@ +# ADR 026: Measurement Interaction and Acquisition + +## Status + +Accepted. + +## Context + +Accepted ADRs 005, 024, and 028 establish transient inspection, persistent +dimension outcomes, and fixed/associative anchor modes. Viewer has no +active-tool lifecycle or approved snapping path that turns pointer input into +an accurate world point and, when requested, a supported component reference. + +## Options + +1. Add one narrow snapping query used by inspection, Fixed dimension, and + Associative dimension acquisition, with an explicit one-shot tool lifecycle. +2. Read rendered depth only and never expose associative dimensions. +3. Add a generalized snapping and sub-object editing framework before the + first measurement tool. +4. Support only programmatic world-point input in the initial version. + +## Recommendation + +Choose option 1. + +### Snap result + +One narrow snapping query returns a `SnapResult` containing: + +- the resolved world point; +- the stable scene-object GUID; +- the snap kind; +- an optional stable component reference; and +- an explicit association error when a visible discrete component cannot be + represented by a stable reference. + +Interactive acquisition initially produces only discrete point kinds: + +1. a Point object; +2. a Mesh vertex; or +3. a Graph node. + +Snapping uses an 18-logical-pixel screen-space radius so its acquisition +footprint remains usable across zoom levels. The nearest eligible discrete +point wins. + +Fixed mode copies the resolved world point into a `PointAnchor`. + +Associative mode accepts the same displayed point, vertex, and node targets and +stores their stable component references. The two modes differ only in +persistence. Lines, edges, faces, and surfaces do not produce interactive +candidates until their eligible geometry has an explicit highlight overlay. + +### Tool lifecycle + +An explicit measurement mode activates one tool and cancels any previously +active tool. Left-button input reaches the active tool before ordinary +selection handling. The first valid click queries the approved snap targets. +Pointer movement over a valid snap updates a transient preview. The second +valid click completes the selected outcome: + +- inspection mode displays a transient result without scene mutation; or +- Fixed dimension mode creates `PointAnchor` values from the snapped points; or +- Associative dimension mode creates `ComponentAnchor` values and accepts only + snap results with supported component references. + +Completing either dimension mode creates one root-level durable +`DistanceDimension`, selects it, clears preview state, and deactivates. The +data model permits mixed anchors; the UI makes each acquired anchor's mode +explicit when constructing a mixed pair. + +Escape or explicit cancellation clears preview and result state and creates +nothing. A background or unsupported snap provides no anchor. Associative mode +never falls back to a fixed point. There is no construction-plane fallback, +general sub-object editing, repeating mode, or dimension editing in this phase. +Camera navigation remains available where its input does not conflict with the +active tool. Transient inspection and persistent dimension tools are both +one-shot in the first version: the second valid anchor completes the operation +and deactivates the tool. + +## Accepted amendment: visible discrete point acquisition + +Accepted on 2026-11-09 after direct use showed that a distance label alone did +not communicate which object components were available, which result a click +would accept, or whether the first anchor had been retained. + +While a measurement tool is active, hovering one object displays every +projected discrete point snap provided by that object: + +- the point of a Point object; +- the vertices of a Mesh; and +- the nodes of a Graph. + +The palette follows the hovered object and disappears when the pointer leaves +it. Guidance points are larger, bright hollow squares; the winner and retained +anchors are distinct filled squares. Palette points are guidance and are not +independently occlusion-tested. Only the distinct highlighted winner within +the existing screen-radius and depth acceptance rules is click-eligible. + +No invisible candidate is eligible. Standalone Lines, Mesh and Graph edges, +faces, and surfaces do not produce candidates. Later support must first define +and implement a visible candidate overlay for the corresponding segment, +region, or surface. + +Winner visibility searches a small instance-depth footprint around the +projected point. Only pixels belonging to the hovered object and matching the +candidate depth within the existing precision epsilon qualify. This avoids a +steeply tilted Mesh edge overwriting the single center sample while neither +loosening the global epsilon nor admitting background, another object, or a +fully occluded component. + +After the first winner is accepted, that anchor remains visible while the +palette follows the next hovered object. A missed point or background click +creates no anchor. Fixed mode has no implicit construction-plane or camera-plane +fallback because a background screen position does not define a unique world +point. + +Transient measurement graphics use the single Viewer overlay canvas recorded +in ADR 025's implementation note. Persistent dimension visibility follows ADR +030. These corrections do not add a general snapping or widget framework. + +## Consequences + +- Measurement accuracy and association follow the explicitly supported snap + targets; unsupported targets fail visibly. +- Fixed and associative acquisition share one result contract without + conflating a snapped coordinate with a durable association. +- Input priority and background behavior are deterministic. +- Both outcomes share acquisition and preview without sharing persistence. +- A narrow one-shot lifecycle avoids a general tool framework promise. +- Hover guidance makes the available discrete anchors, accepted winner, and + retained first anchor visible without changing snap eligibility. + +## Compatibility + +This is a new Viewer interaction. It does not change ordinary selection or +camera input when no measurement tool is active. + +## Verification + +- Verify activation, previous-tool cancellation, input priority, first anchor, + preview, second anchor, and cleanup. +- Verify background clicks and pointer motion over background do not create or + update anchors. +- Verify the 18-logical-pixel screen-space radius, nearest-candidate choice, and + every accepted `SnapResult` field. +- Verify hovering a Point, Mesh, or Graph shows all projected discrete point + snaps for that one object and leaving it clears the palette. +- Verify palette points are guidance only, the distinct depth-qualified winner + is the only click-eligible result, and the first anchor remains visible while + the palette follows the next object. +- Verify guidance points are bright hollow squares and the winner and retained + anchors are distinct filled squares. +- Verify point-footprint visibility accepts a visible receding vertex while + rejecting background pixels, another object's pixels, depth-mismatched + same-object pixels, and fully occluded vertices. +- Verify Lines, Mesh and Graph edges, faces, and surfaces do not produce + interactive candidates. +- Verify Fixed mode stores an exact displayed point, vertex, or node coordinate + in a `PointAnchor`. +- Verify Associative mode accepts the same target set and stores stable + component references without fallback. +- Verify opposite vertices of the 4 × 3 example resolve to a distance of 5. +- Verify transient completion follows ADR 024 without scene mutation. +- Verify fixed, associative, and any exposed mixed acquisition follow ADR 028, + including no silent fallback. +- Verify persistent completion creates and selects exactly one root-level + dimension and uses ADR 030's always-visible pass. +- Verify Escape and explicit cancellation create nothing in both modes. + +## Dependencies + +- Refines Accepted ADRs 005 and 024. +- Must implement Accepted ADR 028 anchor modes and unresolved behavior. +- Persistent results implement Accepted ADRs 021 and 022. +- Measurement labels and tolerance context implement Accepted ADR 027. +- Uses Accepted ADRs 003, 004, and 006 for selection, refresh/history + boundaries, and the public Viewer facade. + +## Decision + +Approved on 2026-11-08. One screen-space snapping query returns a world point, +scene-object GUID, snap kind, optional stable component reference, and explicit +association error for an unstable discrete component reference. Interactive +acquisition is restricted to Point objects, Mesh vertices, and Graph nodes with +visible guides. Fixed mode stores their resolved coordinates; Associative mode +stores their stable component references without fallback. +Active tools receive left-click input before selection, ignore background, +preview on pointer movement, cancel on Escape, retain non-conflicting camera +navigation, and complete as one-shot transient or persistent operations. The +rationale is precise, efficient initial snapping without a general snapping or +sub-object editing framework. Amended on 2026-11-09 to expose projected +Point/Mesh-vertex/Graph-node guidance for the hovered object, keep only the +distinct depth-qualified winner click-eligible, retain the first anchor while +the palette follows the next object, and keep transient graphics visible over +scene geometry. Refined through direct use on 2026-11-09 with larger bright +square markers, an 18-logical-pixel radius, same-object point-footprint +visibility, removal of every invisible line, edge, face, and surface candidate, +and ADR 030's always-visible final pass for persistent dimensions. The rationale +is direct, reliable, unambiguous feedback without loosening occlusion rules. +Continuous and regional targets can return only after their highlight overlays +are defined. + diff --git a/initiatives/scene-viewer-visualisation/decisions/027-viewer-measurement-settings.md b/initiatives/scene-viewer-visualisation/decisions/027-viewer-measurement-settings.md new file mode 100644 index 0000000..3c08323 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/027-viewer-measurement-settings.md @@ -0,0 +1,110 @@ +# ADR 027: Viewer Measurement Settings and UI + +## Status + +Accepted. + +## Context + +Unit, precision, and tolerance are important Viewer measurement information +and presentation settings and must be visible through the UI. Accepted ADR 020 +removed the old unowned root `unit` field and treats direct configuration +mutation as setup-only, so reintroducing editable values requires explicit +ownership, lifecycle, and mutation semantics. + +COMPAS global tolerance is process-wide numerical infrastructure. A Viewer +control must not silently mutate it or imply that display preferences change +geometry algorithm tolerances. + +## Options + +1. Add Viewer-owned unit and precision presentation defaults and show the + active COMPAS tolerance context read-only in one dedicated UI panel. +2. Add an explicit, clearly labeled operation for changing process-wide COMPAS + tolerance from Viewer. +3. Copy global tolerance into an independent editable Viewer field. +4. Keep all three values transient and omit them from Viewer configuration. + +## Recommendation + +Choose option 1. + +Add one typed `measurement` group to Viewer configuration: + +- `unit: str | None` declares the coordinate unit used for measurement labels; +- `precision: int` controls displayed decimal places; and +- tolerance information reports the active numerical tolerance context used by + COMPAS computations; it is not a private Viewer substitute. + +Expose the values through one **Units and Measurement** sidebar tab. Unit and +precision are presentation settings used by transient labels and snapshot into +persistent dimensions according to ADR 022. The first version shows tolerance +read-only and identifies its owner. Whether the same panel may +edit process-wide tolerance is outside this decision; it must never happen as a +side effect of editing Viewer presentation. + +An optional Settings-menu action may focus the same **Units and Measurement** +tab. It does not create a second settings surface or duplicate state. + +Unit, precision, and displayed tolerance are informational or presentational; +they are not sources of geometric correctness. Snap resolution and component +association follow ADRs 026 and 028. The UI does not reinterpret precision as +a geometric tolerance or silently mutate `compas.tolerance.TOL`. + +Persistent dimensions snapshot unit and precision according to ADR 022. +Transient inspection reads the current settings. Tolerance remains referenced +numerical context rather than being copied into every durable dimension or +duplicated as independent Viewer state. + +## Consequences + +- Measurement presentation and numerical tolerance context are discoverable. +- Runtime changes are explicit and validated instead of depending on arbitrary + dataclass mutation. +- Viewer presentation remains distinct from computational geometry tolerance. +- A later framework-wide unit-conversion design may extend these settings but + cannot silently reinterpret the initial declaration-only unit. + +## Compatibility + +This is a new schema field with an explicit owner. It does not restore the old +root `unit` field or weaken schema-2 rejection of that retired path. Its schema +version and migration must be coordinated with the next approved Viewer +configuration version. + +## Verification + +- Validate unit and precision with complete configuration paths and show the + active tolerance source accurately. +- Verify setup serialization, schema migration, explicit runtime updates, and + UI synchronization. +- Verify transient inspection responds to current settings. +- Verify persistent dimensions retain snapshot unit and precision after later + setting changes. +- Verify ordinary Viewer setting changes never mutate COMPAS global tolerance. +- If tolerance editing is later approved, verify it is explicit, process-wide, + and cannot be confused with Viewer-only state. +- Verify the measurement panel does not configure snapping or promise unit + conversion. + +## Dependencies + +- Refines Accepted ADRs 005 and 022. +- Amends the scoped configuration lifecycle of Accepted ADR 020 without making + general Viewer configuration reactive. +- Coordinates with proposed ADR 026 measurement interaction. +- Respects Accepted ADR 028: presentation settings do not determine whether an + anchor is fixed, associative, resolved, or geometrically correct. + +## Decision + +Approved on 2026-11-08. Viewer adds a nested measurement configuration group +for editable coordinate-unit declaration and display precision, exposed through +one **Units and Measurement** sidebar tab. The same tab shows the active global +COMPAS tolerance read-only with its process-wide ownership clear; Viewer never +silently mutates it. Measurement correctness comes from the approved snapping +path rather than unit, precision, or displayed tolerance. An optional Settings +menu action may focus the tab but does not duplicate it. The rationale is one +discoverable presentation surface without restoring the obsolete root unit or +creating a misleading Viewer-local geometry tolerance. + diff --git a/initiatives/scene-viewer-visualisation/decisions/028-dimension-anchor-modes.md b/initiatives/scene-viewer-visualisation/decisions/028-dimension-anchor-modes.md new file mode 100644 index 0000000..20d87e6 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/028-dimension-anchor-modes.md @@ -0,0 +1,101 @@ +# ADR 028: Fixed and Associative Dimension Anchors + +## Status + +Accepted. + +## Context + +Persistent dimensions may document either a position captured at creation or a +relationship to a component that should move as the referenced data changes. +Using only stored points makes every dimension stale after component edits. +Using only component references prevents intentionally fixed dimensions and +cannot represent every acquired location. + +Separate dimension classes would duplicate formatting, rendering, +serialization, and editing behavior even though only anchor resolution differs. + +## Options + +1. Use one `DistanceDimension` whose two anchors are independently either a + fixed `PointAnchor` or an associative `ComponentAnchor`. +2. Create separate fixed and associative dimension classes. +3. Store only points and update them opportunistically after component edits. +4. Store only component references and reject unassociated points. + +## Recommendation + +Choose option 1. + +`DistanceDimension` stores two values of one anchor union: + +- `PointAnchor` stores a fixed point captured at creation; and +- `ComponentAnchor` stores an explicit reference to a supported component and + resolves its current point when the dimension is evaluated. + +The data model permits two fixed anchors, two associative anchors, or one of +each. It does not infer an anchor kind from serialized fields. + +Viewer exposes explicit **Fixed** and **Associative** dimension modes. Both use +the approved snapping path: + +- Fixed mode snaps for accurate acquisition and stores the resulting point in + a `PointAnchor`. +- Associative mode snaps to a supported component and stores a + `ComponentAnchor`. + +Viewer never silently falls back from associative to fixed. If a snap result +cannot produce a supported component reference, associative acquisition does +not accept that anchor and reports the reason through tool state. + +Removing or invalidating a referenced component makes its +`ComponentAnchor` explicitly unresolved. The dimension retains the reference +and reports unresolved state; it never displays a cached point as if the +association were still valid. Rebinding or repairing the reference requires an +explicit later operation. + +The exact supported component selectors and snap targets remain part of +proposed ADR 026. This ADR fixes anchor semantics and failure behavior without +inventing a general component-resolution registry. + +## Consequences + +- One dimension type covers fixed, associative, and mixed use cases. +- Persistence intent is explicit at acquisition and in serialized data. +- Fixed measurements remain stable after later model edits. +- Associative measurements follow supported components and fail visibly when + their references cannot resolve. +- Snapping is required for both UI modes, but snapping does not imply + association unless Associative mode is active. + +## Compatibility + +There is no existing `DistanceDimension` payload. This establishes the initial +anchor schema without a legacy representation. + +## Verification + +- Serialize and evaluate fixed, associative, and mixed anchor pairs. +- Verify Fixed mode stores the snapped point and does not retain a component + reference. +- Verify Associative mode stores the component reference and follows supported + component changes. +- Verify associative acquisition never falls back silently to `PointAnchor`. +- Verify removed or invalid components produce explicit unresolved state and + never reuse a stale cached coordinate. +- Verify unresolved state survives serialization and reload. + +## Dependencies + +- Refines Accepted ADRs 005 and 024. +- Depends on proposed ADR 021 for canonical `DistanceDimension` ownership. +- Constrains proposed ADR 026 acquisition and snapping behavior. + +## Decision + +Approved on 2026-11-08. One `DistanceDimension` supports fixed +`PointAnchor` and associative `ComponentAnchor` values independently at both +ends. Viewer exposes explicit Fixed and Associative modes, uses snapping in +both, never silently falls back, and reports removed component references as +unresolved rather than displaying stale coordinates. + diff --git a/initiatives/scene-viewer-visualisation/decisions/029-persistent-annotation-collection-and-ui.md b/initiatives/scene-viewer-visualisation/decisions/029-persistent-annotation-collection-and-ui.md new file mode 100644 index 0000000..01e5a20 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/029-persistent-annotation-collection-and-ui.md @@ -0,0 +1,111 @@ +# ADR 029: Persistent Annotation Collection and UI + +## Status + +Accepted. + +## Context + +Persistent annotations are currently represented as ordinary root-level scene +objects. This makes them appear in the spatial scene tree and gives them the +same parent/child and transformation semantics as geometry, even though a +dimension instead references fixed world points or components of spatial scene +objects. + +Persistence, spatial hierarchy, rendering, and user-interface placement are +independent concerns. An annotation can remain durable scene/session data +without becoming a transformable child in the ordinary object hierarchy. + +## Options + +1. Add one ordered, scene-scoped annotation collection outside the spatial + hierarchy and expose it through a separate flat Annotations UI. +2. Add a reserved Annotations group inside the ordinary hierarchy and hide its + special behavior behind UI filtering. +3. Move annotations to Session rather than Scene. +4. Keep annotations as ordinary root-level scene objects. + +## Recommendation + +Choose option 1. + +Core Scene owns an ordered persistent annotation collection separate from its +spatial object tree. Annotation data remains independently serializable and is +referenced by stable identity; Scene records placement, ordering, and +presentation state without embedding independently owned data. + +Semantic annotation data and presentation remain separate. A +`DistanceDimension` continues to own anchors, unit, precision, and label. Its +collection entry owns durable visibility and a narrow dimension style. The +initial style contains only color, line width, text size, arrow size, and label +offset. It is not a generalized styling or theme framework. + +Collection entries have no parent, child, or inherited transformation. Fixed +dimension anchors are world-coordinate points. Associative anchors resolve +against the referenced scene objects and their world transformations. Ordinary +object transform, reparent, and hierarchy operations do not apply to +annotations. + +Viewer presents the collection in a separate flat **Annotations** UI rather +than mixing it into the Scene tree. Initial operations are visibility, +selection, naming, removal, and editing the narrow supported style. Annotation +selection must not imply that the annotation can be transformed like a spatial +object. + +Session does not own the collection. A future Session may aggregate the Scene, +its independently serialized data, settings, and history, but dimensions that +reference scene-object GUIDs remain scene-scoped. + +## Consequences + +- Spatial hierarchy again represents only transformable spatial composition. +- Persistent dimensions remain scene-scoped and serializable without living + inside the ordinary tree. +- Viewer gains a clear location for annotation-specific controls without + inventing hierarchy behavior. +- Dimension presentation can be changed without mutating its semantic + measurement data. +- Scene serialization and the current annotation wrapper/storage model require + an explicit schema migration. +- Existing annotation entries require a clean migration decision before + implementation; no compatibility mechanism is implied by this proposal. + +## Compatibility + +This changes Scene's durable schema and the public location of persistent +annotations. Implementation must define the exact schema transition and update +Core, Viewer, framework gates, examples, and documentation together. + +## Verification + +- Round-trip spatial hierarchy and ordered annotations independently. +- Bind independently loaded annotation data by stable identity. +- Verify annotations have no node, parent, children, or inherited transform. +- Verify associative anchors resolve against spatial scene objects. +- Verify ordinary reparent and transform operations reject annotations. +- Verify the Scene tree excludes annotations and the flat Annotations UI shows + them in collection order. +- Verify visibility, selection, naming, and removal do not mutate spatial + hierarchy. +- Verify supported dimension-style values round-trip and refresh only the + annotation render layer. +- Verify semantic anchors, unit, precision, and label are unchanged by style + edits. +- Verify a future Session can aggregate the Scene without becoming annotation + owner. + +## Dependencies + +- Amends Accepted ADRs 005, 013, and 021. +- Preserves ADR 010's independent-data binding boundary. +- Rendering is independent and governed by Accepted ADR 030. + +## Decision + +Approved on 2026-11-09. Core Scene owns one ordered annotation collection +outside the spatial hierarchy. Viewer presents it through a separate flat +Annotations UI. Semantic annotation data remains independent from durable +visibility and the narrow dimension style consisting of color, line width, +text size, arrow size, and label offset. Annotations have no hierarchy or +inherited-transform semantics, and Session remains only a possible future +aggregate rather than the annotation owner. diff --git a/initiatives/scene-viewer-visualisation/decisions/030-always-visible-dimension-rendering.md b/initiatives/scene-viewer-visualisation/decisions/030-always-visible-dimension-rendering.md new file mode 100644 index 0000000..d4424c0 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/030-always-visible-dimension-rendering.md @@ -0,0 +1,73 @@ +# ADR 030: Always-Visible Persistent Dimension Rendering + +## Status + +Accepted. + +## Context + +Transient measurement feedback renders above scene geometry and remains +legible. Persistent distance dimensions were rendered in the ordinary +depth-tested world-annotation pass and could disappear behind geometry. Their +durable storage location does not determine their render-layer semantics. + +## Options + +1. Render persistent distance dimensions in a separate final pass without + depth testing or depth writes. +2. Keep depth testing and increase depth bias or epsilon. +3. Reimplement persistent dimensions on the transient QWidget canvas. +4. Keep the current equal-depth world-annotation pass. + +## Recommendation + +Choose option 1. + +Viewer renders ordinary world text and arrows with their existing depth +behavior. It then renders `DistanceDimension` objects in a separate final pass, +preserving their scene insertion order. Depth testing and depth writes are +disabled for this pass, so scene geometry cannot hide a dimension. + +The pass restores the previous depth function, depth-test enablement, and +depth-write mask in all success and failure paths. It reuses the existing +dimension render geometry and does not duplicate persistent dimension drawing +on the transient QWidget canvas. + +This decision is independent of annotation persistence and UI ownership. +ADR 029 may later move annotations out of the spatial hierarchy without +changing this rendering contract. + +## Consequences + +- Persistent and transient distance feedback remain legible over scene + geometry. +- Dimensions no longer communicate occlusion through the depth buffer; their + purpose is annotation rather than solid-scene geometry. +- Text and arrow annotations keep their existing behavior. +- No general render-layer or annotation-plugin framework is introduced. + +## Compatibility + +This changes only Viewer rendering behavior. Annotation data, serialization, +anchor resolution, and public construction APIs remain unchanged. + +## Verification + +- Verify ordinary world annotations render before persistent dimensions. +- Verify insertion order is preserved within each pass. +- Verify dimensions draw with depth testing and depth writes disabled. +- Verify the previous depth function, test enablement, and write mask are + restored after success and after a draw failure. +- Verify scene geometry cannot hide a completed distance dimension. + +## Dependencies + +- Refines Accepted ADRs 005, 021, 024, and 026. +- Independent of Proposed ADR 029. + +## Decision + +Approved on 2026-11-09. Persistent distance dimensions render in a separate +final Viewer pass without depth testing or depth writes. The rationale is that +durable annotation visibility should match transient measurement legibility +without coupling render policy to spatial hierarchy or storage ownership. diff --git a/initiatives/scene-viewer-visualisation/decisions/031-spatial-object-deletion.md b/initiatives/scene-viewer-visualisation/decisions/031-spatial-object-deletion.md new file mode 100644 index 0000000..d0183f8 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/031-spatial-object-deletion.md @@ -0,0 +1,94 @@ +# ADR 031: Spatial Object Deletion + +## Status + +Accepted. + +## Context + +Core `Scene.remove` already removes one scene object or one complete group +subtree without deleting the independently owned geometry or data item. Viewer +already wraps that operation with render-resource, picking, selection, buffer, +and UI cleanup, and registers `viewer.delete_selected` with the Delete key. + +Deletion is not discoverable in the default menus, however, and the viewport +key binding may not be available while the scene tree owns keyboard focus. +Deletion also has to remain consistent with transform-only history, associative +dimensions, and the proposed separation of spatial objects and annotations. + +## Options + +1. Expose the existing **Delete Selected** command in the default Edit menu and + preserve the current removal semantics. +2. Add deletion to the transform undo/redo stack. +3. Cascade deletion to dimensions that reference removed objects. +4. Add a separate Scene-tree-specific deletion implementation. + +## Recommendation + +Choose option 1. + +The default Edit menu exposes one **Delete Selected** action backed by the +existing `viewer.delete_selected` command and Delete shortcut. The operation +removes every selected spatial object and every descendant of a selected group +as one Viewer mutation. + +Deletion does not delete independently owned geometry or data. It removes +scene placement, render resources, picking registrations, and every removed +object from selection. It rebuilds the affected Viewer buffers and refreshes +the scene tree and viewport. + +Deletion is not undoable in this phase. It clears the existing transform-only +undo and redo history instead of implying a broader history contract. +Associative dimensions that reference a removed object remain durable and +become explicitly unresolved; deletion never converts them to fixed dimensions +or removes them as a cascade. + +ADR 029's flat Annotations UI owns annotation removal. Spatial deletion remains +a Scene-tree operation and does not remove annotation entries merely because +their referenced objects were deleted. + +## Consequences + +- Deletion is visible and usable regardless of whether the viewport or scene + tree currently has focus. +- Core and Viewer retain one removal path rather than duplicating Scene-tree + logic. +- Subtree, independent-data, selection, rendering, and unresolved-association + behavior remain explicit. +- Deletion remains outside undo/redo until a broader history decision is + proposed and approved. + +## Compatibility + +This exposes existing behavior through the default Edit menu. It does not +change Core scene serialization, object ownership, removal semantics, or the +transform-only history contract. + +## Verification + +- Verify **Delete Selected** appears once in the default Edit menu with the + existing command and shortcut. +- Verify it works when the viewport and scene tree respectively own focus. +- Verify one object and one selected group subtree remove all associated render + objects, picking colors, and selection entries. +- Verify independently owned data remains available after scene removal. +- Verify deletion clears transform undo and redo history. +- Verify an associative dimension remains present and resolves as unresolved + after deletion of its referenced object. +- Verify a fixed dimension is unchanged by deletion of unrelated objects. +- Verify spatial deletion and annotation removal remain separate operations. + +## Dependencies + +- Preserves Accepted ADRs 003, 004, 010, 013, and 028. +- Annotation removal is governed separately by Accepted ADR 029. + +## Decision + +Approved on 2026-11-09. Viewer exposes the existing +`viewer.delete_selected` command once through the default Edit menu. Spatial +deletion preserves independently owned data, removes selected subtrees and +their Viewer resources, clears transform-only history, and leaves dependent +associative dimensions present but unresolved. Annotation removal remains a +separate ADR 029 operation. diff --git a/initiatives/scene-viewer-visualisation/decisions/032-three-domain-viewer-sidebar.md b/initiatives/scene-viewer-visualisation/decisions/032-three-domain-viewer-sidebar.md new file mode 100644 index 0000000..e1500a2 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/032-three-domain-viewer-sidebar.md @@ -0,0 +1,167 @@ +# ADR 032: Three-Domain Viewer Sidebar + +## Status + +Accepted. + +## Context + +The current right sidebar places the Scene tree, the flat Annotations panel, +and a shared Object/Camera/Display/Units tab form in one vertical splitter. +Selecting an annotation changes the annotation panel's size hint and updates +the complete sidebar, which redistributes the other panels. Spatial-object +details remain visible at the same time as annotation details even though the +two selections are intentionally independent. This makes the retained object +selection look stale or incorrectly connected to the annotation selection. + +Annotation details are embedded below the annotation list, annotation naming +depends on an undiscoverable inline tree edit, and neither an empty viewport +click nor the effective window-level Escape shortcut clears annotation +selection. The resulting UI does not give Scene, annotation, and system +settings clear ownership or a stable master/detail layout. + +## Options + +1. Replace the stacked sidebar with three top-level domains: **Scene**, + **Annotations**, and **System**. +2. Keep the current splitter and repair its sizing, update routing, and + selection behavior. +3. Introduce one union selection shared by spatial objects and annotations. +4. Make spatial and annotation selection mutually exclusive. + +## Recommendation + +Choose option 1. + +`SideBarRight` becomes one full-height tab widget with exactly three built-in +tabs: + +- **Scene** contains the spatial hierarchy and the selected spatial object's + details and controls. +- **Annotations** contains the ordered annotation list and the selected + annotation's details and controls. +- **System** contains Camera, Display, and Units and Measurement sections. + +Scene and Annotations use ordinary vertical layouts with a stable +master/detail allocation. The sidebar must not use a splitter whose sizes are +recomputed when a selection changes or a detail form is rebuilt. System uses +one scrollable page of clearly labeled sections rather than adding more +top-level tabs. The active tab is transient UI state, defaults to Scene, and +does not require a Viewer configuration schema change. + +Keep `ViewerState.selection` and `ViewerState.annotation_selection` as +independent typed selections. They may both contain values and are preserved +when tabs change. Spatial picking and the Scene tree change only spatial +selection. The annotation list changes only annotation selection. The design +does not add a union or active-selection abstraction. + +An unmodified click on empty viewport background clears both selections. +Ctrl-click on empty background remains a no-op. Escape first cancels an active +measurement and stops; otherwise it clears both selections. An editor that +owns Escape retains its normal local behavior. Annotation-list Delete removes +annotations only, while spatial Delete retains ADR 031's behavior. + +The annotation Name column is display-only. For exactly one selected +annotation, the details area exposes an explicit Name field, read-only Type, +and the supported distance-dimension style controls. Name commits update the +annotation collection and list without rebuilding render resources. Style +edits refresh only the affected annotation layer. No selection shows a clear +empty state; multiple selection shows a summary and the supported removal +operation rather than an ambiguous single-item form. + +Commands address the sidebar through a narrow tab/section navigation boundary +instead of reaching into generic form internals: + +```python +SidebarTab = Literal["Scene", "Annotations", "System"] +SystemSection = Literal["Camera", "Display", "Units and Measurement"] + +class SideBarRight: + def set_current_tab(self, tab: SidebarTab) -> None: ... + def focus_system_section(self, section: SystemSection) -> None: ... +``` + +The strings above name the complete accepted identifier sets, not arbitrary +extension values. Either method raises `ValueError` for an unsupported value. +`focus_system_section` activates System before focusing the requested section. +In particular, Camera Settings uses it to activate System and focus Camera. + +Existing sidebar-item component types remain the extension input for this +migration and are routed by domain: + +- `SceneTree`, `ObjectSetting`, and optional `DatastructureAttributes` belong + to Scene; +- `AnnotationPanel` belongs to Annotations; and +- `CameraSetting`, `DisplaySetting`, and `MeasurementSetting` belong to + System. + +The datastructure inspector remains omitted from the default composition. When +it is explicitly added through `viewer.sidebar_items`, it appears in Scene. + +## Consequences + +- Scene, annotation, and system controls have explicit and stable ownership. +- Spatial and annotation context can coexist without being presented as one + selection. +- Annotation naming and detail editing become discoverable. +- Background click and Escape provide predictable global deselection. +- The sidebar no longer resizes unrelated panels when annotation details + change. +- Viewer sidebar composition and interaction tests require a coordinated + update; Core Scene and its serialization require no change. + +## Compatibility + +This is a clean Viewer UI-composition change. It preserves the existing +spatial and annotation state models, durable annotation collection, Viewer +configuration schema, and optional sidebar component types. Code that reaches +through the sidebar into the old shared tab form is internal and must migrate +to the explicit sidebar navigation boundary. No compatibility layer for the +old visual arrangement is required. + +## Verification + +- Verify exactly three built-in top-level tabs and their component ownership. +- Verify no root or page splitter redistributes panes after selection or form + updates. +- Verify explicit annotation Name editing and the single, multiple, and empty + annotation-detail states. +- Verify object picking affects only spatial selection and annotation-list + interaction affects only annotation selection. +- Verify tab switching preserves both selections. +- Verify an unmodified empty viewport click clears both selections and + Ctrl-click does not. +- Verify real-window Escape cancels an active measurement first and otherwise + clears both selections, including when the viewport or a tree has focus. +- Verify editor-local Escape, annotation Delete, and spatial Delete retain + their distinct ownership. +- Verify Camera Settings activates System and focuses Camera. +- Verify optional datastructure attributes are absent by default and route to + Scene when explicitly configured through `viewer.sidebar_items`. +- Update Viewer user and developer documentation for the three domains and + selection behavior. + +## Dependencies + +- Refines Accepted ADRs 003, 027, 029, and 031. +- Preserves ADR 029's separate annotation collection and selection. +- Preserves ADR 031's separate spatial deletion operation. +- Requires no Core change. + +## Decision + +Approved on 2026-11-09. Viewer replaces the mixed stacked sidebar with stable +Scene, Annotations, and System domains. Spatial and annotation selections +remain independent and survive tab changes; empty-background click and Escape +clear both after measurement-cancel precedence. Annotation naming moves to an +explicit detail form, and commands use the closed sidebar tab/section +navigation boundary recorded above. + +Implementation evidence on 2026-11-09 exposed two regressions. Annotation +graphics refresh synchronously rebuilt the annotation tree, deleting the +checkbox item while its Qt signal was still active. Annotation graphics refresh +now updates render resources and redraws without rebuilding sidebar domains. +Numeric object editors also inferred integer-only behavior from the current +value even when the authoritative `SceneStateField` accepted both integers and +floats. Editors now use the declared field type, with current-value inference +only for contextual non-state attributes. diff --git a/initiatives/scene-viewer-visualisation/decisions/033-scene-inspector-details.md b/initiatives/scene-viewer-visualisation/decisions/033-scene-inspector-details.md new file mode 100644 index 0000000..3821a5d --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/033-scene-inspector-details.md @@ -0,0 +1,78 @@ +# ADR 033: Resizable Scene Inspector and Details Dialog + +## Status + +Proposed. + +## Context + +The Scene tab currently gives the hierarchy and selected-object controls a +fixed layout allocation. `ObjectSetting` also places a read-only description +textbox above the editable controls. The description consumes scarce sidebar +space, while users cannot resize the hierarchy and selected-object areas. + +ADR 032 prohibited the previous root splitter because it mixed unrelated +Scene, Annotation, and System domains and redistributed them during updates. +That does not require the complete absence of a stable splitter inside one +domain. + +## Options + +1. Use one Scene-local two-pane splitter and move descriptive information to a + Details dialog. +2. Keep the fixed layout and only remove the description. +3. Restore a root-level splitter. +4. Add a permanently live modeless inspector window. + +## Recommendation + +Choose option 1. + +Keep the root three-domain tab widget. When both hierarchy and selected-object +details exist, the Scene page contains one vertical splitter with exactly two +stable children for its complete lifetime. The hierarchy is above the existing +Object or Object/Attributes detail surface. Initial stretch is 3:2, neither +child is collapsible, and selection or form updates never reset the user's +dragged allocation. Splitter position is transient UI state. + +Remove the inline read-only object-description textbox. Keep editable controls +in the selected-object panel and add a fixed **Details** button at its bottom: + +- no selection: show `No object selected` and disable Details; +- one selection: show editable controls and enable Details; +- multiple selection: show only a short count, no shared editing controls, and + enable Details. + +Details opens a read-only modal dialog owned by the main window. It snapshots +the current selection. For one object it shows name, represented type, +visibility, and complete inspected parameters. For multiple objects it shows +count, types, and names. It does not track later selection changes. + +## Consequences + +- Sidebar space is used for editable controls rather than duplicated prose. +- Users control the Scene hierarchy/detail allocation without destabilizing + Annotations or System. +- No configuration, serialization, selection, or Core change is required. +- A live modeless inspector and persisted splitter position remain outside + scope. + +## Verification + +- Verify the root remains the three-domain tab widget. +- Verify exactly one Scene-local splitter when both panes exist and none in + Annotations or System. +- Verify user-set sizes survive zero, one, and multiple selection updates. +- Verify the inline description textbox is absent. +- Verify Details enablement and one/multiple-selection dialog content. +- Verify existing editable controls and optional Attributes routing remain + unchanged. + +## Dependencies + +- Narrowly amends Accepted ADR 032's no-page-splitter rule. +- Preserves Accepted ADRs 015–018 and 032's domain ownership. + +## Decision + +Pending explicit approval. diff --git a/initiatives/scene-viewer-visualisation/decisions/034-hidden-vertex-snapping.md b/initiatives/scene-viewer-visualisation/decisions/034-hidden-vertex-snapping.md new file mode 100644 index 0000000..602908a --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/034-hidden-vertex-snapping.md @@ -0,0 +1,74 @@ +# ADR 034: Mesh-Vertex Snapping Independent of Vertex Glyphs + +## Status + +Proposed. + +## Context + +Semantic snapping already enumerates every Mesh vertex while a measurement +tool is active. In practice, vertices become unreliable when normal vertex +glyphs are hidden because the instance/depth pass loses their dedicated point +footprint. Nearby faces or edges may happen to provide qualifying pixels, so +the current result is geometry-dependent. + +Normal rendering preferences and measurement eligibility are separate +concerns. A measurement guide can make a candidate visible without requiring +the ordinary vertex display to remain enabled. + +## Options + +1. Add a measurement-only acquisition footprint for Mesh vertices. +2. Require normal vertex glyphs to be visible. +3. Accept every projected vertex without depth qualification. +4. Add edge and face snapping at the same time. + +## Recommendation + +Choose option 1. + +`show_vertices` controls ordinary Mesh vertex glyphs only. During an active +measurement, every vertex of an effectively visible Mesh is a semantic +candidate and may appear as a hollow-square guide even when normal vertex +glyphs are off. + +Viewer renders a measurement-only point footprint into the offscreen +instance/depth acquisition pass. It never appears in ordinary rendering. The +nearest vertex within the existing 18-logical-pixel radius wins only when its +measurement footprint passes the existing same-object depth qualification. + +`show=False`, including effective ancestor hiding, remains a hard exclusion. A +Mesh with no visible face, edge, or vertex representation is not discoverable +solely because measurement mode is active. Faces and edges may establish +visibility and occlusion but remain non-candidates and create no attraction. +Partial ordinary vertex-display lists do not restrict measurement candidates. + +## Consequences + +- Users can snap to vertices of the normal face-only Mesh display. +- Measurement feedback, not ordinary glyph configuration, communicates snap + availability. +- Occluded vertices and other objects' pixels remain ineligible. +- No new public API, general snapping framework, or edge/face snapping is + introduced. + +## Verification + +- Verify hidden ordinary Mesh vertices remain semantic candidates. +- Verify face-only and edge-only visible Meshes produce guides and a qualified + winner. +- Verify front/silhouette vertices pass while back, depth-mismatched, and + externally occluded vertices do not. +- Verify hidden whole objects and Meshes with no visible representation produce + no candidates. +- Verify no edge or face result is introduced and the 3–4–5 regression remains + exact. + +## Dependencies + +- Amends Accepted ADR 026's visible-discrete-point acquisition wording. +- Preserves Accepted ADR 028's anchor semantics. + +## Decision + +Pending explicit approval. diff --git a/initiatives/scene-viewer-visualisation/decisions/035-distance-dimension-spatial-layout.md b/initiatives/scene-viewer-visualisation/decisions/035-distance-dimension-spatial-layout.md new file mode 100644 index 0000000..058a47d --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/035-distance-dimension-spatial-layout.md @@ -0,0 +1,107 @@ +# ADR 035: Distance-Dimension Spatial Layout + +## Status + +Proposed. + +## Context + +Persistent distance dimensions currently draw their dimension line between the +two measured anchors. This keeps the measured value correct, but it does not +allow the line and label to be moved away from the geometry for legibility. + +The measured anchors and value are semantic dimension data. The location of +the displayed dimension line is scene-specific presentation. A Viewer +construction plane can help an author choose an offset direction, but the +resulting dimension must not depend on mutable Viewer state or on the current +camera. + +## Options + +1. Store a signed world-space offset and captured plane normal as durable + dimension layout on the scene annotation. +2. Store a complete construction plane on the semantic distance dimension. +3. Choose the offset direction from the current camera whenever the annotation + is rendered. +4. Add the spatial offset to the existing screen-space dimension style. + +## Recommendation + +Choose option 1. + +Add a narrow durable `layout` field to the scene annotation that presents a +distance dimension: + +```python +DistanceDimensionLayout( + offset: float = 0.0, + plane_normal: Vector | None = None, +) +``` + +`SceneAnnotation.layout` has type `DistanceDimensionLayout | None`. A resolved +distance-dimension entry normalizes `None` to `DistanceDimensionLayout()`. +Supplying a layout for a resolved text or arrow annotation raises `ValueError`. +An unresolved entry may carry the layout until binding, when the same +annotation-type validation is applied. + +`offset` is a signed distance in world coordinate units. The informational +unit stored by the distance dimension does not convert it. `plane_normal` is +captured in world coordinates. For resolved anchors `start` and `end`, the +positive offset direction is + +```text +unit(plane_normal × (end - start)) +``` + +The displaced endpoints define the dimension line. Extension lines connect +the measured anchors to those endpoints. The measured value continues to come +only from the original anchors. The existing logical-pixel label offset applies +relative to the displaced dimension line. + +An offset of zero preserves current rendering and does not require a normal. A +nonzero offset is explicitly layout-unresolved when the normal is missing or +zero, the anchors coincide, or the normal is parallel to the measured segment. +Viewer does not substitute a camera-dependent direction. + +A complete durable construction plane is not part of this decision. Its origin +does not affect the resolved layout. A future Viewer construction-plane tool +may copy its normal into the durable layout, but the dimension does not retain +a live reference to that authoring context. + +## Consequences + +- Dimensions can be placed away from measured geometry without changing their + value or anchors. +- Fixed and associative dimensions use the same deterministic world-space + layout. +- The same independently serialized dimension data can have different layouts + in different scenes. +- The scene-annotation schema and Viewer dimension rendering require a + coordinated clean update. +- A general construction-plane feature remains a separate future decision. + +## Verification + +- Round-trip zero and signed nonzero layout values with scene annotations. +- Verify default normalization and rejection on text and arrow annotations, + including validation when an unresolved entry becomes bound. +- Verify the measured value is unchanged by layout offset. +- Verify positive and negative offsets and extension-line geometry. +- Verify associative-anchor updates recompute the displaced endpoints from the + stored normal and current resolved anchors. +- Verify missing, zero, coincident, and parallel inputs produce an explicit + layout-unresolved state with no camera fallback. +- Verify the existing logical-pixel label offset is relative to the displaced + line and persistent dimensions remain in the final no-depth render pass. +- Verify annotation bounds include both anchors and displaced endpoints. + +## Dependencies + +- Extends Accepted ADRs 021, 028, 029, and 030. +- Preserves ADR 022's informational unit semantics. +- Does not approve a reusable Viewer construction-plane feature. + +## Decision + +Pending explicit approval. diff --git a/initiatives/scene-viewer-visualisation/decisions/036-viewport-text-ownership-and-persistence.md b/initiatives/scene-viewer-visualisation/decisions/036-viewport-text-ownership-and-persistence.md new file mode 100644 index 0000000..cd36fee --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/036-viewport-text-ownership-and-persistence.md @@ -0,0 +1,102 @@ +# ADR 036: Viewport Text Ownership and Persistence + +## Status + +Accepted. + +## Context + +Text placed at a location in the view can mean either a world annotation whose +position is chosen through the viewport or text that remains fixed to the +screen while the camera changes. These have different ownership and +serialization contracts. Treating both as the existing world-space +`TextAnnotation` would hide that distinction. + +Persistent screen text also belongs to a particular view rather than to the +spatial Scene. The current initiative has not yet approved Session or view-state +persistence for such content. + +## Options + +1. Add a screen-pinned Viewer overlay in normalized viewport coordinates and + keep it out of Scene serialization for now. +2. Place an existing world-space text annotation by intersecting the viewport + ray with geometry or a construction plane. +3. Store screen coordinates directly in Scene annotations. +4. Make screen-pinned text persistent immediately by first designing Session + and view-state serialization. + +## Recommendation + +Choose option 1 for the requested view-screen text. + +Add one concrete Viewer-owned `ScreenTextOverlay` rather than a generalized +overlay registry. It contains text, a normalized viewport position, +horizontal and vertical alignment, and color. If ADR 037 is separately +accepted, it also exposes the equivalent narrow optional background fields. + +`(0, 0)` is the top-left and `(1, 1)` is the bottom-right of the viewport. +Resizing preserves the relative position. Camera changes do not move the text. +Drawing is clipped to the viewport. The overlay is not pickable, does not enter +the spatial Scene or annotation collection, and is absent from Scene +serialization. + +This recommendation intentionally does not make the overlay survive save/load. +If immediate persistence is required, implementation is blocked until a +separate Session/view-state decision defines ownership, stable identity, and +serialization. Viewer configuration is not an alternative owner because it +describes application defaults rather than document content. + +The narrow initial scope exposes construction through `viewer.add_overlay` +and removal through `viewer.remove_overlay`; it does not add a partial +interactive authoring UI. A user-facing click-to-place command also needs a +place to list, select, edit, and delete the resulting screen overlays. If that +workflow is required now, implementation is blocked until the same approval +defines that Viewer-side management surface, or Session/view-state ownership +if the result must persist. + +World-space text selected through the viewport remains a different operation +using the existing `TextAnnotation`; it requires an explicit world-point +acquisition contract and is outside this decision. + +## Consequences + +- The meaning of screen text remains stable under camera movement and viewport + resize. +- Scene stays limited to spatial content and durable scene annotations. +- The implementation remains one concrete overlay instead of a speculative + text or overlay framework. +- Screen-text persistence is deferred unless the user explicitly requires it, + in which case Session/view-state architecture must be approved first. +- World-space text placement remains available as a separately designed + feature rather than an overloaded mode. + +## Verification + +- Verify normalized positions at viewport corners and interior locations. +- Verify viewport resize preserves relative placement and camera changes have + no effect. +- Verify drawing clips to the viewport and respects insertion order. +- Verify screen text is unpickable and excluded from Scene and annotation + serialization. +- Verify color, alignment, and optional background presentation update only + the overlay layer. +- Verify no Session or configuration persistence is implied by the initial + implementation. + +## Dependencies + +- Extends Accepted ADRs 005 and 025 with one concrete overlay type. +- Uses ADR 037's narrow background presentation if both are accepted. +- Persistent screen text is blocked on a future Session/view-state ADR. +- World-space text placement would require a separate acquisition decision. + +## Decision + +Approved on 2026-11-09. Initial viewport text is a screen-pinned Viewer overlay +using normalized viewport coordinates. It is created and removed through the +existing `viewer.add_overlay` and `viewer.remove_overlay` boundary. The initial +scope is programmatic only and does not add interactive placement, listing, +selection, editing, deletion, or persistence. Those capabilities require +separate approval, with durable screen-text ownership blocked on a future +Session/view-state decision. diff --git a/initiatives/scene-viewer-visualisation/decisions/037-annotation-label-backgrounds.md b/initiatives/scene-viewer-visualisation/decisions/037-annotation-label-backgrounds.md new file mode 100644 index 0000000..8728526 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/037-annotation-label-backgrounds.md @@ -0,0 +1,83 @@ +# ADR 037: Optional Annotation Label Backgrounds + +## Status + +Proposed. + +## Context + +Text and distance labels can overlap geometry or a dimension line. Without a +background, their glyphs may become unreadable. This is durable presentation, +not semantic annotation data, and it does not justify a general typography, +theme, or label-style system. + +## Options + +1. Add two direct optional background fields to scene-annotation + presentation. +2. Add a new public label-background class. +3. Duplicate background fields in dimension style and a new text style. +4. Make backgrounds a Viewer-global display preference. + +## Recommendation + +Choose option 1. + +Add only these fields to the durable scene-annotation presentation: + +```python +label_background: Color | None = None +label_background_padding: float = 2.0 +``` + +`None` keeps the current transparent result. The color alpha controls +background opacity. Padding is a nonnegative distance in logical pixels around +the rendered glyph bounds. The fields apply only when the presented annotation +has a text label, initially `TextAnnotation` and `DistanceDimension`. They do +not add label semantics to arrows. A resolved arrow entry accepts only the +defaults (`None` and `2.0`); assigning a background color or non-default +padding raises `ValueError`. An unresolved entry is validated the same way +when it becomes bound. + +Viewer draws the background immediately behind the label in the label's +existing render pass. For a distance dimension, the line is drawn first and +the label background covers the portion beneath the label. No border, corner +radius, shadow, font, theme, or generalized style object is introduced. + +A Viewer-only screen-text overlay may expose equivalent direct fields, but it +does not use scene-annotation storage. + +## Consequences + +- Labels remain legible over geometry and dimension lines. +- The schema stays transparent and avoids a new public helper type for two + values. +- Background presentation round-trips independently from semantic annotation + data. +- Core scene-annotation serialization and Viewer label rendering require a + coordinated clean update. +- More elaborate typography remains outside scope. + +## Verification + +- Round-trip `None`, opaque, translucent, and transparent colors. +- Accept zero and positive logical-pixel padding and reject negative padding. +- Verify default rendering is visually unchanged. +- Verify the background encloses padded glyph bounds and is drawn behind text + but in front of an overlapping dimension line. +- Verify background edits refresh only the affected annotation render layer. +- Verify semantic text, anchors, units, values, and precision remain unchanged. +- Verify annotations without labels do not gain background rendering. +- Verify non-default background presentation is rejected for resolved and + newly bound arrow annotations. + +## Dependencies + +- Extends Accepted ADRs 021 and 029's scene-presentation boundary. +- Preserves ADR 029's narrow `DimensionStyle` rather than mixing screen-pixel + label background fields into line and arrow presentation. +- ADR 036 may expose equivalent Viewer-owned fields for screen text. + +## Decision + +Pending explicit approval. diff --git a/initiatives/scene-viewer-visualisation/decisions/038-contextual-delete-selected.md b/initiatives/scene-viewer-visualisation/decisions/038-contextual-delete-selected.md new file mode 100644 index 0000000..70fb175 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/038-contextual-delete-selected.md @@ -0,0 +1,84 @@ +# ADR 038: Contextual Delete Selected + +## Status + +Proposed. + +## Context + +The default **Edit > Delete Selected** command and Delete shortcut currently +remove only spatial scene objects. Annotation removal exists in the +Annotations panel, but selecting a dimension does not make the user-facing +command remove it. Spatial and annotation selections may intentionally coexist, +so deleting their union would cross ownership boundaries and could remove more +than the current context indicates. + +## Options + +1. Dispatch the user-facing command to the selection owned by the current + interaction context. +2. Delete both spatial and annotation selections together. +3. Keep the menu command spatial-only and require the annotation Remove + control. +4. Replace the two selections with one union selection. + +## Recommendation + +Choose option 1. + +**Delete Selected** removes the selection owned by the current interaction +context and never crosses collection boundaries or deletes both coexisting +selections. The two existing removal operations remain separate. + +Dispatch follows this precedence: + +1. A focused text or numeric editor retains its normal local Delete behavior. +2. Focus in the annotation list or annotation details removes annotation + selection. +3. Focus in the Scene tree or viewport removes spatial selection, even if a + different sidebar tab remains visible. +4. Menu activation obscures the previous focused widget, so **Edit > Delete + Selected** follows the active sidebar tab: Scene removes spatial selection, + Annotations removes annotation selection, and System disables the menu + action. The underlying command safely performs no operation if invoked + directly while System is active. + +When both selections contain values, exactly one domain is affected and the +other selection remains unchanged. The explicit Annotations-panel Remove +control remains annotation-only. + +## Consequences + +- Selected dimensions can be removed through the same discoverable command as + selected spatial objects without conflating the two collections. +- Delete behavior follows visible interaction context and preserves + editor-local key behavior. +- Existing spatial subtree removal and annotation removal primitives remain + independently testable. +- Viewer needs a narrow way to query the active sidebar domain and route menu + and shortcut invocation. +- No union-selection abstraction or Core schema change is introduced. + +## Verification + +- Verify local Delete remains available in focused text and numeric editors. +- Verify annotation-list and annotation-detail focus delete annotations only. +- Verify Scene-tree and viewport focus delete spatial objects only. +- Verify menu invocation follows Scene, Annotations, and System tab ownership. +- Verify System disables the menu action and direct command invocation is a + no-op. +- Verify simultaneous selections remove exactly one domain and preserve the + other selection. +- Verify the explicit annotation Remove control remains annotation-only. +- Re-run spatial subtree, annotation resource cleanup, unresolved associative + anchor, and transformation-history invalidation regressions. + +## Dependencies + +- Amends Accepted ADR 032's input-ownership and Delete behavior. +- ADR 031 continues to govern the spatial removal primitive. +- ADR 029 continues to govern annotation removal and selection. + +## Decision + +Pending explicit approval. diff --git a/initiatives/scene-viewer-visualisation/decisions/039-scene-add-menu.md b/initiatives/scene-viewer-visualisation/decisions/039-scene-add-menu.md new file mode 100644 index 0000000..a540e44 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/039-scene-add-menu.md @@ -0,0 +1,85 @@ +# ADR 039: Scene-Owned Add Menu + +## Status + +Proposed. + +## Context + +Viewer currently exposes geometry presets in a separate top-level **Add** menu. +Every geometry item created by these commands enters the current spatial Scene, +alongside the Scene menu's clear, load, and save operations. Keeping Add at the +top level obscures that ownership. + +Other creation workflows have different meanings. Measurement commands are +interactive acquisition tools even when they produce a durable dimension. +Transient overlays and system configuration do not enter the Scene. + +## Options + +1. Move the existing geometry hierarchy to **Scene > Add**. +2. Keep **Add** as a top-level menu. +3. Move every command that can eventually create durable data under Scene. +4. Expand Add with speculative datastructure, group, annotation, and text + commands during the move. + +## Recommendation + +Choose option 1. + +Move only the existing geometry hierarchy beneath **Scene > Add**: + +- Primitives; +- Curves; +- Surfaces; and +- Shapes. + +Preserve the existing command identifiers, callbacks, preset parameters, and +resulting Scene insertion behavior. This is a menu-ownership change, not a new +creation API. + +Keep measurement acquisition under **Measure**, including fixed and +associative dimension commands. Keep Scene load as a separate Scene operation. +Do not add datastructure, group, general annotation, or text creation commands +as part of this change. Transient overlays and System settings remain outside +Scene > Add. + +The old top-level Add path is removed without a compatibility alias. Extension +code should not receive a new arbitrary nested-menu registration API merely to +preserve the former path; any future menu-extension contract requires its own +evidence and decision. + +## Consequences + +- Menu placement communicates that added geometry belongs to the current + Scene. +- Existing creation behavior and command identities remain stable. +- Measurement remains organized by authoring workflow rather than by the + persistence of its result. +- The top-level menu becomes less crowded without introducing new commands or + extension abstractions. +- Code or tests that locate the former top-level Add menu must use the new + nested location. + +## Verification + +- Verify the top-level Add menu is absent and **Scene > Add** contains the four + existing geometry categories in their current order. +- Verify every existing geometry command retains its identifier, callback, + preset parameters, and resulting Scene object. +- Verify Measure still owns transient inspection and fixed and associative + dimension acquisition. +- Verify Scene load, save, and clear remain separate operations. +- Verify no datastructure, group, general annotation, text, overlay, or System + creation command is added. +- Update user and developer documentation that names the old Add menu path. + +## Dependencies + +- Consistent with Accepted ADRs 001 and 013's Scene ownership. +- Preserves Accepted ADRs 024 and 026's measurement-tool lifecycle. +- Requires no Core, Scene schema, or serialization change. + +## Decision + +Pending explicit approval. diff --git a/initiatives/scene-viewer-visualisation/decisions/040-default-toolbar-view-shortcuts.md b/initiatives/scene-viewer-visualisation/decisions/040-default-toolbar-view-shortcuts.md new file mode 100644 index 0000000..21d79a1 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/040-default-toolbar-view-shortcuts.md @@ -0,0 +1,97 @@ +# ADR 040: Default Toolbar View Shortcuts + +## Status + +Accepted. + +## Context + +Viewer already exposes render-mode and current-view selection through the +View menu and System sidebar. Both surfaces use stable commands and shared +Viewer state, but the default toolbar is empty and hidden. Frequently changing +these presentation settings therefore requires opening a menu or sidebar. + +Nine independent toolbar buttons would consume substantial space and require +new icons and active-button styling. Two labeled selectors can expose the same +choices while preserving one command and state path for every operation. + +## Options + +1. Add two state-bound toolbar selectors and show the default toolbar. +2. Add nine independent icon or text buttons. +3. Add the selectors but keep the default toolbar hidden. +4. Keep render-mode and view selection in the menu and sidebar only. + +## Recommendation + +Choose option 1. + +Add one narrow toolbar item type, `select`, and populate the default toolbar +through `default_toolbar_items()`. The default controls, in order, are: + +1. **Render Mode** + - Shaded + - Ghosted + - Lighted + - Wireframe +2. **View** + - Perspective + - Top + - Front + - Right + - Ortho + +The selectors reuse `viewer.change_rendermode` and `viewer.change_view` and +bind to `renderer.rendermode` and `renderer.view`. Toolbar, View menu, System +form, and public API updates synchronize through the existing Viewer-state +signal. State-driven selector updates block their own signals and do not invoke +the commands again. + +Change the default `ui.toolbar.show` value to `True` so the shortcuts are +discoverable. An explicit configured value of `False` remains authoritative. +Existing custom `viewer.toolbar_items` remains the composition boundary. + +Do not add renderer commands, a general toolbar-widget registry, an icon +system, or another state path. + +## Consequences + +- Render-mode and view shortcuts are visible by default and remain compact. +- Menu, sidebar, toolbar, and public API controls cannot drift because they + observe the same state. +- Existing configurations that explicitly hide the toolbar remain unchanged. +- Applications that relied on the previous implicit hidden default gain one + toolbar unless they set `ui.toolbar.show` to `False`. +- The supported toolbar schema gains one concrete state-bound selector type, + not an arbitrary custom-widget mechanism. + +## Verification + +- Verify the exact selector labels, values, and ordering. +- Verify configured renderer state determines both initial selections. +- Verify each user selection invokes the existing command exactly once. +- Verify menu, System form, and public API changes update the toolbar without + invoking a command again. +- Verify toolbar changes update the menu and System form through shared state. +- Verify explicit `ui.toolbar.show=False` remains effective and the unspecified + default is visible. +- Verify invalid selector definitions and unsupported values fail clearly. +- Run focused offscreen Qt tests, the full Viewer suite, Ruff, Pyright, strict + MkDocs, package CI, and framework integration. + +## Dependencies + +- Extends Accepted ADR 006's public Viewer UI facade. +- Amends Accepted ADR 020's default toolbar visibility without changing + configuration ownership or schema. +- Coordinates with ADR 041 through the existing render-mode and view state + paths but is independently implementable. + +## Decision + +Approved on 2026-11-09. The default toolbar gains visible, labeled Render Mode +and View selectors in that order. They reuse the existing commands and shared +renderer state, synchronize without recursive command invocation, and make the +toolbar visible by default while preserving an explicit +`ui.toolbar.show=False`. No button grid, new renderer command, general widget +registry, or icon system is authorized. diff --git a/initiatives/scene-viewer-visualisation/decisions/041-grid-and-units-system-section.md b/initiatives/scene-viewer-visualisation/decisions/041-grid-and-units-system-section.md new file mode 100644 index 0000000..5a17d66 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/041-grid-and-units-system-section.md @@ -0,0 +1,127 @@ +# ADR 041: Grid and Units System Section + +## Status + +Accepted. + +## Context + +The System sidebar currently separates grid controls into Display while unit, +precision, and nine read-only global-tolerance values occupy Units and +Measurement. Grid and coordinate units describe the same spatial presentation +context, whereas global COMPAS tolerance is not currently a Viewer setting and +cannot be changed there. + +Camera and Display also rely on implicit row sizing with different editor +width limits. This produces inconsistent alignment and gives some controls less +usable width than others. + +## Options + +1. Add a Grid and Units section, remove tolerance from Viewer UI, and apply one + System-form layout rule. +2. Keep separate Display and Units and Measurement sections but align them. +3. Make global tolerance editable from Viewer. +4. Change the generic container layout for every Viewer form. + +## Recommendation + +Choose option 1. + +The closed System section set becomes, in order: + +1. Camera +2. Display +3. Grid and Units + +Display retains: + +- Render Mode; +- Current View; +- Background Color; and +- Selection Color. + +Grid and Units contains: + +- Show Grid; +- Show Z Axis; +- Grid Mode; +- Grid Color; +- Grid X Extent and Divisions; +- Grid Y Extent and Divisions; +- Coordinate Unit; and +- Display Precision. + +Replace the public `MeasurementSetting` component and sidebar item type with +`GridUnitSetting`. Replace the closed section identifier `Units and +Measurement` with `Grid and Units`. Remove the old names without aliases. + +Remove every tolerance row and the component's dependency on +`compas.tolerance.TOL`. Do not modify, copy, or provide Viewer controls for the +process-wide tolerance object. Computational code may continue using COMPAS +tolerance internally. + +Preserve the existing `renderer.*`, `measurement.*`, and +`ViewerState.set_measurement_*` paths. Unit remains an informational +declaration: it does not convert coordinates, grid spacing, snapping, geometry, +or measurements. Precision remains paired with the unit and controls +measurement formatting. Because configuration ownership and paths do not move, +no configuration-schema migration is introduced. + +Camera, Display, and Grid and Units use one private two-column layout rule: + +- labels occupy one left-aligned label column; +- editors occupy one aligned right-hand field column; +- editor rows share a common right edge; +- fields use the available column width rather than unrelated fixed maxima; +- checkboxes align within the same field column; and +- compact margins and row heights are retained. + +Implement the rule privately in the three System components. Do not change the +generic `Container` or introduce a public form-layout abstraction. + +## Consequences + +- Spatial grid presentation, declared coordinate unit, and precision are + available in one coherent section. +- Display becomes limited to general renderer presentation. +- Irrelevant global-tolerance information no longer consumes sidebar space, + while COMPAS tolerance behavior remains unchanged. +- System controls use consistent alignment and gain usable editor width. +- Custom sidebar definitions using `MeasurementSetting` or the old section + identifier require a clean update. +- Existing configuration files and runtime state paths remain valid. + +## Verification + +- Verify the exact Camera, Display, and Grid and Units section order and closed + identifiers. +- Verify Display no longer owns grid controls and `GridUnitSetting` owns grid, + unit, and precision controls. +- Verify no tolerance widgets or Viewer component dependency on `TOL` remains. +- Verify grid changes still rebuild only grid resources. +- Verify unit and precision changes affect measurement presentation without + changing geometry, grid scale, snapping, or global tolerance. +- Verify fixed-width Qt layout tests give each System section a common field + column, shared right edge, aligned checkboxes, and usable editor width. +- Verify the retired component type and section identifier fail clearly. +- Preserve configuration round-trip and Viewer-state tests, then run the full + Viewer suite, Ruff, Pyright, strict MkDocs, package CI, and framework + integration. + +## Dependencies + +- Amends Accepted ADR 027 by removing tolerance display while preserving unit + and precision semantics. +- Amends Accepted ADR 032's closed System section and component-type sets. +- Preserves Accepted ADR 020's configuration ownership and schema. +- Coordinates with ADR 040 through shared render-mode and view state. + +## Decision + +Approved on 2026-11-09. System contains Camera, Display, and Grid and Units. +Grid and Units replaces `MeasurementSetting` with `GridUnitSetting`, owns grid, +coordinate-unit, and display-precision controls, and removes tolerance from the +Viewer UI without changing global COMPAS tolerance or existing configuration +and state paths. All three System sections use the approved private aligned +two-column layout. The retired component and section names receive no aliases. diff --git a/initiatives/scene-viewer-visualisation/decisions/042-selected-area-and-volume-inspection.md b/initiatives/scene-viewer-visualisation/decisions/042-selected-area-and-volume-inspection.md new file mode 100644 index 0000000..a5fbfe0 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/042-selected-area-and-volume-inspection.md @@ -0,0 +1,142 @@ +# ADR 042: Selected Area and Volume Inspection + +## Status + +Accepted. + +## Context + +Viewer's Measure menu currently supports point-acquired distance inspection and +persistent distance dimensions. Area and volume are whole-object properties; +they do not require point snapping and should not be forced into the distance +tool state. + +Core types expose area and volume through existing public APIs, but those APIs +are not syntactically uniform: some are methods and others are properties. A +selected scene object may also have inherited world transformations. Measuring +only its local item would disagree with displayed scale, while measuring its +render tessellation would silently replace exact public geometry behavior with +an approximation. + +## Options + +1. Add transient, selection-driven area and volume inspection using the + represented item's public scalar and exact supported transformation rules. +2. Add click-to-acquire whole-object measurement tools. +3. Measure rendered tessellations for every object. +4. Add persistent area and volume annotations immediately. +5. Aggregate areas or volumes across the current selection. + +## Recommendation + +Choose option 1. + +Add these commands to Measure: + +1. Inspect Distance +2. Inspect Selected Area +3. Inspect Selected Volume +4. separator +5. Add Fixed Distance Dimension +6. Add Associative Distance Dimension +7. separator +8. Cancel Measurement + +Use the public command and Viewer method identifiers +`viewer.inspect_selected_area` and `viewer.inspect_selected_volume`. + +Each inspection requires exactly one selected spatial scene object. It first +cancels active and retained distance-inspection state, resolves the represented +item, and reads its public `area` or `volume` member structurally: call the +member when callable, otherwise use the property value. Missing members, +`NotImplementedError`, and `None` mean that the measurement is unsupported. An +open Mesh whose `volume()` returns `None` explicitly reports that it does not +enclose a measurable volume. Other implementation exceptions are reported as +operation failures rather than silently reclassified as unsupported. + +Convert the result to a finite, nonnegative scalar. Reject booleans, +non-numeric values, non-finite values, and negative results. The public Viewer +method returns the world-space scalar or raises a clear error. Only the command +callback owns the read-only result or error dialog. + +Use the complete inherited `SceneObject.worldtransformation`: + +- For area, accept similarity transformations: rotation or reflection with a + uniform scale. Multiply local area by the square of that scale. Reject + non-uniform scale, shear, and projective transformations because a local + scalar does not contain the orientation information needed for an exact + transformed area. +- For volume, accept affine transformations and multiply local volume by the + absolute determinant of the linear part. Reject projective transformations. + +Similarity and affine classification may use COMPAS numerical tolerance +internally. Removing tolerance from Viewer UI in ADR 041 does not remove its +computational role. Never use rendered triangles as an implicit fallback. + +Area meaning follows the represented item's public contract: for example, +planar enclosed area for planar regions and surface area for Mesh, Shape, +Polyhedron, and Brep values. Volume likewise follows the item's declared +contract. + +Format the dialog using current Viewer precision. Append the declaration-only +unit with a squared or cubed exponent when present, such as `m²` or `m³`, and +perform no unit conversion. Retain no new measurement state. Do not mutate the +Scene, spatial or annotation selection, annotations, serialization, or +transformation history. + +Do not aggregate multiple selections or add persistent area/volume +annotations, region acquisition, face snapping, a measurement registry, new +Core protocols, or an approximation mode. + +## Consequences + +- Users can inspect exact supported area and volume values from the existing + selection model. +- The public Viewer methods remain UI-independent and reusable, while commands + own dialogs. +- Displayed transforms affect results when a scalar can be transformed exactly. +- Unsupported APIs, open volumes, and transformations that cannot be resolved + exactly fail explicitly instead of producing plausible but incorrect values. +- Persistent area and volume annotations and click-based region tools remain + outside scope. + +## Verification + +- Verify zero, one, and multiple spatial selections. +- Verify method-valued and property-valued measurements. +- Verify Mesh area, closed Mesh volume, open Mesh volume rejection, analytic + Shape, Polygon, Polyhedron, and available backend Brep behavior. +- Verify unsupported Group, Graph, BufferGeometry, and unresolved references. +- Verify parent and local rigid, reflected, and uniform-scale transformations. +- Verify area rejects non-uniform scale, shear, and projective transforms. +- Verify volume uses exact absolute affine-determinant scaling and rejects + projective transforms. +- Verify boolean, non-numeric, negative, and non-finite results fail clearly. +- Verify precision and squared or cubed unit suffixes without conversion. +- Verify active and retained distance state is cancelled. +- Verify Scene content, both selections, annotations, serialization, and + transformation history remain unchanged. +- Run focused Viewer tests, the full Viewer suite, Ruff, Pyright, strict + MkDocs, package CI, and framework exact-source integration. + +## Dependencies + +- Uses Accepted ADR 003's ordered spatial selection. +- Uses Accepted ADR 004's world-transformation contract. +- Extends Accepted ADR 006's public Viewer facade. +- Defines a transient measurement outcome under Accepted ADR 024. +- Uses ADR 027's unit and precision semantics, as amended by ADR 041 if that + proposal is accepted. +- Interacts with ADR 026 only by cancelling active distance state; it does not + use point snapping. + +## Decision + +Approved on 2026-11-09. Measure gains transient Inspect Selected Area and +Inspect Selected Volume operations for exactly one spatial selection. They use +the represented item's public scalar, apply only the approved exact +world-transformation rules, format declaration-only squared or cubed units, +and present a read-only result without retaining state or mutating the Scene. +Unsupported data and transformations fail explicitly; tessellation fallback, +multi-selection aggregation, persistent annotations, and generic measurement +infrastructure are not authorized. diff --git a/initiatives/scene-viewer-visualisation/decisions/README.md b/initiatives/scene-viewer-visualisation/decisions/README.md new file mode 100644 index 0000000..cf64cc3 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/decisions/README.md @@ -0,0 +1,134 @@ +# Scene, Viewer, and Visualisation Decisions + +ADRs 013–020 are Accepted. ADRs 013–014 supersede the implemented +node/runtime-adapter model of ADR 008, part of ADR 009, and the unaccepted +alternatives in ADRs 011–012. ADR 010 remains Accepted with item references +moved to stable scene objects. ADRs 015–016 authorize contextual object +settings from one normalized mapping: editable `SceneStateField` entries plus +narrowly declared non-state attributes. The earlier `FormField` implementation +has been replaced and verified. ADRs 017–020 authorize lazy datastructure +attribute tables, their editing semantics, configured Viewer identity, and a +configuration lifecycle/field audit. Their implementation is verified locally +and in hosted Viewer and framework CI. ADR 017 is amended to keep the +datastructure inspector out of the default sidebar while preserving opt-in +custom use. ADR 003 is implemented, locally +verified, independently approved, and green in hosted Viewer and refreshed +framework CI. ADR 004 is implemented, locally verified, and independently +approved; refreshed hosted Viewer, core, and framework verification passed. +ADRs 021–031 record the accepted Phase 3 durable annotation ownership, unit +snapshots, clean-break migration, transient/persistent outcomes, overlay +contracts, snapping and acquisition, Viewer measurement presentation, +fixed/associative anchor model, separate annotation collection and UI, +always-visible dimension rendering, and spatial-object deletion behavior. +ADR 032 is Accepted in response to direct-use evidence that the current +stacked sidebar does not provide stable or clearly separated Scene, +Annotations, and System contexts. +ADRs 033–035 and 037–039 are Proposed follow-ups from further direct use. They +cover a Scene-local resizable inspector, vertex snapping independent of normal +glyph visibility, deterministic dimension layout, label backgrounds, +contextual deletion, and moving the existing geometry Add menu under Scene. +ADR 036 accepts programmatic, non-persistent screen-pinned text overlays. Only +ADRs 036 and 040–042 authorize source implementation among these follow-ups. +ADRs 040–042 accept synchronized default-toolbar selectors, a Grid and Units +System section with consistent field alignment and no tolerance UI, and +transient selected-object area and volume inspection. Their implementations +remain pending. + +| ADR | Decision | Status | Dependencies | +|---|---|---|---| +| 001 | [Ownership and state boundaries](001-ownership-boundaries.md) | Accepted | Geometry 022/024; Plugin 002 | +| 002 | [Indexed Viewer buffer geometry](002-indexed-buffer-geometry.md) | Accepted | 001; Typing structural inputs | +| 003 | [Viewer state and object selection](003-viewer-state-and-selection.md) | Accepted; implemented, local verification passed | 001 | +| 004 | [Transformations, refresh, and undo](004-transform-refresh-undo.md) | Accepted; implemented and verified | 001, 003 | +| 005 | [Annotations, measurements, and overlays](005-annotations-and-overlays.md) | Accepted, amended by 024/028 | 001, 002, 003 | +| 006 | [Public Viewer integration facade](006-viewer-integration-facade.md) | Accepted | 001, 003, 004, 005 | +| 007 | [Initial scope and verification](007-scope-and-verification.md) | Accepted | 001–006; Plugin 005 | +| 008 | [Serializable scene nodes and runtime adapters](008-scene-nodes-and-runtime-adapters.md) | Superseded by 013–014 | 001; verified round-trip regressions | +| 009 | [Explicit scene-state serialization fields](009-scene-state-fields.md) | Superseded in part by 013 | 008 | +| 010 | [Scene description, item bindings, and aggregation boundary](010-scene-description-and-item-bundling.md) | Accepted | 008, 009 | +| 011 | [Node-first scene construction and adapter lifetime](011-node-first-scene-adapters.md) | Superseded before acceptance | 008; 010 | +| 012 | [Explicit node-backed adapter state](012-explicit-node-backed-adapter-state.md) | Superseded before acceptance | 011 | +| 013 | [Hierarchy-only nodes and stable scene objects](013-hierarchy-nodes-and-stable-sceneobjects.md) | Accepted | Supersedes 008/009 placement; preserves 010 | +| 014 | [Context-keyed scene operation plugins](014-context-keyed-scene-operations.md) | Accepted | 013; replaces backend class registration | +| 015 | [Editable scene-object attributes](015-contextual-scene-form-contributions.md) | Accepted, amended | 013; respects 014 | +| 016 | [Contextual editable-attribute overrides and mutation](016-scene-form-field-bindings.md) | Accepted, amended | 015; respects 014 | +| 017 | [Lazy datastructure element-attribute tables](017-lazy-datastructure-attribute-tables.md) | Accepted; amended 2026-11-09 | 006; sidebar coordination | +| 018 | [Datastructure element-attribute editing](018-datastructure-attribute-editing.md) | Accepted | 017; 006/016 refresh ownership | +| 019 | [Configured Viewer identity](019-configured-viewer-identity.md) | Accepted | Independent | +| 020 | [Viewer configuration lifecycle and field audit](020-viewer-config-lifecycle-and-audit.md) | Accepted | 019; sidebar coordination with 017–018 | +| 021 | [Durable annotation ownership and schema](021-durable-annotation-ownership.md) | Accepted | 005; 010; 013–014; 028 | +| 022 | [Distance-dimension unit semantics](022-distance-dimension-units.md) | Accepted | 021; 027; 005; 020 | +| 023 | [Clean break for legacy Viewer annotations](023-annotation-clean-break.md) | Accepted | 021; 005 | +| 024 | [Measurement outcomes and persistence](024-measurement-outcomes-and-persistence.md) | Accepted | 005; 021–022; 026 | +| 025 | [Scale and legend overlay contracts](025-scale-and-legend-overlays.md) | Accepted; implementation note added 2026-11-09 | 005–006; 023 | +| 026 | [Measurement interaction and acquisition](026-measurement-interaction-and-acquisition.md) | Accepted; amended 2026-11-09 | 005; 024; 021–022; 003–004; 006; 027–028 | +| 027 | [Viewer measurement settings and UI](027-viewer-measurement-settings.md) | Accepted | 005; 020; 022; 026 | +| 028 | [Fixed and associative dimension anchors](028-dimension-anchor-modes.md) | Accepted | 005; 024; 021; 026 | +| 029 | [Persistent annotation collection and UI](029-persistent-annotation-collection-and-ui.md) | Accepted | 005; 010; 013; 021; 030 | +| 030 | [Always-visible persistent dimension rendering](030-always-visible-dimension-rendering.md) | Accepted | 005; 021; 024; 026; independent of 029 | +| 031 | [Spatial object deletion](031-spatial-object-deletion.md) | Accepted | 003–004; 010; 013; 028; annotation removal governed by 029 | +| 032 | [Three-domain Viewer sidebar](032-three-domain-viewer-sidebar.md) | Accepted; implemented and verified | Refines 003, 027, 029, and 031 | +| 033 | [Resizable Scene inspector and Details dialog](033-scene-inspector-details.md) | Proposed | Narrowly amends 032 | +| 034 | [Mesh-vertex snapping independent of vertex glyphs](034-hidden-vertex-snapping.md) | Proposed | Amends 026; preserves 028 | +| 035 | [Distance-dimension spatial layout](035-distance-dimension-spatial-layout.md) | Proposed | Extends 021, 028–030; preserves 022 | +| 036 | [Viewport text ownership and persistence](036-viewport-text-ownership-and-persistence.md) | Accepted; programmatic, non-persistent initial scope | Extends 005 and 025; optional use of 037 | +| 037 | [Optional annotation label backgrounds](037-annotation-label-backgrounds.md) | Proposed | Extends 021 and 029 | +| 038 | [Contextual Delete Selected](038-contextual-delete-selected.md) | Proposed | Amends 032; preserves 029 and 031 primitives | +| 039 | [Scene-owned Add menu](039-scene-add-menu.md) | Proposed | Consistent with 001, 013, 024, and 026 | +| 040 | [Default toolbar view shortcuts](040-default-toolbar-view-shortcuts.md) | Accepted; implementation pending | Extends 006; amends 020 default visibility | +| 041 | [Grid and Units System section](041-grid-and-units-system-section.md) | Accepted; implementation pending | Amends 027 and 032; preserves 020 | +| 042 | [Selected area and volume inspection](042-selected-area-and-volume-inspection.md) | Accepted; implementation pending | Uses 003–004; extends 006 and 024; coordinates with 027/041 | + +ADRs 008–010 were accepted on 2026-11-07. ADR 010 refines ADR 008's item store +into non-owning runtime bindings and keeps aggregation outside Scene. A +redesigned Session is the likely aggregate under separate future approval. +ADRs 015–016 were accepted and amended on 2026-11-08. Durable semantic fields +declare editability on their existing `SceneStateField`; only non-state +attributes use `__editable_attributes__`. Context overrides remain runtime-only, +and public `FormField`, item-target, and core refresh-hook semantics are removed. +ADRs 017–020 were accepted on 2026-11-08 and implemented in the required order +ADR 019, ADR 020, ADR 017, then ADR 018 so configuration and sidebar ownership +were established before the attribute tables were added. Local verification, +independent review, and hosted Viewer and framework checks passed. ADR 003 now +has one Viewer-owned ordered object selection, with all interaction paths +migrated and scene-local mutation APIs removed. Local verification, +independent review, the hosted Viewer matrix, and refreshed framework checks +passed. ADR 004 now provides atomic world-space multi-object transforms, four +explicit refresh categories, and a private Viewer-level reversible transform +transaction stack. Local verification and independent review passed; refreshed +hosted Viewer, core, and framework checks passed. +ADRs 021–028 were accepted on 2026-11-08. Durable annotations live +in `compas.scene` and load without Viewer. Persistent dimensions snapshot the +declared Viewer unit and precision without implicit conversion. `Tag`, +`ArrowOverlay`, their aliases, and their serialized dtype paths are removed +rather than preserved through a compatibility layer. Viewer distinguishes live +transient inspection from persistent dimension annotation; persistent +completion creates one `DistanceDimension` with independently fixed or +associative anchors. Both UI modes use snapping, associative acquisition never +silently falls back, and removed components make anchors explicitly unresolved. +ADR 027 adds one Units and Measurement tab with editable Viewer unit and display +precision plus read-only global COMPAS tolerance. It neither restores the old +root unit nor mutates global tolerance; snapping governs correctness. +ADR 025 adds one ordered Viewer overlay layer, a camera-target scale bar, and +an ordered categorical legend without serialization or picking. Its +2026-11-09 implementation note records the transparent widget canvas used to +keep transient painting outside the OpenGL renderer. ADR 026 adds one +nearest-eligible-discrete-point query and one-shot transient and persistent +tool lifecycles. Its 2026-11-09 amendment exposes the hovered object's discrete +point palette, a distinct click winner, and the retained first anchor. +Direct-use refinement adds bright square markers, an 18-logical-pixel radius, +and same-object footprint depth qualification. Only visible Point, +Mesh-vertex, and Graph-node guides are eligible; every invisible line, edge, +face, and surface target is disabled. ADR 030 keeps persistent dimensions +visible in a separate final render pass. ADRs 029 and 031 were accepted on +2026-11-09. ADR 029 moves durable annotations out of the spatial hierarchy, +adds a flat Annotations UI, and separates semantic annotation data from a +narrow durable dimension style. ADR 031 exposes existing spatial deletion +through the default Edit menu while preserving subtree, independent-data, +history-invalidation, and unresolved-association behavior. Their implementation +and refreshed hosted verification passed. Direct-use evidence subsequently +showed that the shared splitter and mixed detail surfaces make the sidebar +unstable and ambiguous. Accepted ADR 032 records the approved three-domain +replacement. Its implementation, documentation, local verification, framework +direct-source gate, independent review, hosted package CI, and exact +source-installed framework gate pass. diff --git a/initiatives/scene-viewer-visualisation/handoff.md b/initiatives/scene-viewer-visualisation/handoff.md new file mode 100644 index 0000000..c8e3272 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/handoff.md @@ -0,0 +1,115 @@ +# Scene, Viewer, and Visualisation Handoff + +Last updated: 2026-11-09 + +## Resume here + +Current phase: `Phase 3 ADRs 036 and 040–042 implemented and verified` + +The scene foundation, contextual settings, Viewer configuration and tables, +selection, and reversible transformations governed by Accepted ADRs 001–020 +are implemented and verified. The architectural watchpoint remains active: +the accepted `Data`/scene-state/extension model is authoritative, but concrete +contrary evidence should be brought back for an explicit amendment rather than +handled through speculative abstractions. + +The implemented Phase 3 foundation follows Accepted ADRs 021–028 and 030. +Core owns narrow durable text, arrow, and distance annotation data (ADR 021). +Persistent dimensions snapshot declared unit and precision without implicit +conversion (ADR 022). +Legacy `Tag` and `ArrowOverlay` names and serialized paths are removed without +aliases or legacy decoding (ADR 023). Live distance inspection is transient, +while explicit fixed and associative modes create durable dimensions +(ADRs 024 and 028). Viewer owns one ordered, non-serialized scale/legend layer +(ADR 025), nearest eligible discrete-point acquisition and one-shot +measurement tools (ADR 026), and the editable Units and Measurement +presentation settings with read-only global tolerance (ADR 027). Interactive +acquisition is limited to visible Point, Mesh-vertex, and Graph-node guides +with no invisible fallback. +Persistent dimensions use ADR 030's always-visible final pass. Accepted ADR +029 moves annotations out of the spatial hierarchy, adds a flat Annotations UI, +and owns a narrow durable dimension style. Accepted ADR 031 exposes the +existing spatial-object deletion command in the default Edit menu while +preserving subtree removal, independent data, transform-history invalidation, +and unresolved associative dimensions. Both implementations pass local package, +documentation, independent review, refreshed package CI, and the exact +source-installed framework gate. + +Direct-use feedback shows that the current stacked sidebar resizes unrelated +panels, presents independent spatial and annotation contexts ambiguously, hides +annotation naming, and does not provide consistent background-click or Escape +deselection. Accepted ADR 032 replaces it with stable Scene, Annotations, and +System domains. The implementation, documentation, 441-test Viewer suite, +Ruff, Pyright, strict MkDocs, framework direct-source gate, and independent +review pass. Hosted package and exact source-installed integration checks also +pass. + +Direct use then exposed a Qt lifecycle crash when an annotation visibility +checkbox rebuilt and deleted its own emitting tree item, plus repeated +`vertexsize` errors caused by treating an `(int, float)` field as integer-only +when its current value happened to be an integer. Both causes are fixed. The +Viewer now passes 445 tests, Ruff, Pyright, strict MkDocs, independent review, +hosted package CI, and the refreshed framework exact source-installed gate at +the revision below. + +Further direct use produced ADRs 033–039. They cover the resizable +Scene inspector and Details dialog, vertex snapping with ordinary glyphs +hidden, deterministic spatial dimension offsets, screen-pinned viewport text, +label backgrounds, contextual deletion, and moving the existing geometry Add +hierarchy under Scene. ADR 036 is Accepted and implemented with a screen-pinned, +non-persistent, programmatic-first contract. Accepted ADRs 040–042 add synchronized default-toolbar selectors, a +Grid and Units System section with consistent two-column field alignment and no +tolerance UI, and transient selected-object area and volume inspection. The +four implementations pass 501 Viewer tests, Ruff, formatting, Pyright, strict +MkDocs, independent review, the complete hosted Viewer matrix, and the exact +source-installed framework gate. +The other follow-ups remain Proposed and require explicit approval. + +The Core and refreshed Viewer candidate and framework gate are green at the +revisions below. Viewer restricts acquisition to visible discrete guides, +uses an 18-logical-pixel snap radius, proves the 4 × 3 diagonal equals 5, +renders persistent dimensions above geometry, and removes the Attributes tab +from the default sidebar while retaining opt-in custom use. Local package +verification, independent review, complete Viewer package CI, and the exact +framework source-installed gate pass. + +Exact candidate-artifact compatibility has not been run and must not be +inferred from source installation, package builds, or native probes. + +Read next: + +1. [Implementation plan](implementation-plan.md) +2. [Decision index](decisions/README.md) +3. [Proposal](proposal.md) +4. [Exploratory UI sketch](ui.md) + +## Exact candidates + +| Repository | Branch | Verified revision | Pull request | Status | +|---|---|---|---|---| +| `compas-dev/compas_framework` | `initiative/scene-viewer-visualisation` | `f7ac4ce02a3d20f17a5c10246f0e905cc9b9232e` | [7](https://github.com/compas-dev/compas_framework/pull/7) | Hosted contracts and exact source-installed gate passed | +| `compas-dev/compas` | `initiative/scene-viewer-visualisation` | `70aeb1e408772f0a84213c280658d4d594bf12ea` | [1540](https://github.com/compas-dev/compas/pull/1540) | Local verification, independent review, and hosted package CI passed | +| `compas-dev/compas_viewer` | `initiative/scene-viewer-visualisation` | `efbb7991c9f60aef2e8225813c5050190b5cfb0b` | [233](https://github.com/compas-dev/compas_viewer/pull/233) | Local and hosted package verification passed | +| `BlockResearchGroup/compas_model` | `c3-upgrade` | `83df4167f7ba1539ae205a837e0238afecc0a36b` | None | Compatibility consumer only; no source changes authorized | + +## Verification evidence + +| Layer | Status | Evidence | +|---|---|---| +| Local package checks | Passed | Core remains at its verified candidate. Viewer passed 501 tests, Pyright, Ruff, format, strict MkDocs, and independent review. The updated direct-source framework gate passed 15 tests with the exact-revision assertion skipped as designed. | +| Native interactive probes | Partial | Earlier native macOS captures showed the point palette, winner, retained anchor, live line and label without a `QPainter` warning or crash. Direct confirmation of 18-pixel attraction, discrete-only acquisition, and the final persistent-dimension pass remains pending. | +| Package CI | Passed | Core PR 1540 remains green. Viewer PR 233 passes build, coverage, policy, distributions, and all nine OS/Python quality jobs. | +| Framework integration | Passed | Framework PR 7 passes contracts and the exact source-installed Viewer gate. | +| Candidate artifacts | Not run | No compatibility claim is made for independently built candidate artifacts. Run this layer before artifact admission or release if that claim is required. | + +## Next tasks + +1. Reconfirm the new toolbar, Grid and Units layout, screen text, and scalar + inspection interactively. +2. Obtain explicit decisions on Proposed ADRs 033–035 and 037–039. + +## Approval gates + +- Adding model, session, notebook, or host packages requires explicit approval. +- Session aggregation and Viewer new/open/save conveniences remain future work. +- Do not merge or publish without explicit approval. diff --git a/initiatives/scene-viewer-visualisation/implementation-plan.md b/initiatives/scene-viewer-visualisation/implementation-plan.md new file mode 100644 index 0000000..6301986 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/implementation-plan.md @@ -0,0 +1,360 @@ +# Scene, Viewer, and Visualisation Implementation Plan + +## Status + +Architecture correction implemented and verified. ADRs 013–014 are Accepted +and supersede the adapter model. Accepted ADRs 015–016 govern +`SceneStateField`-backed editability, non-state editable declarations, and +contextual overrides; the superseded implementations were replaced and the +amended contract is independently approved and green in package and +exact-candidate integration CI. Accepted ADRs 017–020 are implemented, locally +verified, and independently approved in their required order: ADR 019, ADR 020, +ADR 017, then ADR 018. Their hosted verification passed. ADR 003 object +selection is now implemented, locally verified, independently approved, and +green in the hosted Viewer matrix and refreshed exact-candidate verification. +ADR 004 transformations, refresh, and undo is implemented, locally verified, +independently approved, and green in refreshed package and exact-candidate +verification. Accepted ADRs 021–028 are implemented, locally verified, +independently approved, and green in Core and Viewer package CI and the +framework exact source-installed gate. Phase 3 source implementation and +integration are complete. Exact candidate-artifact compatibility remains a +separate, unrun verification layer. + +## Dependency graph + +```text +ADR 001 --> ADR 008 --> ADR 009 --> ADR 010 + | + +--------> ADR 002 + +--------> ADR 003 --> ADR 004 + +ADRs 001–003 ----------> ADR 005 +ADRs 001, 003–005 -----> ADR 006 +ADRs 001–010 ----------> ADR 007 rollout gate +``` + +## Phase 0 — Scene ownership and serialization amendment + +Governing ADRs: 001, 008, 009, and 010. + +Status: implemented and verified after the Accepted ADR 013–014 correction. + +1. Add the verified Viewer round-trip regression and a minimal core adapter + test covering the constructor-before-attachment failure. Keep the actual + draft ModelViewer failure as evidence for its later redesign. +2. Audit Scene, SceneObject, Group, Viewer adapters, the draft model adapters, + and compatibility-only consumers against the proposed node/adapter split. +3. Implement the closed scene node/state schema, durable node GUIDs, + reference-only descriptions, runtime item bindings, and two-phase + deserialize/bind lifecycle. +4. Implement explicit MRO-composed extension field declarations; preserve + unknown namespaced extension state within the new schema. +5. Migrate core and Viewer adapters without serializing caches, selection, + construction commands, or runtime handles. Use the draft ModelViewer failure + as external regression evidence, not as behavior to preserve. +6. Document the separate future Session aggregation boundary without adding a + `SceneBundle`, URI resolver, asset registry, or Session implementation. + +Exit gate: the Viewer and minimal-adapter regressions pass; shared item +identity and durable node identity round-trip separately; scenes load without +a visualization backend; runtime adapters bind only after the complete +hierarchy exists; independently loaded items bind without copying; unresolved +references follow ADR 010; local/package quality, typing, docs, and artifact +checks pass. + +## Phase 1 — Boundaries and indexed geometry + +Governing ADRs: 001, 002, 007, 008, 009, and 010. + +Status: implemented and verified. + +1. Audit compatibility-only consumers for affected core scene contracts and + stop for approval if a required core change would break them. +2. Implement indexed `BufferGeometry` and convenience constructors in Viewer. +3. Migrate Viewer adapters and buffer assembly without expanding indexed data. +4. Add performance-regression assertions based on buffer/object counts rather + than unstable wall-clock thresholds. + +Exit gate: package-local source, typing, artifact, rendering-semantic, and +large-indexed-input evidence passes at exact candidate heads. + +## Phase 2 — State, selection, and transforms + +Governing ADRs: 001, 003, 004, 007, 008, and 009. + +Status: ADR 003 object selection is implemented, locally verified, and +independently approved on the verified ADR 013–014 scene foundation. The hosted +Viewer matrix and exact-candidate verification passed. ADR 004 transformations, +refresh, and undo is implemented, locally verified, and independently approved; +hosted package and exact-candidate verification passed. + +1. [Complete] Separate persistent Viewer configuration from transient Viewer + state. +2. [Complete] Implement the object-selection model and migrate viewport, + rectangle, tree, commands, renderer settings, and programmatic Viewer APIs. +3. [Complete] Remove scene-owned selection as a second authority and update + serialization/tests. Keep only the read-only scene-object projection needed + by rendering. +4. [Complete] Add atomic multi-object transform transactions, categorized + refresh, and the Viewer-level reversible transaction stack. +5. [Complete] Add the transform-selected command and undo/redo menu operations + after command/programmatic semantics passed. No transform-input UI was + invented; visual gizmo design remains a follow-up if it requires new + choices. + +Exit gate: all selection paths share one model; transform/undo tests cover +parents, batches, failures, world/local conversion, cached descendant bounds, +history invalidation, and buffer-update scope. The local gate passed; hosted +package and exact-candidate verification passed. + +## Contextual object-settings work + +Governing ADRs: 013, 014, 015, and 016. + +Status: implemented and independently verified under amended Accepted ADRs +015–016. + +Implementation record: + +1. Removed the public `FormField` API, item-target bindings, field refresh + modes, the parallel built-in Viewer field inventory, and the first separate + `EditableAttribute` implementation. +2. Added `editable` and the optional atomic data-only `update` callback to + `SceneStateField`, rejecting `update` when the field is not editable. +3. Reserved `__editable_attributes__` for non-state fields, initially `name` + and `opacity`, and composed both MRO sources through + `SceneObject.editable_attributes()` without duplicate subclass names. +4. Added graphics-free context contributions that filter, extend, or replace + entries through the same mapping with exact registry keys, deterministic + lexical contribution ordering, and conflict errors. +5. Migrated object settings to infer presentation and writability from the + normalized mapping and current values; represented-item parameters remain + in `ParameterForm`. +6. Applied default assignment or the optional synchronous data-side callback + atomically; Viewer conservatively rebuilds/redraws/refreshes after success + only. +7. Verified source composition, removal, conflicts, rollback, graphics-free + discovery, serialization exclusion, and multiple contexts. + +Exit gate: passed. Durable semantic attributes use `SceneStateField` as their +single source; non-state names are declared once; context plugins only modify the +normalized mapping; Viewer exclusively owns form UI and post-mutation refresh; +core exposes no form or refresh protocol; all applicable core, Viewer, and +framework integration checks pass. + +## Viewer identity and configuration lifecycle + +Governing ADRs: 019 and 020. + +Status: implemented, locally verified, independently approved, and passed in +hosted package and exact-candidate verification. + +Implementation record: ADR 019 was completed first. ADR 020 followed because +its schema validation and startup application depend on the accepted identity +contract. + +1. Applied validated startup configuration before Qt application/window + construction and connected title, icon, dimensions, and fullscreen. +2. Retained dataclasses, added path-aware validation, and separated startup + configuration from transient Viewer state. +3. Implemented the schema-2 field audit and migration/rejection behavior. +4. Verified identity, icons, fullscreen, status bar, every field disposition, + setup-only mutation semantics, serialization, and typed subclass extension. + +Local exit gate: passed. Startup identity and configuration are validated and +effective; removed fields are absent; transient state is not serialized. + +## Datastructure attribute tables + +Governing ADRs: 006, 017, and 018. + +Status: implemented, locally verified, independently approved, and passed in +hosted package and exact-candidate verification after ADRs 019–020 established +configuration and sidebar ownership. + +Implementation record: + +1. Added lazy Mesh and Graph element-attribute table models using declared + default mappings and singular domain APIs. +2. Added sidebar tabs only for domains with declared columns, preserved mapping + insertion order, and omitted sparse undeclared attributes. +3. Added supported scalar delegates, singular setter/unset mutation, effective + values, local selection, and conservative Viewer refresh. +4. Verified laziness, large/empty structures, value types, reset behavior, + atomic failure, and excluded first-version features. + +Local exit gate: passed. Tables are lazy, declared-domain-driven, Viewer-owned, +and verified without core API changes. The component is opt-in for custom +sidebars after the 2026-11-09 amendment to ADR 017; it is not part of the +built-in sidebar. + +The implementation order was ADR 019, ADR 020, ADR 017, then ADR 018. +Configuration work established startup and sidebar visibility ownership before +the tables followed. The architectural watchpoint recorded in the proposal +remains active during integration verification; concrete contrary evidence +must be brought back without inventing a replacement model speculatively. + +## Phase 3 — Annotations and overlays + +Governing ADRs: 001–005, 007, and 021–042. + +Status: the discrete-only acquisition, 18-pixel attraction, always-visible +persistent-dimension pass, and default-sidebar refinement are verified locally +and in hosted package and exact source-installed integration CI. ADRs 029 and +031 are implemented, independently reviewed, and verified locally across Core, +Viewer, the direct-source framework gate, and refreshed hosted CI. Direct-use +feedback identified a separate sidebar-composition defect; ADR 032 accepts +the replacement. Its implementation, documentation, local verification, +framework direct-source gate, and independent review pass; hosted refreshes +also pass. Interactive confirmation of the existing measurement refinement +remains pending. +ADR 023 provides the clean break with no aliases or legacy decoding. ADR 024 +separates transient inspection from +persistent dimensions. ADR 028 defines one dimension type with fixed and +associative anchors, snapping in both UI modes, no silent fallback, and +explicit unresolved references. ADRs 021–022 place narrow durable annotation +data in `compas.scene` and define persistent unit/precision snapshots without +implicit conversion. ADR 025 governs the ordered scale/legend overlay layer. +ADR 026 governs nearest eligible discrete-point acquisition and the one-shot +tool lifecycle. ADR 027 governs Viewer measurement presentation settings and the +Units and Measurement UI. ADR 030 governs the always-visible persistent +dimension pass. ADR 029 governs the approved separate annotation collection, +flat UI, and narrow dimension style. ADR 031 governs discoverable spatial +deletion without expanding history or cascading to annotations. + +1. [Complete] Inspect current `Tag`/`ArrowOverlay` serialized behavior and + approve the clean-break migration in ADR 023. +2. [Complete] Separate transient measurement inspection from persistent + dimension-annotation outcomes in ADR 024. +3. [Complete] Define fixed and associative persistent dimension anchors in ADR + 028. +4. [Complete] Approve core ownership/schema and persistent unit/precision + snapshots in ADRs 021–022. +5. [Complete] Approve Viewer unit/precision presentation and read-only global + tolerance UI in ADR 027. +6. [Complete] Implement world text, arrow, and distance annotation scene + items and Viewer render objects. +7. [Complete] Implement the approved transient inspection plus fixed/associative + persistent dimension snapping, preview, cancel, and completion. +8. [Complete] Implement the approved scale and legend screen overlays through + one Viewer overlay layer. +9. [Complete] Keep overlay dispatch outside the main scene render loop and + remove the obsolete Viewer annotation implementations. +10. [Complete] Restrict interactive acquisition to visible Point, + Mesh-vertex, and Graph-node guides with an 18-logical-pixel radius. +11. [Complete] Render persistent distance dimensions in ADR 030's final pass + without depth testing or depth writes. +12. [Complete and verified] Move persistent annotations out + of the spatial hierarchy, add a flat Annotations UI, and expose ADR 029's + narrow durable style. +13. [Complete and verified] Expose the existing + `viewer.delete_selected` command in the default Edit menu while preserving + subtree removal, independent data, transform-history invalidation, and + unresolved associative dimensions. +14. [Complete and verified] Replace the + mixed stacked sidebar with stable Scene, Annotations, and System domains; + add explicit annotation details and the approved global deselection + behavior. +15. [Blocked on ADR 033 approval] Add the Scene-local resizable hierarchy/detail + boundary and modal Details dialog; remove the inline description textbox. +16. [Blocked on ADR 034 approval] Make Mesh vertices measurable independently + of ordinary vertex-glyph visibility without adding edge or face snapping. +17. [Blocked on ADR 035 approval] Add deterministic world-space dimension + offsets from a captured plane normal, including extension lines and + explicit unresolved layout behavior. +18. [Complete and verified] Add screen-pinned viewport text as a Viewer + overlay through the existing programmatic overlay API; do not add an + incomplete interactive management surface or persistence until their + ownership is approved. +19. [Blocked on ADR 037 approval] Add the narrow optional label background and + padding presentation fields. +20. [Blocked on ADR 038 approval] Dispatch Delete Selected to the active Scene + or Annotations interaction domain without deleting both selections. +21. [Blocked on ADR 039 approval] Move the existing geometry Add hierarchy + under Scene while retaining measurement acquisition under Measure. +22. [Complete and verified] Establish Camera, Display, and Grid and Units + ownership; remove tolerance from Viewer UI; and align all System form + fields on one two-column layout. +23. [Complete and verified] Add the + visible-by-default Render Mode and View toolbar selectors synchronized + through existing state and commands. +24. [Complete and verified] Add transient selection-driven area and + volume inspection with exact supported transform scaling and explicit + unsupported cases. + +Exit gate: the ADR-029/031 candidate passed local Core, Viewer, documentation, +independent review, refreshed package CI, and exact source-installed framework +integration verification. Durable annotations round-trip and resolve through +fixed and associative anchors; transient +inspection and overlays do not serialize; only visible discrete guides produce +interactive anchors; fixed and associative acquisition do not fall back; and +persistent dimensions remain visible over scene geometry. Direct-use +confirmation of the refined attraction and presentation remains pending. +Independently built exact candidate artifacts were not installed together and +remain a separate unrun layer. The sidebar usability follow-up does not +invalidate those verified storage, rendering, or deletion contracts. + +ADR 032's replacement sidebar also passes its local package, documentation, +direct-source integration, independent-review, hosted package, and exact +source-installed integration gates. Direct-use regressions in annotation +visibility refresh and numeric field-type inference are fixed and verified in +hosted Viewer and framework CI. ADRs 036 and 040–042 are implemented and pass +the complete local and hosted Viewer gates plus the exact source-installed +framework gate. ADRs 033–035 and 037–039 remain Proposed and blocked. + +## Phase 4 — Public Viewer operations + +Governing ADRs: 001, 003–007. + +Status: partially satisfied by the implemented selection, transform, +measurement, annotation, overlay, menu, and documentation work. Audit the +remaining example and custom-dock scope before adding more API. + +1. Add public refresh, history, command/menu, dock, annotation, and overlay + operations required by approved Viewer-owned features. +2. Add direct script examples for indexed buffers, selection, transforms, + measurements, overlays, and one custom dock. +3. Update core and Viewer documentation using repository skills and + current MkDocs-compatible NumPy style. + +Exit gate: Viewer-owned tools and components use public Viewer operations and +package-local tests/docs/artifacts pass. + +## Later phase — compas_model redesign + +The current `ModelViewer` is a draft and is not migrated as a compatibility +exercise. A later approved design may replace its controller, hierarchy +projections, selection, caching, and UI composition. It should consume proven +core Scene and Viewer contracts where they fit, and propose additions only for +new demonstrated requirements. + +## Phase 5 — Framework integration and review + +Governing ADR: 007. + +1. [Complete] Verify installed core Scene and Viewer behavior at exact + candidates; keep the separate plugin initiative's model/viewer lifecycle + gate independent. +2. [Complete] Install exact candidate revisions and exercise the approved cross-package + runtime and typing contracts. +3. [In progress] Core and Viewer package CI, refreshed framework CI, and + independent code/documentation review passed. Exact candidate-artifact + verification has not run; decide whether it is applicable before admission. +4. [In progress] Findings are resolved and the handoff records evidence by + layer. Explicit merge approval remains pending. + +Exit gate: all applicable verification layers pass at recorded exact heads; +required unavailable evidence remains an explicit blocker. + +## Deferred work requiring new approval + +- sub-object or domain-component selection; +- ancestor/descendant group-transform semantics and advanced gizmos; +- angular, radial, area, or snapping measurement systems; +- a general overlay/plugin registry; +- console, terminal, Python/shell execution, assistant services, credentials, + or remote transports; +- `compas_session` reactive-state integration; and +- `compas_session` aggregation of data, one or more scenes, settings, and + history, including optional Viewer new/open/save conveniences; +- notebook, Rhino, Grasshopper, Blender, or other backend migrations. diff --git a/initiatives/scene-viewer-visualisation/inventory.md b/initiatives/scene-viewer-visualisation/inventory.md new file mode 100644 index 0000000..358c566 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/inventory.md @@ -0,0 +1,181 @@ +# Scene, Viewer, and Visualisation Inventory + +Inventory date: 2026-11-07. + +## Audited checkpoints + +| Repository | Branch | Exact head | State | +|---|---|---|---| +| `compas-dev/compas` | `remove-future` | `99b82a6673ff7d05c1c323c8921135c274993f11` | Clean | +| `compas-dev/compas_viewer` | `c3-upgrade` | `cf5a5195bda840a511319d6b7201978af68c15e3` | Clean | +| `BlockResearchGroup/compas_model` | `c3-upgrade` | `83df4167f7ba1539ae205a837e0238afecc0a36b` | Clean | +| `compas-dev/compas_session` | `c3-upgrade` | `e0bdd02aa8490248c6f2f36042651d8ebfc4442b` | Clean | +| `compas-dev/compas_framework` | `initiative/scene-viewer-visualisation` | Based on `e797d49f77ac32b65371497a21925a02b7d048d8` | Clean before initiative documents | + +## Core scene infrastructure + +`compas.scene.Scene` owns a serializable tree, item and scene-object stores, +context selection, hierarchy mutation, drawing traversal, and glTF conversion. +`SceneObject` combines serializable visual configuration with context-adapter +factory dispatch, local/world transformations, renderer identifiers, and +manual cache invalidation. + +The global context registry maps item types to adapter classes and uses plugin +registration. Its lifecycle offers `clear`, `before_draw`, and `after_draw`, +but no renderer capability, event, change-notification, reverse-picking, or +incremental-update contract. Core has no common indexed render-buffer type. + +Core tests cover context registration, hierarchy, transformations, +serialization, glTF conversion, and scene ownership. They do not cover +selection, interaction state, undo, incremental redraw, overlays, or batched +render data. The visualisation introduction is stale in its use of `data`, its +transformation explanation, and its assumptions about available adapters. + +## Viewer architecture + +`Viewer` coordinates the Qt application, `ViewerScene`, renderer, +`ViewerState`, commands, events, and UI as a singleton. `ViewerScene` fixes the +context to `"Viewer"`, maps picking colors, and directly coordinates renderer +and sidebar updates. `ViewerSceneObject` converts items into point, line, +front-face, and back-face channels and reaches the active viewer through that +singleton. + +`BufferManager` efficiently batches ordinary objects into shared GPU-oriented +buffers and can update transforms without rebuilding topology. However, +`BufferGeometry` accepts expanded point, line-vertex, and triangle-vertex +arrays rather than shared vertices plus edge or triangle indices. Examples and +several adapters therefore duplicate vertices manually. `TessellationObject` +and `PolygonalSurfaceObject` already demonstrate indexed paths, but there is no +uniform public convenience layer. + +Viewport and scene-tree multi-selection exist. Selection is stored as mutable +`is_selected` flags on scene objects and synchronized by imperative refresh +calls. There is no separate observable selection model, selection-change +event, complete rectangle-deselection path, or common programmatic mutation +contract. + +Programmatic transforms and efficient transform-buffer updates exist, but +there is no object gizmo, transformation command, multi-object transform UI, +or defined undo contract. `Tag` and `ArrowOverlay` provide useful text and +arrow primitives, but the renderer special-cases their concrete classes. No +measurement, dimension, scale-bar, legend, or general overlay contract exists. + +`ViewerState` provides observable dotted-path access to persistent +configuration. Selection, active tools, gestures, scene mutations, and command +execution live elsewhere. Commands and UI definitions offer useful extension +points, but there is no comparable public dock composition API and no console, +terminal, assistant, or safe execution boundary. + +## Draft model integration evidence + +`compas_model` owns backend-neutral model scene adapters, Viewer-specific +adapters, a `ModelViewer` controller, NumPy-based `RenderGeometry`, quality +settings, a revision-aware CPU cache, hierarchy projections, selection, +inspectors, and contact layers. + +The draft treats `Model.tree` and rendered `Scene` hierarchy as separate. +remain separate. `ModelViewer` constructs and indexes the scene projection, +but reaches into concrete viewer sidebar and renderer APIs. Structural changes +are reconciled through explicit rebuilds rather than an observed projection +contract. + +Draft model render geometry preserves separate indexed filled triangles and visible +line segments, but Viewer-specific adapters expand some arrays back to Python +lists. This makes buffer ownership and reusable conversion responsibilities +unclear. Package tests and documentation describe the current controller, +including multi-selection, visibility, caching, contacts, and offscreen viewer +integration. They establish implementation evidence, not public behavior that +this initiative must preserve. + +## Adjacent packages + +`compas_session` persists a generic core scene, data, settings, and undo/redo +history, but it is not a reactive viewer/UI state store. Notebook and CAD-host +packages consume core scene contracts under different runtime constraints. +They should be checked for compatibility with approved core changes, but +implementation migration would broaden the initial initiative materially. + +## Framework evidence + +Package-local core and Viewer tests provide substantial evidence. Draft model +tests provide additional coupling and regression evidence. The +framework repository currently has no installed cross-package scene/viewer +test. The plugin initiative separately requires a coordinated installed +model/viewer registry and lifecycle test; this initiative should coordinate +that gate rather than duplicate it. + +Focused reconnaissance results: + +- Core scene/plugin/glTF suite: 53 passed; one non-authoritative cache-write + warning because the checkout cache directory was not writable. +- Viewer selection/state/tessellation/tag/overlay suite: 35 passed offscreen. +- Draft model integration behavior was inspected from its existing tests and + build workflow; no new model tests were run and those tests are not treated + as preservation requirements. + +## Principal gaps and risks + +1. Durable scene state, persistent configuration, and transient interaction + state do not have explicit ownership boundaries. +2. Renderer identity has no common reverse mapping to scene objects or domain + elements. +3. Scene mutations, selection, renderer updates, and UI refreshes use + distributed imperative paths. +4. Raw indexed buffers lack a uniform public input and batching contract. +5. Overlay rendering is coupled to concrete Viewer classes. +6. The draft model controller demonstrates coupling to private or concrete + Viewer structure, but its shape is not an architectural constraint. +7. Core appearance serialization and glTF export do not cover all visual + settings consistently. +8. Per-object pickability conflicts with batching for large auxiliary data. +9. Singleton coupling makes state, commands, rendering, and scene behavior + harder to test independently. +10. Scope can expand rapidly across notebook and host adapters unless initial + and compatibility-only packages are explicit. + +## Scene state and serialization follow-up + +The current scene format is not ordinary `SceneObject` serialization. `Scene` +stores every domain item once by GUID and writes hierarchy nodes as an optional +item GUID, a free-form `settings` mapping, and children. Loading replays those +settings through `Scene.add`, which selects and constructs a runtime adapter +before the reconstructed hierarchy is complete. Multiple nodes can correctly +share one item, but node/adapter GUIDs are not preserved. + +Two regressions were reproduced at the audited heads: + +- a Viewer Box/ShapeObject translated by `[2, 0, 0]` reloads without its + transformation because `ViewerSceneObject.settings` replaces the base + mapping; `u=7`, `v=9`, and face color also reload as defaults; +- a `ModelViewer` scene fails to load because constructor replay uses + `ModelObject(add_elements=True)` before attachment, causing its child + creation to raise `RuntimeError: A detached scene object cannot own child + objects.` + +Unrestricted serialization introspection is unsafe. Concrete COMPAS objects +contain cycles, scene/item backreferences, GPU and picking identifiers, native +handles, lazy caches, derived NumPy buffers, and constructor commands. Public +properties can be computed or side-effecting, while persistent descriptor +values are often stored privately. Constructor signatures also lose inherited +state behind `**kwargs`. + +Introspection remains useful when applied to a closed declared schema: it can +validate readable fields, constructor compatibility, and editor metadata. It +cannot safely determine persistence from `__dict__`, public names, +annotations, properties, or constructor parameters alone. + +## Architecture questions + +1. Does core own only scene hierarchy and transformations, or also neutral + render primitives and change events? +2. Where do indexed buffers, picking identities, and reverse lookup live? +3. What observable state model unifies viewport, tree, and programmatic + selection without making UI state serializable scene data? +4. What change categories allow transform-only, style-only, geometry, and + hierarchy updates to remain efficient? +5. Which annotation and overlay objects are durable, transient, or both? +6. Which Viewer capabilities should be public because Viewer-owned tools and + components require them, independently of a draft domain controller? +7. What is the smallest safe extension boundary for docks, consoles, and + optional assistant integrations? +8. Which scene appearance semantics must serialization and glTF preserve? diff --git a/initiatives/scene-viewer-visualisation/objective.md b/initiatives/scene-viewer-visualisation/objective.md new file mode 100644 index 0000000..f1e0231 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/objective.md @@ -0,0 +1,113 @@ +# Scene, Viewer, and Visualisation Initiative + +## Objective + +Establish a simple, coherent, and scalable visualisation architecture across +COMPAS core scenes and `compas_viewer`. Users should be able to visualise large indexed datasets, +select and transform objects consistently, add measurements and annotations, +and extend the viewer UI without coupling durable scene data to a particular +renderer or Qt widget hierarchy. + +The initiative should clarify ownership before adding features. Core scene +data, renderer-facing geometry, persistent configuration, transient tool and +selection state, and domain-specific controllers must each have one clear +home and contract. + +## Questions to resolve + +1. Which data and behavior belong to backend-neutral `compas.scene`, the + viewer renderer, viewer application state, and package-specific adapters? +2. What indexed point, line, and triangle buffer contract supports efficient + visualisation without requiring heavyweight core geometry objects? +3. How should selection, element picking, hover, and multi-selection be shared + by the viewport, scene graph, and programmatic consumers? +4. What mutation and undo contract supports single- and multi-object + transformations? +5. Which annotations, measurements, scale indicators, legends, and overlays + are durable scene data, and which are transient tool or UI state? +6. How should persistent configuration be separated from reactive session, + tool, and UI state? +7. Which stable extension boundary can support docks, consoles, terminals, or + optional assistants without embedding those concerns in core scene data? +8. Which public Viewer operations are required by its own tools, UI components, + and independent future consumers? +9. Which local, package, framework-integration, and artifact evidence is + required for each approved wave? +10. How can scene nodes reference independently serialized `Data` objects while + leaving optional aggregation to a separately designed Session? + +## Design principles + +- Keep core scene infrastructure backend-neutral. +- Preserve indexed data and batch rendering where possible; do not expand a + large edge or triangle set into one Python object per primitive. +- Keep raw NumPy-compatible buffers valid inputs without forcing conversion + through COMPAS geometry or data objects. +- Keep referenced `Data` independently serializable and algorithm-ready; keep + optional Session aggregation separate from Scene. +- Separate durable scene state, persistent viewer configuration, and transient + interaction state. +- Provide one observable selection path for viewport, scene graph, and code. +- Prefer explicit, small data contracts over renderer-specific base classes or + speculative extension frameworks. +- Keep plugin discovery graphics-free and optional UI/runtime imports lazy. +- Reuse accepted tessellation, typing, plugin, and repository-modernisation + contracts rather than duplicating them. +- Make high-level convenience APIs simple while keeping ownership and + performance costs visible. + +## Refined initial scope + +- `compas`: scene hierarchy, scene-object identity and transformations, and + any approved backend-neutral contracts. +- `compas_viewer`: render buffers, GPU lifecycle, viewport interaction, + selection, overlays, commands, and UI state. +- `compas_framework`: installed cross-package verification. + +## Deliverables + +1. A verified cross-package inventory and approved architecture decisions. +2. Clear ownership and state boundaries across core scene and Viewer runtime + concerns. +3. Efficient convenience APIs for indexed points, edges, and triangles. +4. Consistent observable selection and transformation contracts. +5. An extensible annotation, measurement, and overlay foundation. +6. Public integration boundaries for Viewer tools, components, and optional + UI extensions. +7. Package-local and framework-level tests, examples, and documentation. +8. Reference-only scene descriptions with deterministic GUID binding and + unresolved-reference behavior, plus a clear boundary for a separately + approved Session aggregate. + +## Non-goals without a later scope decision + +- Replacing the core plugin manager or accepted geometry conversion APIs. +- Making Qt, OpenGL, or viewer-specific state a core COMPAS dependency. +- Implementing a chatbot service, shell execution engine, or remote transport + before the UI extension and security boundaries are approved. +- Migrating notebook, Rhino, Grasshopper, or Blender adapters in the initial + wave. +- Turning `compas_session` into a general reactive application store without + a separate persistence decision. +- Preserving the current draft `compas_model.ModelViewer` controller shape or + behavior. It is a later redesign consumer, not an architectural constraint. +- Adding modeling functionality to the viewer or duplicating domain data + structures in the scene graph. + +## Dependencies + +- Geometry-tessellation ADRs 022 and 024 govern transfer-oriented + `Tessellation`, producer conversions, and representation-preserving mesh + triangulation. +- Typing-alignment decisions govern structural NumPy-compatible inputs. +- Plugin-implementations decisions govern lightweight Viewer-context + registration and leave coordinated model/viewer lifecycle evidence open. +- Repository-modernisation decisions govern package workflows and artifact + verification. + +## Current status + +Reconnaissance and architecture are complete. ADRs 013–014 are Accepted and +the scene architecture correction may proceed within the approved initial +scope before Phase 2 resumes. The current draft `ModelViewer` is evidence and +a later redesign target, not a contract. diff --git a/initiatives/scene-viewer-visualisation/proposal.md b/initiatives/scene-viewer-visualisation/proposal.md new file mode 100644 index 0000000..fbab7c0 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/proposal.md @@ -0,0 +1,637 @@ +# Scene, Viewer, and Visualisation Proposal + +## Summary + +Keep `compas.scene` responsible for durable, backend-neutral scene content and +hierarchy. Put indexed render buffers, picking, selection, transient state, +tools, overlays, GPU synchronization, and UI composition in `compas_viewer`. +Expose only the public operations required by Viewer-owned tools and UI +components. Future integrations may consume that boundary after it is proven. + +The first implementation wave should establish these boundaries and deliver +object selection, efficient indexed geometry, multi-object transforms, +measurements, annotations, scale/legend overlays, and public dock/command +composition. It should not attempt a universal renderer API, a generic reactive +framework, sub-object editing, a shell, or host-application migration. + +ADRs 013–014 are Accepted, implemented, and verified. Session redesign and +Viewer/Session convenience operations remain later work. + +ADRs 015–016 authorize one normalized editable-attribute mapping composed from +editable `SceneStateField` entries, narrowly declared non-state attributes, +and runtime-only contextual overrides. The earlier `FormField` implementation +was replaced; the amended core and Viewer implementation is independently +approved and green in package and exact-candidate integration CI. + +ADRs 017–020 authorize lazy datastructure element-attribute tables and editing, +configured Viewer identity, and an explicit configuration lifecycle/field +audit. Their implementation is verified locally and in hosted Viewer and +framework CI. ADR 003 object selection is also fully verified. ADR 004 +transformations, categorized refresh, and Viewer-level transform history is +implemented, independently approved, and verified locally and in hosted core, +Viewer, and framework CI. + +ADRs 029 and 031 are implemented and verified locally and in hosted package +and exact source-installed integration CI. Direct use then exposed a sidebar +composition problem: one stacked splitter presents spatial, annotation, and +system contexts simultaneously, redistributes unrelated panels, and hides +annotation naming and global deselection behavior. Accepted ADR 032 responds +with three stable top-level domains while preserving separate spatial and +annotation selection models. Its implementation and local verification pass; +hosted package and exact source-installed integration verification also pass. + +## Direct-use follow-ups + +Direct use after ADR 032 identifies seven independent refinements. ADR 036 is +Accepted; ADRs 033–035 and 037–039 remain Proposed: + +- keep the three-domain root and introduce one stable Scene-local splitter; + remove the inline description textbox and expose its information through a + modal Details dialog; +- separate normal Mesh vertex glyph visibility from measurement acquisition by + rendering an invisible measurement-only vertex footprint; +- store a distance dimension's signed world-space offset and captured plane + normal as durable scene presentation, without storing a full construction + plane or changing the measured value; +- treat text pinned to a viewport location as a Viewer overlay in normalized + screen coordinates; initially expose only programmatic add/remove and keep + it outside Scene serialization unless a future Session/view-state decision + and management surface explicitly provide persistence and interactive + authoring; +- add only optional background color and logical-pixel padding to labels, + without introducing a typography or theme abstraction; +- make Delete Selected dispatch to the selection owned by the current + interaction domain, never to both spatial and annotation selections; and +- move the existing geometry creation hierarchy from top-level Add to + **Scene → Add**, while keeping measurement acquisition tools under Measure. + +The spatial dimension offset records only the plane normal needed for stable +layout. A reusable construction plane is an authoring aid and should be +designed separately rather than embedded in each dimension. Viewport text +persistence is likewise deferred to the separately proposed Session/view-state +boundary; configuration and Scene are not suitable owners. + +Further UI and measurement feedback produces three additional independent +proposals: + +- populate and show the default toolbar with synchronized Render Mode and View + selectors using the existing commands and Viewer state; +- replace Units and Measurement with Grid and Units, remove tolerance from the + Viewer UI without changing global COMPAS tolerance, and align every System + form on one two-column field layout; and +- add transient selection-driven area and volume inspection using represented + items' public scalar APIs and exact supported world-transformation rules, + without tessellation fallback or persistent annotations. + +If accepted together, establish the final System ownership and layout first, +then add the synchronized toolbar selectors, then add the independent area and +volume inspections. + +## Proposed three-domain sidebar amendment + +Replace the shared vertical splitter with one full-height tab widget containing +Scene, Annotations, and System. Scene owns the hierarchy and selected spatial +object details. Annotations owns the ordered annotation list and an explicit +selected-annotation detail form. System owns Camera, Display, and Units and +Measurement sections. Ordinary layouts provide stable master/detail space; +selection updates must not resize or rebuild unrelated domains. + +Spatial and annotation selections remain independent and can coexist. Tab +changes preserve both. Spatial picking changes only spatial selection and the +annotation list changes only annotation selection. An unmodified empty +viewport click clears both. Escape cancels an active measurement first and +otherwise clears both, while focused editors retain their local Escape +behavior. Annotation and spatial deletion remain separate operations. + +The annotation detail form makes Name editing explicit and presents Type and +the supported narrow dimension style without embedding those controls in the +list. Commands navigate with `sidebar.set_current_tab`, accepting only Scene, +Annotations, or System, and `sidebar.focus_system_section`, accepting only +Camera, Display, or Units and Measurement. Unsupported identifiers raise +`ValueError`; focusing a system section first activates System. The optional +datastructure inspector remains absent by default and routes to Scene when +explicitly configured. The existing Viewer configuration schema, Core Scene +schema, and optional sidebar component types remain unchanged. + +## New evidence requiring amendment + +- A Viewer Box/ShapeObject local translation `[2, 0, 0]` reloads as + `transformation is None` because `ViewerSceneObject.settings` replaces core + settings. A headless ShapeObject with `u=7`, `v=9`, and a face color reloads + with resolution defaults `16`, `16`, and the default face color. +- A ModelViewer scene fails while loading. Runtime factory dispatch constructs + `ModelObject` with its default `add_elements=True`; it calls `self.add` + before attachment and raises `RuntimeError: A detached scene object cannot + own child objects.` The original controller deliberately used + `add_elements=False` and `add_children=False`. Render settings and caches are + absent too, but caches are transient and should stay out of scene files. +- Shared item identity survives through the item GUID store. Scene-object GUIDs + do not survive, so they cannot yet serve as the durable identity assumed by + ADR 001. + +## Recommended architecture + +### Durable scene content and runtime adapters + +Core `Scene` remains the backend-neutral serializable hierarchy, but its +durable entries become scene-owned node/state value objects rather than runtime +`SceneObject` adapters. Nodes preserve their own GUID, optional item GUID, +local transformation, hierarchy, visibility, base appearance, and explicitly +declared extension state. Runtime item bindings preserve shared identity +without making Scene the owner or serialization container of those items. + +Runtime `SceneObject` instances bind a complete node and item to a chosen +visualization context. They are not serialized identities and may be created +only after deserialization has rebuilt the hierarchy and resolved the required +item bindings. +Their constructors do not populate hierarchy. Scene context is runtime binding +configuration; absence of a backend cannot prevent loading durable content. + +Durable node GUIDs are the stable boundary between scene content and Viewer +state. Renderer pick IDs remain short-lived Viewer mappings and are never +serialized. Unknown namespaced adapter state remains inactive but round-trips +without importing that adapter. + +Base node state uses a closed core schema. Additional durable fields use +explicit MRO-composed declarations. Introspection may validate declarations +and support editors, but `__dict__`, public properties, annotations, and +constructor parameters never define persistence automatically. + +### Scene descriptions, item bindings, and aggregation + +Durable scene nodes reference items by stable item GUID. Serialized `Scene` +contains the visual node hierarchy and state but does not require referenced +`Data` objects to live inside it. At runtime Scene binds already loaded objects +to those GUIDs without taking exclusive ownership; the same object remains +independently serializable and directly usable by algorithms. + +A separately loaded description may contain unresolved references. Its +hierarchy and node state remain inspectable, and callers can bind items later. +All nodes sharing one GUID resolve to the same bound instance. Item-dependent +adapter, draw, and packaging operations fail precisely when the required GUID +is unresolved. + +A redesigned `compas_session.Session` is the likely optional aggregate for +independently serialized data, one or more scene descriptions, settings, +history, and their shared identity. Its design and implementation require a +separate dependent decision and scope approval; this initiative does not add a +redundant one-scene `SceneBundle`. Scene remains usable without Session. + +Do not add URI resolution, filesystem search, network loading, or an asset +registry without a concrete future requirement. + +### Indexed render geometry + +`compas_viewer` owns one public indexed `BufferGeometry` contract: + +```python +geometry = BufferGeometry( + vertices=vertices, + points=point_indices, + edges=edge_indices, + triangles=triangle_indices, +) +``` + +Vertices accept the approved structural numerical input, including Python +sequences and NumPy arrays. Index channels are optional and retain their +connectivity. Convenience constructors cover the common direct cases: + +```python +BufferGeometry.from_points(vertices) +BufferGeometry.from_vertices_and_edges(vertices, edges) +BufferGeometry.from_vertices_and_triangles(vertices, triangles) +``` + +Construction normalizes each supplied channel once to the Viewer's required +NumPy dtype and validates only rank, column count, and index bounds. It does +not create `Mesh`, `PolygonalSurface`, `Tessellation`, or one object per +primitive. Styling stays on the scene object; a separate color-buffer decision +is required only when current uniform/per-item styling proves insufficient. + +Existing Viewer adapters should return indexed channels to the buffer manager +instead of expanding geometry. Geometry producers continue to use their approved +`to_tessellation` and `to_polygonal_surface` APIs; this Viewer contract does +not become a geometry-algorithm input. + +### Viewer state and selection + +Separate three state classes: + +| State | Owner | Persistence | +|---|---|---| +| Scene items, hierarchy, local transformations, durable appearance | `compas.scene` | Scene serialization | +| Viewer defaults, appearance, key bindings, layout preferences | `Viewer.config` | Viewer configuration | +| Selection, hover, active tool, gestures, and transient tool results | `Viewer.state` | Session-only | + +`Viewer.state.selection` is the one object-selection model. It stores ordered +scene-object GUIDs and exposes replace, add, remove, toggle, clear, and query +operations plus one change notification. Viewport picking, rectangle +selection, the scene tree, commands, and programmatic consumers all mutate +this model. +The current mutable and serialized `ViewerSceneObject.is_selected` path is +removed rather than retained as a second authority. + +Initial selection is object-level. The architecture reserves no generic +component-token schema; vertex, edge, face, or domain-element selection should +be proposed when a concrete editing workflow requires it. + +The state implementation should be a small Python model with a Qt bridge, not +a generic observable dictionary or third-party reactive framework. The +renderer reads selection state when updating its per-object settings buffer. + +### Transformations and undo + +Core transformations remain authoritative. Viewer exposes one public +multi-object transformation operation and uses it from code, commands, and a +future gizmo: + +```python +viewer.transform_objects(objects, transformation, space="world") +``` + +The initial operation applies one world-space delta to every selected object's +pre-operation world transformation. For each object, Viewer derives the new +local transformation from its parent world transformation. Ancestor/descendant +pairs in one request are rejected initially because applying the same delta to +both is ambiguous. Invalid targets leave all objects unchanged. + +Every successful call is one transaction containing the before and after local +transformations. A small Viewer undo stack handles these explicit reversible +transactions. Existing callback commands remain valid; only mutating commands +that implement the reversible transaction contract enter history. This does +not move general application/session history into Viewer or `compas_session`. + +Viewer retains explicit refresh operations for geometry, appearance, +transform, and hierarchy changes. The initial wave does not add a generic core +scene event bus: direct external mutation still requires the corresponding +public Viewer refresh call. This keeps synchronization costs explicit and +avoids making all core scene properties observable. + +### Annotations and overlays + +Use two explicit paths: + +- World-anchored annotations are serializable scene items with Viewer scene + adapters. The initial types are text annotation and distance dimension. A + distance dimension stores its two world anchors, display unit/precision, and + optional label override; its measured value is derived, not duplicated. +- Screen-space overlays are transient Viewer UI objects. The initial types are + scale indicator and legend. They are not scene items and do not participate + in scene serialization or picking unless a later requirement says so. + +Existing `Tag` and `ArrowOverlay` should be aligned with these two paths rather +than leaving concrete-class checks in the renderer. Do not introduce a +framework-wide overlay registry. One Viewer-owned world-annotation adapter +path and one Viewer overlay layer are sufficient for the approved types. + +The measurement tool owns temporary pointer/preview state in `Viewer.state`. +Completing a measurement creates a durable distance-dimension scene item; +cancelling it leaves no scene mutation. + +### Public Viewer operations + +Expose the small set of operations that Viewer-owned commands, tools, and UI +components need without coupling them to renderer or widget internals: + +- `viewer.scene` for durable content; +- `viewer.state.selection` for selection; +- `viewer.refresh_geometry`, `refresh_appearance`, `refresh_transform`, and + `refresh_hierarchy` for explicit synchronization; +- `viewer.transform_objects` and undo/redo; +- public command registration and menu placement; +- public dock addition/removal using Viewer component/widget content; and +- public annotation and overlay addition. + +These operations are justified and tested inside Viewer. They are not designed +around the current draft `compas_model.ModelViewer`. That controller may be +redesigned freely in a later consumer phase, at which point it can use the +small proven Viewer boundary or motivate a separately approved addition. + +A console, terminal, or assistant can later occupy a public dock and invoke +registered commands, but arbitrary code execution, shell access, credentials, +remote transports, and assistant policy are explicitly outside this wave and +require a security decision. + +## Alternatives and tradeoffs + +### Put render buffers in core + +Rejected for the initial wave. Core would gain renderer-oriented dtype, +channel, and update assumptions while notebook and host backends have not +demonstrated a shared contract. Structural geometry inputs and `Tessellation` +already cover neutral transfer needs; GPU-ready batching belongs to Viewer. + +### Use scene-object flags as selection state + +Rejected. It makes transient interaction state serializable, requires every UI +to poll/mutate objects, and leaves viewport, tree, domain controller, and +renderer synchronization distributed. + +### Add a universal reactive store and scene event bus + +Rejected for the initial wave. It adds a second application framework and +forces observability into core without established semantics for arbitrary +item mutation. Explicit state models and refresh categories satisfy current +requirements more transparently. + +### Make all annotations screen overlays + +Rejected. Measurements and world labels need world anchors, scene hierarchy, +transformations, and persistence. Conversely, scale indicators and legends are +view-dependent and should not become durable geometry. + +### Standardize every visualisation backend now + +Rejected. Notebook and CAD hosts are important compatibility consumers, but +their runtime and rendering models differ. The first wave should avoid breaking +their core scene contracts and record follow-up work only after the Viewer +design is proven. + +## Compatibility implications + +- Removing `ViewerSceneObject.is_selected` is a deliberate Viewer API break. + Commands, tree widgets, shaders, and tests migrate in one coordinated change; + no writable compatibility alias remains. +- `BufferGeometry` construction changes from expanded channel vertices to + shared indexed vertices. Current examples and adapters migrate together. + A deprecated parallel constructor is not proposed. +- Existing core scene serialization is not sufficient for the approved + architecture. ADRs 008–009 define a new explicit node schema without a + compatibility loader for existing scene files. ADR 010 separates + reference-only descriptions from a possible future Session aggregate; its + accepted replacement is implemented and verified. +- Current `Tag` and `ArrowOverlay` data may require a documented migration to + the accepted annotation/overlay types. Exact compatibility should be checked + against serialized fixtures before implementation; do not silently reinterpret + ambiguous old data. +- The current draft `compas_model.ModelViewer` behavior, hierarchy projections, + selection behavior, controller shape, and cache arrangement are not + compatibility requirements. Its failure remains evidence for the scene + reconstruction problem, and its redesign is deferred. +- Viewer plugin discovery remains graphics-free and function-local under the + accepted plugin ADRs. + +## Affected packages + +| Package | Responsibility | +|---|---| +| `compas` | Preserve scene identity, hierarchy, transformations, durable appearance, and serialization; clarify stale documentation. | +| `compas_viewer` | Implement indexed buffers, state/selection, transforms/history, annotations, overlays, facade, rendering, and UI. | +| `compas_model` | Later redesign consumer and regression evidence; no current draft controller behavior is preserved by this wave. | +| `compas_framework` | Pin exact candidates and verify installed cross-package scene, plugin, selection, transform, and buffer behavior. | + +`compas_session`, `compas_notebook`, Rhino, Grasshopper, and Blender are +compatibility-reviewed but not implementation targets in the initial wave. + +## Tests and examples + +### Core + +- Preserve scene serialization, shared-item identity, hierarchy, and local/ + world transformation tests. +- Add the verified Viewer transformation/ShapeObject settings regression. + Preserve the ModelViewer detached-child failure as evidence and cover its + core failure mode with a minimal adapter whose constructor must not run + during hierarchy deserialization; the draft controller itself is deferred. +- Preserve durable node GUIDs separately from shared item GUIDs and round-trip + unknown namespaced extension state without its runtime adapter. +- Load independently serialized items, bind them to reference-only scene + descriptions, preserve shared identity, and verify unresolved-reference + behavior without Session. +- Add regression coverage proving transient Viewer state is absent from core + scene data and serialization. +- Correct and test the core scene/visualisation guide against current APIs. + +### Viewer + +- Accept list and NumPy vertices/indices; verify shapes, bounds, dtypes, + non-mutation, and retained indices. +- Compare large indexed edge/triangle input with expected buffer counts and + assert it does not create one scene object per primitive. +- Exercise selection replacement/add/remove/toggle from viewport, tree, and + code through the same observable model. +- Verify renderer picking IDs resolve to scene GUIDs and are not serialized. +- Test world-space multi-object transforms, parent conversion, atomic failure, + undo/redo, and ancestor/descendant rejection. +- Test distance derivation, unit/precision formatting, tool cancel/complete, + annotation serialization, and transient overlay non-serialization. +- Test public dock/command composition without importing optional integrations + during plugin discovery. + +### Framework and later consumers + +- Use the current draft ModelViewer load failure as regression evidence for + two-phase scene reconstruction, not as a public behavior suite. +- Add an installed exact-candidate test for core Scene and Viewer contracts. +- Redesign and verify model integration only in a later approved consumer phase. +- Keep candidate-artifact evidence separate from source-build integration. + +Examples remain direct scripts and demonstrate, in order: + +1. vertices and edges; +2. vertices and triangles; +3. shared indexed geometry with selection; +4. multi-object transformation and undo; +5. distance measurement and world annotation; and +6. scale/legend overlays and a custom dock. + +## Dependency order + +```text +ADR 001 --> ADR 008 --> ADR 009 --> ADR 010 + | + +--------> ADR 002 + +--------> ADR 003 --> ADR 004 + +ADRs 001–003 ----------> ADR 005 +ADRs 001, 003–005 -----> ADR 006 +ADRs 001–010 ----------> ADR 007 rollout gate +``` + +Core geometry, typing, plugin, and repository-modernisation decisions remain +upstream constraints. Implementation starts only after all ADRs required for a +wave are Accepted. + +## Architecture correction after Phase 1 + +Implementation evidence invalidates the detached/bound adapter mechanism used +for the first implementation of ADRs 008–009. It duplicates provisional and +node state, changes GUID meaning at binding, and requires hidden attribute +interception. Removal and context replacement can expose stale values on old +adapter references. Backend class substitution adds another ambiguity: the +type returned for one scene entry depends on which visualization plugins are +installed and selected. + +The preferred correction assigns one purpose to each concept: + +- `SceneNode` stores only ordered hierarchy through a scene-object GUID; +- stable backend-neutral `SceneObject` values own item references, identity, + transformation, appearance, visibility, and semantic type-specific state; +- independently serialized `Data` items remain external and bind by GUID; and +- visualization backends register context-keyed `draw` and `clear` functions + rather than replacement scene-object classes. + +`scene.add(data, ...)` remains the primary convenience path and returns the +stable scene object. One node is allowed per scene object; repeated appearances +of one item use multiple scene objects. The scene-object GUID is the hierarchy +key, so there is no second durable node identity. A scene serializes stable +object records plus a hierarchy of GUID references and loads without any +backend installed. + +The general COMPAS plugin dispatcher cannot select a `draw` implementation +from an invocation's explicit visualization context. The preferred design does +not complicate it. Lightweight discovery plugins populate a small scene +operation registry keyed by `(context, scene-object type, operation)`. Runtime +buffers, host handles, picking state, and caches live outside durable objects. + +ADRs 011–012 record the unaccepted first node-first alternative. Accepted ADRs +013–014 record the selected design, which is now implemented and verified. + +## Accepted editable scene-object declarations + +Durable semantic fields use their existing `SceneStateField` as the single +source of persistence and editability. That field gains only `editable=False` +and an optional synchronous atomic data-side `update(owner, value) -> None` +callback; providing `update` while not editable is invalid. Ordinary mutation +uses `setattr`. + +`SceneObject.__editable_attributes__` is reserved for genuinely editable +non-state attributes, initially `name` and `opacity`. Its values are only +optional update callbacks. `SceneObject.editable_attributes()` composes both +sources base-to-derived into one ordered `name -> optional callback` mapping +without duplicating subclass state-field names. Core contains no labels, +editors, arbitrary data, form identifiers, refresh categories, or context +metadata. Viewer infers presentation and does not maintain a parallel built-in +field list or expose public `FormField` values. + +Graphics-free context plugins may extend, replace, or remove entries through +the same mapping. They compose general-to-specific by stable scene-object MRO. +Their key is `(context, stable SceneObject type, contribution ID)`. Within each +MRO specificity, contributions apply by lexical contribution ID while +preserving mapping insertion order. Duplicate exact registrations and +same-specificity edits or removals of one attribute are errors rather than +load-order overrides. Contributions and resolved mappings are runtime-only and +never serialized. + +After a successful mutation, Viewer exclusively decides whether to rebuild +render data, redraw, and refresh UI. Context plugins only modify neutral +editable-attribute declarations. Core contains no refresh callback, refresh +category, or context protocol. Failed mutation restores the control and +triggers no view refresh. + +The initial scope is only stable scene-object attributes in object settings. +Represented-item parameters remain on the existing `ParameterForm` path. The +amended ADRs explicitly supersede the earlier public `FormField`, item-target, +and field-level refresh design and the first uncommitted separate +`EditableAttribute` declaration design. The replacement is implemented and +verified. + +## Accepted datastructure element-attribute tables + +Viewer may add lazy `QAbstractTableModel` views for Mesh and Graph element +attributes without changing core. Domains and columns come from existing +`default_*_attributes` mappings and matching singular APIs. Default mapping +insertion order defines columns; sparse undeclared attributes are not scanned +or shown. Tabs exist only for domains with declared attributes. + +The accepted editing contract supports Boolean, integer, float, and text +defaults. Other types are read-only. Cells show effective values, mutate +through singular setters, and reset through singular unset operations. Table +selection remains local, and Viewer refreshes conservatively after successful +mutation. Default-schema editing, sparse-column discovery, batch editing, +undo, and viewport component selection remain outside the first version. + +## Accepted Viewer identity and configuration lifecycle + +The existing `WindowConfig.title` should consistently supply Qt application +name, display name, and window title. `icon=None` selects the packaged icon; +otherwise the icon is an absolute path. Identity and window behavior are +startup-only, fullscreen is honored, and configuration is applied before Qt +application construction. This identity decision is independent of schema +migration and unrelated field cleanup. + +Viewer should retain nested dataclasses and gain explicit path-aware +validation rather than Pydantic, arbitrary plugin dictionaries, or a reactive +configuration promise. Schema version 2 connects fullscreen and status-bar +visibility; removes `about`, obsolete sidebar fields, renderer `opacity`, and +the duplicated `display` group; removes root `unit` until a unit-aware workflow +has an approved owner and lifecycle; adds `ortho` to renderer view choices; and +keeps active `vectorsize`. Schema-1 migration drops known retired fields, +preserves retained values, and rejects unknown fields; schema 2 rejects +explicit retired fields. Typed Viewer subclasses may add typed dataclass +configuration fields with their own validation. Direct mutation is setup-time +only, replacing `viewer.config` is unsupported, and dotted-path `ViewerState` +access is transitional rather than an extension API. + +## Architectural watchpoint + +The user has reserved judgment on whether the overall relationship between +`Data`, durable scene state, and extension mechanisms is the final model. The +current Accepted ADRs remain authoritative and implementation should proceed +as specified. If implementation evidence exposes duplicated ownership, +non-transparent extension paths, forced representation changes, or another +concrete mismatch, bring that evidence back for an explicit amendment or new +decision. Do not preemptively reopen the accepted architecture or add a +speculative replacement model. + +## Decision record + +1. [ADR 001 — Ownership and state boundaries](decisions/001-ownership-boundaries.md) +2. [ADR 002 — Indexed Viewer buffer geometry](decisions/002-indexed-buffer-geometry.md) +3. [ADR 003 — Viewer state and object selection](decisions/003-viewer-state-and-selection.md) +4. [ADR 004 — Transformations, refresh, and undo](decisions/004-transform-refresh-undo.md) +5. [ADR 005 — Annotations, measurements, and overlays](decisions/005-annotations-and-overlays.md) +6. [ADR 006 — Public Viewer integration facade](decisions/006-viewer-integration-facade.md) +7. [ADR 007 — Initial scope and verification](decisions/007-scope-and-verification.md) +8. [ADR 008 — Serializable scene nodes and runtime adapters](decisions/008-scene-nodes-and-runtime-adapters.md) +9. [ADR 009 — Explicit scene-state serialization fields](decisions/009-scene-state-fields.md) +10. [ADR 010 — Scene description, item bindings, and aggregation boundary](decisions/010-scene-description-and-item-bundling.md) +11. [ADR 011 — Node-first scene construction and adapter lifetime](decisions/011-node-first-scene-adapters.md) +12. [ADR 012 — Explicit node-backed adapter state](decisions/012-explicit-node-backed-adapter-state.md) +13. [ADR 013 — Hierarchy-only nodes and stable scene objects](decisions/013-hierarchy-nodes-and-stable-sceneobjects.md) +14. [ADR 014 — Context-keyed scene operation plugins](decisions/014-context-keyed-scene-operations.md) +15. [ADR 015 — Editable scene-object attributes](decisions/015-contextual-scene-form-contributions.md) +16. [ADR 016 — Contextual editable-attribute overrides and mutation](decisions/016-scene-form-field-bindings.md) +17. [ADR 017 — Lazy datastructure element-attribute tables](decisions/017-lazy-datastructure-attribute-tables.md) +18. [ADR 018 — Datastructure element-attribute editing](decisions/018-datastructure-attribute-editing.md) +19. [ADR 019 — Configured Viewer identity](decisions/019-configured-viewer-identity.md) +20. [ADR 020 — Viewer configuration lifecycle and field audit](decisions/020-viewer-config-lifecycle-and-audit.md) +21. [ADR 021 — Durable annotation ownership and schema](decisions/021-durable-annotation-ownership.md) +22. [ADR 022 — Distance-dimension unit semantics](decisions/022-distance-dimension-units.md) +23. [ADR 023 — Clean break for legacy Viewer annotations](decisions/023-annotation-clean-break.md) +24. [ADR 024 — Measurement outcomes and persistence](decisions/024-measurement-outcomes-and-persistence.md) +25. [ADR 025 — Scale and legend overlay contracts](decisions/025-scale-and-legend-overlays.md) +26. [ADR 026 — Measurement interaction and acquisition](decisions/026-measurement-interaction-and-acquisition.md) +27. [ADR 027 — Viewer measurement settings and UI](decisions/027-viewer-measurement-settings.md) +28. [ADR 028 — Fixed and associative dimension anchors](decisions/028-dimension-anchor-modes.md) +29. [ADR 029 — Persistent annotation collection and UI](decisions/029-persistent-annotation-collection-and-ui.md) +30. [ADR 030 — Always-visible persistent dimension rendering](decisions/030-always-visible-dimension-rendering.md) +31. [ADR 031 — Spatial object deletion](decisions/031-spatial-object-deletion.md) +32. [ADR 032 — Three-domain Viewer sidebar](decisions/032-three-domain-viewer-sidebar.md) +33. [ADR 033 — Resizable Scene inspector and Details dialog](decisions/033-scene-inspector-details.md) +34. [ADR 034 — Mesh-vertex snapping independent of vertex glyphs](decisions/034-hidden-vertex-snapping.md) +35. [ADR 035 — Distance-dimension spatial layout](decisions/035-distance-dimension-spatial-layout.md) +36. [ADR 036 — Viewport text ownership and persistence](decisions/036-viewport-text-ownership-and-persistence.md) +37. [ADR 037 — Optional annotation label backgrounds](decisions/037-annotation-label-backgrounds.md) +38. [ADR 038 — Contextual Delete Selected](decisions/038-contextual-delete-selected.md) +39. [ADR 039 — Scene-owned Add menu](decisions/039-scene-add-menu.md) +40. [ADR 040 — Default toolbar view shortcuts](decisions/040-default-toolbar-view-shortcuts.md) +41. [ADR 041 — Grid and Units System section](decisions/041-grid-and-units-system-section.md) +42. [ADR 042 — Selected area and volume inspection](decisions/042-selected-area-and-volume-inspection.md) + +ADRs 013–016 are Accepted. ADRs 008–009 and 011–012 are superseded as recorded +in the decision index; ADR 010 remains Accepted with amended terminology. +The amended ADR 015–016 implementation is complete and verified; the +superseded `FormField` implementation was replaced. +ADRs 017–020 are Accepted and were implemented in order ADR 019, ADR 020, ADR +017, then ADR 018 so configuration and sidebar ownership were established +first. Local verification, independent review, and hosted verification passed. +ADR 003 is fully verified. ADR 004 is implemented, locally verified, and +independently approved; refreshed hosted core, Viewer, and framework +verification passed. + +ADRs 033–039 respond to direct-use feedback. ADR 036 is Accepted with a +screen-pinned, non-persistent, programmatic-first contract. ADRs 040–042 are +also Accepted. ADRs 033–035 and 037–039 remain Proposed and do not authorize +source changes. diff --git a/initiatives/scene-viewer-visualisation/ui.md b/initiatives/scene-viewer-visualisation/ui.md new file mode 100644 index 0000000..5196e94 --- /dev/null +++ b/initiatives/scene-viewer-visualisation/ui.md @@ -0,0 +1,66 @@ +# UI + +> **Status:** Exploratory design sketch. This file records possible UI ideas +> for discussion; it is not an accepted specification, implementation plan, or +> backlog. Individual ideas require reconciliation with the accepted ADRs and +> explicit approval before implementation. + +## Menu + +* File + * New Session + * --- + * Open Session + * Save Session + * Save As (Session) + * --- + * ? +* Edit + * Undo + * Redo + * --- + * Edit Data Parameters + * Edit Object Parameters + * ? +* Select(ion) (same as now) +* Measure +* Scene + * Clear Scene + * --- + * Load Scene + * Save Scene + * --- + * Add Geometry + * Add Datastructure + * --- + * ? +* View (same as now) +* Help + +## Sidebar + +* Section 1 + * Scene Tree + * Data store +* Section 2 + * Object: Properties of selected object(s) + * Camera + * Display + +In the scene tree, every node provides a link to a form with two tabs: one for the scene object, one for the data item. + +The tree uses icons to give an indication of the type of object. + +## Toolbar + +A fixed or floating toolbar provides toolbar buttons with often used tools: + +* Zoom? +* Selection? +* Screen capture? +* Measurements? + +## Other + +The entire UI config shoould be accessible somehwere as well. +Transformations using a gimball would be amazing. diff --git a/tests/test_package.py b/tests/test_package.py index b877fbd..483d510 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -57,6 +57,21 @@ def test_native_candidate_integration_runs_from_the_protected_initiative_branch( assert "inputs.manifest_path || '.github/candidates/native-linux-py312.json'" in workflow +def test_scene_candidate_integration_pins_exact_source_revisions(): + source = Path(__file__).parents[1] + core_requirements = (source / ".github" / "scene-candidates" / "core-requirements.txt").read_text() + viewer_requirements = (source / ".github" / "scene-candidates" / "viewer-requirements.txt").read_text() + workflow = (source / ".github" / "workflows" / "scene-candidate-integration.yml").read_text() + + assert "compas.git@a4cc38a4f54d147f1ff45e19673b32f089576e2f" in core_requirements + assert "compas_viewer.git@a4fe52e51f7254c13df9659f9a61dc22ebbc1daa" in viewer_requirements + assert "branches: [c3-upgrade]" in workflow + assert "core-requirements.txt" in workflow + assert "viewer-requirements.txt" in workflow + assert "--no-deps" in workflow + assert "source-installed-candidates" in workflow + + def test_framework_examples_page_is_link_oriented(): page = (Path(__file__).parents[1] / "docs" / "examples.md").read_text()