From dd553020b4d2a4634da1289518045db90374a2b1 Mon Sep 17 00:00:00 2001 From: tomvanmele Date: Mon, 30 Nov 2026 13:43:53 +0100 Subject: [PATCH 1/8] Qualify BRep JSON with candidate wheels and Rhino round trips --- .github/actionlint.yaml | 3 + .../brep-interchange-v1.schema.json | 342 ++++++++++++++++++ .github/brep-interchange/interchange.py | 184 ++++++++++ .../interchange_validation.py | 338 +++++++++++++++++ .github/brep-interchange/nurbs_checks.py | 305 ++++++++++++++++ .github/brep-interchange/nurbs_fixture.py | 160 ++++++++ .github/brep-interchange/nurbs_multispan.py | 146 ++++++++ .github/brep-interchange/nurbs_periodic.py | 125 +++++++ .github/brep-interchange/nurbs_pole.py | 84 +++++ .github/brep-interchange/nurbs_seam.py | 99 +++++ .github/brep-interchange/occ_adapter.py | 108 ++++++ .github/brep-interchange/occ_compound.py | 48 +++ .github/brep-interchange/occ_nurbs.py | 330 +++++++++++++++++ .github/brep-interchange/planar_cavity.py | 16 + .github/brep-interchange/planar_compound.py | 52 +++ .github/brep-interchange/rhino_adapter.py | 85 +++++ .github/brep-interchange/rhino_compound.py | 23 ++ .github/brep-interchange/rhino_nurbs.py | 102 ++++++ .github/brep-interchange/run_in_rhino.py | 80 ++++ .github/brep-interchange/run_interchange.py | 228 ++++++++++++ .../run_interchange_in_rhino.py | 14 + .github/brep-interchange/run_probe.py | 304 ++++++++++++++++ .../brep-interchange/run_return_in_rhino.py | 14 + .github/brep-interchange/test_interchange.py | 129 +++++++ .github/candidates/README.md | 60 +++ .github/candidates/brep_legacy_occ_v1.json | 1 + .github/candidates/candidate_brep_json.py | 113 ++++++ .github/scripts/run_rhino_brep_candidate.py | 138 +++++++ .../native-candidate-integration.yml | 41 ++- .github/workflows/rhino-brep-integration.yml | 85 +++++ 30 files changed, 3756 insertions(+), 1 deletion(-) create mode 100644 .github/actionlint.yaml create mode 100644 .github/brep-interchange/brep-interchange-v1.schema.json create mode 100644 .github/brep-interchange/interchange.py create mode 100644 .github/brep-interchange/interchange_validation.py create mode 100644 .github/brep-interchange/nurbs_checks.py create mode 100644 .github/brep-interchange/nurbs_fixture.py create mode 100644 .github/brep-interchange/nurbs_multispan.py create mode 100644 .github/brep-interchange/nurbs_periodic.py create mode 100644 .github/brep-interchange/nurbs_pole.py create mode 100644 .github/brep-interchange/nurbs_seam.py create mode 100644 .github/brep-interchange/occ_adapter.py create mode 100644 .github/brep-interchange/occ_compound.py create mode 100644 .github/brep-interchange/occ_nurbs.py create mode 100644 .github/brep-interchange/planar_cavity.py create mode 100644 .github/brep-interchange/planar_compound.py create mode 100644 .github/brep-interchange/rhino_adapter.py create mode 100644 .github/brep-interchange/rhino_compound.py create mode 100644 .github/brep-interchange/rhino_nurbs.py create mode 100644 .github/brep-interchange/run_in_rhino.py create mode 100644 .github/brep-interchange/run_interchange.py create mode 100644 .github/brep-interchange/run_interchange_in_rhino.py create mode 100644 .github/brep-interchange/run_probe.py create mode 100644 .github/brep-interchange/run_return_in_rhino.py create mode 100644 .github/brep-interchange/test_interchange.py create mode 100644 .github/candidates/brep_legacy_occ_v1.json create mode 100644 .github/candidates/candidate_brep_json.py create mode 100644 .github/scripts/run_rhino_brep_candidate.py create mode 100644 .github/workflows/rhino-brep-integration.yml diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 0000000..c1c2d8d --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,3 @@ +self-hosted-runner: + labels: + - rhino8 diff --git a/.github/brep-interchange/brep-interchange-v1.schema.json b/.github/brep-interchange/brep-interchange-v1.schema.json new file mode 100644 index 0000000..5030702 --- /dev/null +++ b/.github/brep-interchange/brep-interchange-v1.schema.json @@ -0,0 +1,342 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:compas:brep:interchange:1", + "title": "Proposed COMPAS BRep interchange, version 1", + "description": "Structural validation for the plain JSON boundary representation. Reference ranges, domain ordering, knot consistency, and topology require semantic validation.", + "type": "object", + "additionalProperties": false, + "required": ["schema", "version", "kind", "units", "tolerances", "components"], + "properties": { + "schema": { "const": "compas.brep.interchange" }, + "version": { "type": "integer", "const": 1 }, + "kind": { "enum": ["face", "solid", "compound"] }, + "units": { "type": "string", "minLength": 1 }, + "tolerances": { "$ref": "#/$defs/tolerances" }, + "components": { "type": "array" } + }, + "oneOf": [ + { + "properties": { + "kind": { "const": "face" }, + "components": { + "minItems": 1, + "maxItems": 1, + "items": { "$ref": "#/$defs/faceComponent" } + } + } + }, + { + "properties": { + "kind": { "const": "solid" }, + "components": { + "minItems": 1, + "maxItems": 1, + "items": { "$ref": "#/$defs/solidComponent" } + } + } + }, + { + "properties": { + "kind": { "const": "compound" }, + "components": { + "minItems": 2, + "items": { "$ref": "#/$defs/solidComponent" } + } + } + } + ], + "$defs": { + "positiveNumber": { + "type": "number", + "exclusiveMinimum": 0 + }, + "index": { + "type": "integer", + "minimum": 0 + }, + "degree": { + "type": "integer", + "minimum": 1 + }, + "point2": { + "type": "array", + "minItems": 2, + "maxItems": 2, + "items": { "type": "number" } + }, + "point3": { + "type": "array", + "minItems": 3, + "maxItems": 3, + "items": { "type": "number" } + }, + "interval": { + "description": "Increasing parameter interval.", + "type": "array", + "minItems": 2, + "maxItems": 2, + "items": { "type": "number" } + }, + "knots": { + "description": "Full, nondecreasing knot vector.", + "type": "array", + "minItems": 4, + "items": { "type": "number" } + }, + "weights": { + "type": "array", + "minItems": 2, + "items": { "$ref": "#/$defs/positiveNumber" } + }, + "tolerances": { + "type": "object", + "additionalProperties": false, + "required": ["model", "uv"], + "properties": { + "model": { "$ref": "#/$defs/positiveNumber" }, + "uv": { "$ref": "#/$defs/positiveNumber" } + } + }, + "component": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "vertices", "edges", "faces"], + "properties": { + "kind": { "enum": ["face", "solid"] }, + "vertices": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/point3" } + }, + "edges": { + "type": "array", + "items": { "$ref": "#/$defs/edge" } + }, + "faces": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/face" } + }, + "shells": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/shell" }, + "contains": { "properties": { "role": { "const": "outer" } } }, + "minContains": 1, + "maxContains": 1 + } + } + }, + "faceComponent": { + "$ref": "#/$defs/component", + "properties": { + "kind": { "const": "face" }, + "faces": { "maxItems": 1 } + }, + "not": { "required": ["shells"] } + }, + "solidComponent": { + "$ref": "#/$defs/component", + "properties": { "kind": { "const": "solid" } }, + "required": ["shells"] + }, + "edge": { + "type": "object", + "additionalProperties": false, + "required": ["vertices", "domain", "curve"], + "properties": { + "vertices": { + "type": "array", + "minItems": 2, + "maxItems": 2, + "items": { "$ref": "#/$defs/index" } + }, + "domain": { "$ref": "#/$defs/interval" }, + "curve": { "$ref": "#/$defs/curve3" } + } + }, + "face": { + "type": "object", + "additionalProperties": false, + "required": ["surface", "uv_bounds", "reversed", "loops"], + "properties": { + "surface": { "$ref": "#/$defs/surface" }, + "uv_bounds": { + "type": "array", + "minItems": 2, + "maxItems": 2, + "items": { "$ref": "#/$defs/interval" } + }, + "reversed": { "type": "boolean" }, + "loops": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/loop" }, + "contains": { "properties": { "role": { "const": "outer" } } }, + "minContains": 1, + "maxContains": 1 + } + } + }, + "shell": { + "type": "object", + "additionalProperties": false, + "required": ["role", "faces"], + "properties": { + "role": { "enum": ["outer", "inner"] }, + "faces": { + "type": "array", + "minItems": 1, + "uniqueItems": true, + "items": { "$ref": "#/$defs/index" } + } + } + }, + "loop": { + "type": "object", + "additionalProperties": false, + "required": ["role", "trims"], + "properties": { + "role": { "enum": ["outer", "inner"] }, + "trims": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/trim" } + } + } + }, + "trim": { + "oneOf": [ + { "$ref": "#/$defs/regularTrim" }, + { "$ref": "#/$defs/singularTrim" } + ] + }, + "regularTrim": { + "type": "object", + "additionalProperties": false, + "required": ["edge", "reversed", "domain", "curve"], + "properties": { + "edge": { "$ref": "#/$defs/index" }, + "reversed": { "type": "boolean" }, + "domain": { "$ref": "#/$defs/interval" }, + "curve": { "$ref": "#/$defs/curve2" } + } + }, + "singularTrim": { + "type": "object", + "additionalProperties": false, + "required": ["edge", "vertex", "domain", "curve"], + "properties": { + "edge": { "type": "null" }, + "vertex": { "$ref": "#/$defs/index" }, + "domain": { "$ref": "#/$defs/interval" }, + "curve": { "$ref": "#/$defs/curve2" } + } + }, + "curve2": { + "oneOf": [ + { + "$ref": "#/$defs/line", + "properties": { "points": { "items": { "$ref": "#/$defs/point2" } } } + }, + { + "$ref": "#/$defs/nurbsCurve", + "properties": { "points": { "items": { "$ref": "#/$defs/point2" } } } + } + ] + }, + "curve3": { + "oneOf": [ + { + "$ref": "#/$defs/line", + "properties": { "points": { "items": { "$ref": "#/$defs/point3" } } } + }, + { + "$ref": "#/$defs/nurbsCurve", + "properties": { "points": { "items": { "$ref": "#/$defs/point3" } } } + } + ] + }, + "line": { + "type": "object", + "additionalProperties": false, + "required": ["type", "points"], + "properties": { + "type": { "const": "line" }, + "points": { "type": "array", "minItems": 2, "maxItems": 2 } + } + }, + "nurbsCurve": { + "type": "object", + "additionalProperties": false, + "required": ["type", "degree", "knots", "points", "weights"], + "properties": { + "type": { "const": "nurbs" }, + "degree": { "$ref": "#/$defs/degree" }, + "knots": { "$ref": "#/$defs/knots" }, + "points": { "type": "array", "minItems": 2 }, + "weights": { "$ref": "#/$defs/weights" } + } + }, + "surface": { + "oneOf": [ + { "$ref": "#/$defs/plane" }, + { "$ref": "#/$defs/nurbsSurface" } + ] + }, + "plane": { + "type": "object", + "additionalProperties": false, + "required": ["type", "origin", "xaxis", "yaxis"], + "properties": { + "type": { "const": "plane" }, + "origin": { "$ref": "#/$defs/point3" }, + "xaxis": { "$ref": "#/$defs/point3" }, + "yaxis": { "$ref": "#/$defs/point3" } + } + }, + "nurbsSurface": { + "type": "object", + "additionalProperties": false, + "required": ["type", "degrees", "knots", "points", "weights", "periodic"], + "properties": { + "type": { "const": "nurbs" }, + "degrees": { + "type": "array", + "minItems": 2, + "maxItems": 2, + "items": { "$ref": "#/$defs/degree" } + }, + "knots": { + "type": "array", + "minItems": 2, + "maxItems": 2, + "items": { "$ref": "#/$defs/knots" } + }, + "points": { + "description": "Control points in points[v][u] order.", + "type": "array", + "minItems": 2, + "items": { + "type": "array", + "minItems": 2, + "items": { "$ref": "#/$defs/point3" } + } + }, + "weights": { + "description": "Control weights in weights[v][u] order.", + "type": "array", + "minItems": 2, + "items": { "$ref": "#/$defs/weights" } + }, + "periodic": { + "description": "Periodicity flags in U, V order.", + "type": "array", + "minItems": 2, + "maxItems": 2, + "items": { "type": "boolean" } + } + } + } + } +} diff --git a/.github/brep-interchange/interchange.py b/.github/brep-interchange/interchange.py new file mode 100644 index 0000000..e4d3387 --- /dev/null +++ b/.github/brep-interchange/interchange.py @@ -0,0 +1,184 @@ +"""Executable reference API for the proposed shared BRep interchange format.""" + +from copy import deepcopy +from math import dist + +from interchange_validation import SCHEMA +from interchange_validation import VERSION +from interchange_validation import validate +from planar_compound import compound_data +from planar_compound import solid_records + +_PLANAR = "compas.brep.planar-prototype" +_NURBS = "compas.brep.nurbs-prototype" +_COMPOUND = "compas.brep.compound-prototype" +_ADAPTERS = {_PLANAR: "adapter", _NURBS: "nurbs", _COMPOUND: "compound"} +_TOLERANCE = 1e-7 + + +def _require_units(units): + if units != "mm": + raise NotImplementedError("The reference adapters exchange millimetres.") + + +def _geometry_format(kind, surfaces): + if surfaces == {"plane"}: + return _PLANAR + if kind == "face" and surfaces == {"nurbs"}: + return _NURBS + raise NotImplementedError("The reference adapters support planar solids and individual NURBS faces.") + + +def _shared_component(record): + planar = record["schema"] == _PLANAR + kind = "solid" if record["solid"] else "face" + component = { + "kind": kind, + "vertices": record["vertices"], + "edges": record["edges"], + "faces": record["faces"], + } + if kind == "solid": + component["shells"] = record.get( + "shells", + [{"role": "outer", "faces": list(range(len(component["faces"])))}], + ) + for edge in component["edges"]: + if planar: + edge["curve"] = { + "type": "line", + "points": [list(component["vertices"][index]) for index in edge["vertices"]], + } + else: + edge["curve"]["type"] = "nurbs" + for face in component["faces"]: + face["uv_bounds"] = face.pop("domain") + if planar: + face["surface"] = {"type": "plane", **face.pop("plane")} + else: + face["surface"]["type"] = "nurbs" + face["surface"].setdefault("periodic", [False, False]) + for loop in face["loops"]: + for trim in loop["trims"]: + if planar: + trim["curve"] = {"type": "line", "points": trim.pop("uv")} + else: + trim["curve"]["type"] = "nurbs" + return component + + +def from_prototype_data(old, *, units="mm"): + """Translate the executable fixture adapters' records into the shared schema.""" + _require_units(units) + record = deepcopy(old) + schema = record.get("schema") + if schema == _COMPOUND: + records = solid_records(record) + elif schema in {_PLANAR, _NURBS}: + records = [record] + else: + raise ValueError("Unsupported fixture adapter schema.") + if any(item.get("version") != 1 or item.get("units") != units or item.get("tolerance") != _TOLERANCE for item in records): + raise ValueError("Unexpected fixture adapter version, units or tolerance.") + components = [_shared_component(item) for item in records] + data = { + "schema": SCHEMA, + "version": VERSION, + "units": units, + "tolerances": {"model": _TOLERANCE, "uv": _TOLERANCE}, + "kind": "compound" if schema == _COMPOUND else components[0]["kind"], + "components": components, + } + validate(data) + return data + + +def _require_linear_domain(domain, points): + if domain[0] != 0 or abs(domain[1] - dist(*points)) > _TOLERANCE: + raise NotImplementedError("Reference planar curves require length parameters beginning at zero.") + + +def _require_complete_curve(domain, curve): + degree = curve["degree"] + knots = curve["knots"] + if domain != [knots[degree], knots[-degree - 1]]: + raise NotImplementedError("Reference NURBS curves require their complete knot interval.") + + +def _check_uv_bounds(bounds, measured): + if any(abs(expected - actual) > _TOLERANCE for interval, extent in zip(bounds, measured) for expected, actual in zip(interval, extent)): + raise ValueError("Face uv_bounds do not match the trim extents.") + + +def _prototype_component(component): + kind = component["kind"] + vertices, edges, faces = (component[key] for key in ("vertices", "edges", "faces")) + schema = _geometry_format(kind, {face["surface"]["type"] for face in faces}) + planar = schema == _PLANAR + curve_type = "line" if planar else "nurbs" + for edge in edges: + curve = edge["curve"] + if curve.pop("type") != curve_type: + raise NotImplementedError("Reference edge geometry must match the planar or NURBS adapter.") + if planar: + points = [vertices[index] for index in edge["vertices"]] + if curve["points"] != points: + raise NotImplementedError("Reference planar edge endpoints must match the vertices exactly.") + _require_linear_domain(edge["domain"], points) + del edge["curve"] + else: + _require_complete_curve(edge["domain"], curve) + for face in faces: + face["domain"] = face.pop("uv_bounds") + surface = face["surface"] + del surface["type"] + if planar: + face["plane"] = face.pop("surface") + elif surface["periodic"] == [False, False]: + del surface["periodic"] + elif surface["periodic"] != [True, False]: + raise NotImplementedError("The reference NURBS adapters support periodicity in U only.") + for loop in face["loops"]: + for trim in loop["trims"]: + curve = trim["curve"] + if curve.pop("type") != curve_type: + raise NotImplementedError("Reference UV geometry must match the planar or NURBS adapter.") + if planar: + if trim["edge"] is None: + raise NotImplementedError("The reference planar adapter does not support singular trims.") + _require_linear_domain(trim["domain"], curve["points"]) + trim["uv"] = trim.pop("curve")["points"] + else: + _require_complete_curve(trim["domain"], curve) + if trim["edge"] is not None and trim["domain"] != edges[trim["edge"]]["domain"]: + raise NotImplementedError("Reference adapters require matching 3D-edge and UV-trim intervals.") + if planar: + endpoints = (point for loop in face["loops"] for trim in loop["trims"] for point in trim["uv"]) + _check_uv_bounds(face["domain"], [(min(axis), max(axis)) for axis in zip(*endpoints)]) + result = { + "schema": schema, + "version": 1, + "units": "mm", + "tolerance": _TOLERANCE, + "solid": kind == "solid", + "vertices": vertices, + "edges": edges, + "faces": faces, + } + if len(component.get("shells", ())) > 1: + result["shells"] = component["shells"] + return result + + +def to_prototype_data(data): + """Validate shared data and translate it into a supported fixture adapter record.""" + validate(data) + _require_units(data["units"]) + if data["tolerances"] != {"model": _TOLERANCE, "uv": _TOLERANCE}: + raise NotImplementedError("Reference adapters use model and UV tolerances of 1e-7.") + components = [_prototype_component(component) for component in deepcopy(data["components"])] + if data["kind"] == "compound": + if any(component["schema"] != _PLANAR or not component["solid"] for component in components): + raise NotImplementedError("The reference compound adapters require planar solid components.") + return compound_data(components) + return components[0] diff --git a/.github/brep-interchange/interchange_validation.py b/.github/brep-interchange/interchange_validation.py new file mode 100644 index 0000000..bdaf01f --- /dev/null +++ b/.github/brep-interchange/interchange_validation.py @@ -0,0 +1,338 @@ +"""Validate shared BRep JSON structure and indexed topology without a native kernel.""" + +from collections import defaultdict +from math import isclose +from math import isfinite + +SCHEMA = "compas.brep.interchange" +VERSION = 1 + + +def _require(condition, path, message): + if not condition: + raise ValueError(f"{path}: {message}") + + +def _record(value, path, fields=None): + _require(isinstance(value, dict), path, "expected a JSON object") + if fields is not None: + _require(value.keys() == set(fields.split()), path, f"expected fields {fields}") + return value + + +def _array(value, path, size=None): + _require(isinstance(value, list), path, "expected a JSON array") + if size is not None: + _require(len(value) == size, path, f"expected {size} entries") + return value + + +def _number(value, path): + _require( + type(value) is int or (type(value) is float and isfinite(value)), + path, + "expected a finite number", + ) + return value + + +def _positive(value, path): + _require(_number(value, path) > 0, path, "expected a positive number") + + +def _flag(value, path): + _require(type(value) is bool, path, "expected a boolean") + + +def _reference(value, size, path): + _require(type(value) is int and 0 <= value < size, path, "index out of range") + return value + + +def _coordinates(value, dimension, path): + for index, coordinate in enumerate(_array(value, path, dimension)): + _number(coordinate, f"{path}[{index}]") + + +def _interval(value, path): + _coordinates(value, 2, path) + _require(value[0] < value[1], path, "expected an ascending interval") + + +def _knots(knots, degree, count, path): + _require( + type(degree) is int and 1 <= degree < count, + path, + "degree must be positive and less than the control point count", + ) + values = _array(knots, path, count + degree + 1) + for index, value in enumerate(values): + _number(value, f"{path}[{index}]") + _require(values == sorted(values), path, "knots must be nondecreasing") + _require(values[degree] < values[count], path, "knot support must have positive length") + return values[degree], values[count] + + +def _weights(value, count, path): + for index, weight in enumerate(_array(value, path, count)): + _positive(weight, f"{path}[{index}]") + + +def _curve(curve, dimension, domain, path): + curve = _record(curve, path) + kind = curve.get("type") + if kind == "line": + _record(curve, path, "type points") + points = _array(curve["points"], f"{path}.points", 2) + else: + _require(kind == "nurbs", path, "expected a line or NURBS curve") + _record(curve, path, "type degree knots points weights") + points = _array(curve["points"], f"{path}.points") + _weights(curve["weights"], len(points), f"{path}.weights") + lower, upper = _knots(curve["knots"], curve["degree"], len(points), f"{path}.knots") + _require( + lower <= domain[0] < domain[1] <= upper, + path, + "effective domain falls outside the knot support", + ) + for index, point in enumerate(points): + _coordinates(point, dimension, f"{path}.points[{index}]") + + +def _surface(surface, path): + surface = _record(surface, path) + kind = surface.get("type") + if kind == "plane": + _record(surface, path, "type origin xaxis yaxis") + for key in ("origin", "xaxis", "yaxis"): + _coordinates(surface[key], 3, f"{path}.{key}") + xaxis, yaxis = surface["xaxis"], surface["yaxis"] + for key, axis in (("xaxis", xaxis), ("yaxis", yaxis)): + _require( + all(abs(value) <= 1.0 + 1e-9 for value in axis) and isclose(sum(value * value for value in axis), 1, rel_tol=0, abs_tol=1e-9), + f"{path}.{key}", + "expected a unit axis", + ) + _require( + abs(sum(x * y for x, y in zip(xaxis, yaxis))) <= 1e-9, + path, + "plane axes must be orthogonal", + ) + return + + _require(kind == "nurbs", path, "expected a plane or NURBS surface") + _record(surface, path, "type degrees knots points weights periodic") + degrees = _array(surface["degrees"], f"{path}.degrees", 2) + knots = _array(surface["knots"], f"{path}.knots", 2) + points = _array(surface["points"], f"{path}.points") + _require(points, f"{path}.points", "expected a control net") + count_u = len(_array(points[0], f"{path}.points[0]")) + weights = _array(surface["weights"], f"{path}.weights", len(points)) + for v, (row, weight_row) in enumerate(zip(points, weights)): + for u, point in enumerate(_array(row, f"{path}.points[{v}]", count_u)): + _coordinates(point, 3, f"{path}.points[{v}][{u}]") + _weights(weight_row, count_u, f"{path}.weights[{v}]") + periodic = _array(surface["periodic"], f"{path}.periodic", 2) + for axis, count in enumerate((count_u, len(points))): + degree, axis_knots = degrees[axis], knots[axis] + knot_path = f"{path}.knots[{axis}]" + lower, upper = _knots(axis_knots, degree, count, knot_path) + _flag(periodic[axis], f"{path}.periodic[{axis}]") + if periodic[axis]: + shift = count - degree + _require( + all(isclose(end - start, upper - lower, rel_tol=1e-9) for start, end in zip(axis_knots, axis_knots[shift:])), + knot_path, + "periodic knots must repeat at the active period", + ) + for key, net in (("points", points), ("weights", weights)): + rows = net if axis == 0 else zip(*net) + _require( + all(row[:degree] == row[-degree:] for row in rows), + f"{path}.{key}", + "periodic control rows must repeat the first degree-many entries", + ) + + +def _edge(edge, vertex_count, path): + edge = _record(edge, path, "vertices domain curve") + endpoints = _array(edge["vertices"], f"{path}.vertices", 2) + for index, vertex in enumerate(endpoints): + _reference(vertex, vertex_count, f"{path}.vertices[{index}]") + _interval(edge["domain"], f"{path}.domain") + _curve(edge["curve"], 3, edge["domain"], f"{path}.curve") + return endpoints + + +def _trim(trim, edges, vertex_count, path): + trim = _record(trim, path) + if trim.get("edge") is None: + _record(trim, path, "edge vertex domain curve") + pole = _reference(trim["vertex"], vertex_count, f"{path}.vertex") + endpoints = (pole, pole) + else: + _record(trim, path, "edge reversed domain curve") + edge = _reference(trim["edge"], len(edges), f"{path}.edge") + _flag(trim["reversed"], f"{path}.reversed") + endpoints = edges[edge][::-1] if trim["reversed"] else edges[edge] + _interval(trim["domain"], f"{path}.domain") + _curve(trim["curve"], 2, trim["domain"], f"{path}.curve") + return endpoints + + +def _face(face, edges, vertex_count, path): + face = _record(face, path, "surface uv_bounds reversed loops") + _surface(face["surface"], f"{path}.surface") + for axis, bounds in enumerate(_array(face["uv_bounds"], f"{path}.uv_bounds", 2)): + _interval(bounds, f"{path}.uv_bounds[{axis}]") + _flag(face["reversed"], f"{path}.reversed") + roles = [] + uses = defaultdict(list) + for loop_index, loop in enumerate(_array(face["loops"], f"{path}.loops")): + loop_path = f"{path}.loops[{loop_index}]" + loop = _record(loop, loop_path, "role trims") + _require( + loop["role"] in ("outer", "inner"), + loop_path, + "expected an outer or inner loop", + ) + roles.append(loop["role"]) + trims = _array(loop["trims"], f"{loop_path}.trims") + _require(trims, loop_path, "a loop requires at least one trim") + endpoints = [] + for index, trim in enumerate(trims): + endpoints.append(_trim(trim, edges, vertex_count, f"{loop_path}.trims[{index}]")) + if trim["edge"] is not None: + uses[trim["edge"]].append(trim["reversed"] != face["reversed"]) + for index, (_, end) in enumerate(endpoints): + _require( + end == endpoints[(index + 1) % len(endpoints)][0], + loop_path, + "trim endpoints must form a continuous closed loop", + ) + _require(roles.count("outer") == 1, path, "a face requires exactly one outer loop") + for orientations in uses.values(): + _require(len(orientations) <= 2, path, "an edge has more than two uses on a face") + if len(orientations) == 2: + _require( + orientations[0] != orientations[1], + path, + "paired seam trims must use opposite orientations", + ) + return uses + + +def _shells(shells, face_count, uses, path): + face_owners = {} + members = [] + roles = [] + for index, shell in enumerate(_array(shells, path)): + shell_path = f"{path}[{index}]" + shell = _record(shell, shell_path, "role faces") + _require( + shell["role"] in ("outer", "inner"), + shell_path, + "expected an outer or inner shell", + ) + roles.append(shell["role"]) + faces = _array(shell["faces"], f"{shell_path}.faces") + _require(faces, shell_path, "a shell requires at least one face") + for face in faces: + _reference(face, face_count, f"{shell_path}.faces") + _require( + face not in face_owners, + shell_path, + "a face belongs to more than one shell", + ) + face_owners[face] = index + members.append(set(faces)) + _require(roles.count("outer") == 1, path, "a solid requires exactly one outer shell") + _require(len(face_owners) == face_count, path, "shells must partition all solid faces") + + adjacent = defaultdict(set) + for incidences in uses.values(): + _require(len(incidences) == 2, path, "a shell edge requires two incidences") + (first, forward), (second, backward) = incidences + _require( + face_owners[first] == face_owners[second], + path, + "an edge joins different shells", + ) + _require( + forward != backward, + path, + "shell edge incidences must have opposite orientations", + ) + adjacent[first].add(second) + adjacent[second].add(first) + for index, faces in enumerate(members): + pending = [min(faces)] + visited = set() + while pending: + face = pending.pop() + if face not in visited: + visited.add(face) + pending.extend(adjacent[face] - visited) + _require(visited == faces, f"{path}[{index}]", "shell faces must be connected") + + +def _component(component, kind, path): + fields = "kind vertices edges faces shells" if kind == "solid" else "kind vertices edges faces" + component = _record(component, path, fields) + _require(component["kind"] == kind, path, f"expected a {kind} component") + vertices = _array(component["vertices"], f"{path}.vertices") + _require(vertices, path, "a component requires at least one vertex") + for index, vertex in enumerate(vertices): + _coordinates(vertex, 3, f"{path}.vertices[{index}]") + edges = [_edge(edge, len(vertices), f"{path}.edges[{index}]") for index, edge in enumerate(_array(component["edges"], f"{path}.edges"))] + faces = _array(component["faces"], f"{path}.faces") + if kind == "face": + _require(len(faces) == 1, path, "a face component contains exactly one face") + uses = defaultdict(list) + for face_index, face in enumerate(faces): + for edge, orientations in _face(face, edges, len(vertices), f"{path}.faces[{face_index}]").items(): + uses[edge].extend((face_index, orientation) for orientation in orientations) + _require(len(uses) == len(edges), path, "every edge must have a trim") + referenced_vertices = {vertex for edge in edges for vertex in edge} + referenced_vertices.update(trim["vertex"] for face in faces for loop in face["loops"] for trim in loop["trims"] if trim["edge"] is None) + _require( + len(referenced_vertices) == len(vertices), + f"{path}.vertices", + "each vertex must be referenced by an edge or singular trim", + ) + if kind == "solid": + _shells(component["shells"], len(faces), uses, f"{path}.shells") + + +def validate(data): + """Raise ValueError for malformed structure or invalid indexed topology.""" + data = _record(data, "$", "schema version units tolerances kind components") + _require(data["schema"] == SCHEMA, "$.schema", "unsupported BRep interchange schema") + _require( + type(data["version"]) is int and data["version"] == VERSION, + "$.version", + "unsupported BRep interchange version", + ) + units = data["units"] + _require(isinstance(units, str) and bool(units), "$.units", "expected a unit name") + tolerances = _record(data["tolerances"], "$.tolerances", "model uv") + for key in ("model", "uv"): + _positive(tolerances[key], f"$.tolerances.{key}") + kind = data["kind"] + _require( + kind in ("face", "solid", "compound"), + "$.kind", + "expected a face, solid or compound", + ) + components = _array(data["components"], "$.components") + if kind == "compound": + _require( + len(components) >= 2, + "$.components", + "a compound requires at least two solids", + ) + kind = "solid" + else: + _require(len(components) == 1, "$.components", "expected exactly one component") + for index, component in enumerate(components): + _component(component, kind, f"$.components[{index}]") diff --git a/.github/brep-interchange/nurbs_checks.py b/.github/brep-interchange/nurbs_checks.py new file mode 100644 index 0000000..ebed925 --- /dev/null +++ b/.github/brep-interchange/nurbs_checks.py @@ -0,0 +1,305 @@ +"""Check the restricted NURBS fixture against analytic and native evaluations.""" + +from collections import Counter +from math import dist +from math import isclose + +from nurbs_fixture import SCHEMA +from nurbs_fixture import TOLERANCE +from nurbs_fixture import curve_point +from nurbs_fixture import fixture_data +from nurbs_fixture import surface_point + +TRIM_SAMPLES = tuple(i / 8 for i in range(9)) + + +def _check(condition, message): + if not condition: + raise ValueError(message) + + +def _near(actual, expected, message): + deviation = dist(actual, expected) + _check(deviation <= TOLERANCE, f"{message} Deviation {deviation:.3g}.") + return deviation + + +def _parameter(domain, fraction): + return domain[0] + (domain[1] - domain[0]) * fraction + + +def _axis_samples(knots, fractions): + unique = sorted(set(knots)) + samples = list(unique[1:-1]) + for index in range(len(unique) - 1): + span = unique[index : index + 2] + samples.extend(_parameter(span, fraction) for fraction in fractions) + return sorted(samples) + + +def _check_curve(curve, reference): + _check(curve["degree"] == reference["degree"], "Unexpected NURBS curve degree.") + _check( + len(curve["points"]) == len(curve["weights"]) == len(reference["points"]), + "Unexpected curve control point or weight count.", + ) + _check(all(weight > 0 for weight in curve["weights"]), "Nonpositive curve weight.") + _near(curve["knots"], reference["knots"], "Curve knots changed.") + + +def _directed_vertices(edges, trim): + if trim["edge"] is None: + return trim["vertex"], trim["vertex"] + start, end = edges[trim["edge"]]["vertices"] + return (end, start) if trim["reversed"] else (start, end) + + +def check_nurbs(data, adapter=None, shape=None, *, reference=None): + """Validate the fixture payload and optionally sample its native geometry.""" + if reference is None: + reference = fixture_data() + _check( + ( + data["schema"], + data["version"], + data["units"], + data["tolerance"], + data["solid"], + ) + == (SCHEMA, 1, "mm", TOLERANCE, False), + "Unexpected NURBS schema, units, tolerance or solid flag.", + ) + vertices, edges, faces = (data[key] for key in ("vertices", "edges", "faces")) + _check( + len(vertices) == len(reference["vertices"]) and len(edges) == len(reference["edges"]) and len(faces) == 1, + "NURBS vertex, edge or face count changed.", + ) + reference_face = reference["faces"][0] + reference_trims = reference_face["loops"][0]["trims"] + reference_uses = Counter(trim["edge"] for trim in reference_trims if trim["edge"] is not None) + seam_pairs = sum(count == 2 for count in reference_uses.values()) + singular_trims = len(reference_trims) - sum(reference_uses.values()) + face = faces[0] + _check(face["reversed"] is True, "Expected reversed face orientation.") + (loop,) = face["loops"] + trims = loop["trims"] + _check( + loop["role"] == "outer" and len(trims) == len(reference_trims), + "Outer loop trim count changed.", + ) + regular_trims = [trim for trim in trims if trim["edge"] is not None] + edge_uses = Counter(trim["edge"] for trim in regular_trims) + _check( + sorted(edge_uses) == list(range(len(edges))) and sorted(edge_uses.values()) == sorted(reference_uses.values()), + "Edge use counts changed.", + ) + _check( + len({(trim["edge"], trim["reversed"]) for trim in regular_trims}) == len(regular_trims), + "Two seam trims must traverse their shared edge in opposite directions.", + ) + _check( + len(trims) - len(regular_trims) == singular_trims, + "Singular trim count changed.", + ) + u_bounds, v_bounds = face["domain"] + _near(u_bounds, reference_face["domain"][0], "Trimmed U bounds changed.") + _near(v_bounds, reference_face["domain"][1], "Trimmed V bounds changed.") + + surface = face["surface"] + reference_surface = reference_face["surface"] + _check(surface["degrees"] == reference_surface["degrees"], "Support degrees changed.") + periodic = surface.get("periodic", [False, False]) + _check( + periodic == reference_surface.get("periodic", [False, False]), + "Native support periodicity changed.", + ) + knots_u, knots_v = surface["knots"] + _near(knots_u, reference_surface["knots"][0], "Support U knots changed.") + _near(knots_v, reference_surface["knots"][1], "Support V knots changed.") + _check( + [len(row) for row in surface["points"]] == [len(row) for row in reference_surface["points"]], + "Expected points[v][u].", + ) + _check( + [len(row) for row in surface["weights"]] == [len(row) for row in reference_surface["weights"]], + "Expected weights[v][u].", + ) + weight_scale = surface["weights"][0][0] + _check(weight_scale > 0, "Nonpositive surface weight.") + for row, ref_row, weights, ref_weights in zip( + surface["points"], + reference_surface["points"], + surface["weights"], + reference_surface["weights"], + ): + for point, ref_point in zip(row, ref_row): + _near(point, ref_point, "Support control point changed.") + _near( + [weight / weight_scale for weight in weights], + [weight / reference_surface["weights"][0][0] for weight in ref_weights], + "Support weights changed.", + ) + + degree_u, degree_v = surface["degrees"] + u_knots = knots_u[degree_u:-degree_u] + v_knots = knots_v[degree_v:-degree_v] + u_samples = _axis_samples(u_knots, (0.17, 0.5, 0.86)) + v_samples = _axis_samples(v_knots, (0.19, 0.48, 0.82)) + if periodic[0]: + seam = u_knots[-1] + if seam_pairs: + _near(u_bounds, [u_knots[0], seam], "Shared seam must span one U period.") + u_samples.extend([u_knots[0], seam]) + else: + _check(u_bounds[0] < seam < u_bounds[1], "The trim must straddle the U seam.") + u_samples.extend( + [ + u_bounds[0], + (u_bounds[0] + seam) / 2, + seam, + (seam + u_bounds[1]) / 2, + u_bounds[1], + ] + ) + surface_error = 0.0 + for u in u_samples: + for v in v_samples: + expected = surface_point(reference_surface, u, v) + _near( + surface_point(surface, u, v), + expected, + "Serialized surface sample changed.", + ) + if adapter is not None: + error = _near( + adapter.sample_surface(shape, u, v), + expected, + "Native surface sample changed.", + ) + surface_error = max(surface_error, error) + + sequence = [] + trim_error = 0.0 + seam_crossings = 0 + edge_correspondence = {} + reference_starts = [curve_point(trim["curve"], trim["domain"][0]) for trim in reference_trims] + for trim_index, trim in enumerate(trims): + start, end = _directed_vertices(edges, trim) + _check( + 0 <= start < len(vertices) and 0 <= end < len(vertices), + "Edge vertex index out of range.", + ) + # In UV, both sides of the seam have distinct start points even + # when they meet the same topological vertex in 3D. + uv_start = curve_point(trim["curve"], trim["domain"][0]) + ref_index = min( + range(len(reference_trims)), + key=lambda index: dist(reference_starts[index], uv_start), + ) + ref_trim = reference_trims[ref_index] + ref_edge_id = ref_trim["edge"] + edge_id = trim["edge"] + _check( + (edge_id is None) == (ref_edge_id is None), + "Trim singularity changed.", + ) + edge = None + if edge_id is not None: + _check( + edge_correspondence.setdefault(edge_id, ref_edge_id) == ref_edge_id, + "Trims were assigned to the wrong shared edge.", + ) + edge = edges[edge_id] + ref_edge = reference["edges"][ref_edge_id] + _near(edge["domain"], ref_edge["domain"], "3D edge domain changed.") + _check_curve(edge["curve"], ref_edge["curve"]) + else: + _check("reversed" not in trim, "Singular trim must reference its pole alone.") + ref_start, ref_end = _directed_vertices(reference["edges"], ref_trim) + _near( + vertices[start], + reference["vertices"][ref_start], + "Trim start vertex changed.", + ) + _near( + vertices[end], + reference["vertices"][ref_end], + "Trim end vertex changed.", + ) + sequence.append((start, end, ref_index)) + _near(trim["domain"], ref_trim["domain"], "UV trim domain changed.") + _check_curve(trim["curve"], ref_trim["curve"]) + if periodic[0]: + ends_u = [curve_point(trim["curve"], parameter)[0] for parameter in trim["domain"]] + seam_crossings += min(ends_u) < seam < max(ends_u) + for fraction in TRIM_SAMPLES: + uv = curve_point(ref_trim["curve"], _parameter(ref_trim["domain"], fraction)) + xyz = surface_point(reference_surface, *uv) + _near( + curve_point(trim["curve"], _parameter(trim["domain"], fraction)), + uv, + "Serialized UV trim sample changed.", + ) + if edge is None: + _near(vertices[start], xyz, "Singular UV trim must collapse to its pole.") + else: + edge_fraction = 1.0 - fraction if trim["reversed"] else fraction + edge_point = curve_point(edge["curve"], _parameter(edge["domain"], edge_fraction)) + _near(edge_point, xyz, "Serialized edge disagrees with its UV trim.") + if adapter is not None: + native_uv, native_xyz = adapter.sample_trim(shape, 0, trim_index, fraction) + _near(native_uv, uv, "Native UV trim sample changed.") + trim_error = max( + trim_error, + _near(native_xyz, xyz, "Native 3D boundary sample changed."), + ) + native_surface = adapter.sample_surface(shape, *native_uv) + trim_error = max( + trim_error, + _near( + native_xyz, + native_surface, + "Native 3D boundary disagrees with its UV trim.", + ), + ) + _check( + len(set(edge_correspondence.values())) == len(edges) + and all(first[1] == second[0] and (first[2] + 1) % len(reference_trims) == second[2] for first, second in zip(sequence, sequence[1:] + sequence[:1])), + "Expected the original edge identities and cyclic trim order.", + ) + result = {"max_surface_error_mm": surface_error, "max_trim_error_mm": trim_error} + if periodic[0]: + _check( + seam_crossings == (0 if seam_pairs else 2), + "The trims must retain their relationship to the reference U seam.", + ) + if adapter is not None: + native_domain = adapter.native_u_domain(shape) + _near( + [native_domain[1] - native_domain[0]], + [u_knots[-1] - u_knots[0]], + "Native support period changed.", + ) + result.update( + canonical_seam_u=seam, + crossing_trims=seam_crossings, + native_u_domain=native_domain, + ) + if seam_pairs: + native_seams = adapter.native_seam_edges(shape) + _check(native_seams == seam_pairs, "Native paired seam edge count changed.") + result["native_seam_edges"] = native_seams + if singular_trims and adapter is not None: + native_singular = adapter.native_singular_trims(shape) + _check(native_singular == singular_trims, "Native singular trim count changed.") + result["native_singular_trims"] = native_singular + return result + + +def area_difference(source, target): + """Check independent native integrations of the same trimmed patch.""" + _check( + isclose(source, target, rel_tol=1e-7, abs_tol=1e-7), + "Native NURBS areas differ.", + ) + return abs(source - target) diff --git a/.github/brep-interchange/nurbs_fixture.py b/.github/brep-interchange/nurbs_fixture.py new file mode 100644 index 0000000..cb5436a --- /dev/null +++ b/.github/brep-interchange/nurbs_fixture.py @@ -0,0 +1,160 @@ +"""Analytic fixture for the trimmed rational NURBS interchange probe.""" + +from bisect import bisect_right +from math import comb + +SCHEMA = "compas.brep.nurbs-prototype" +TOLERANCE = 1e-7 + + +def _homogeneous(point, weight): + return [value * weight for value in point] + [weight] + + +def _euclidean(point): + return [value / point[-1] for value in point[:-1]] + + +def _blend(points, parameters): + for parameter in parameters: + points = [ + [a + parameter * (b - a) for a, b in zip(first, second)] + for first, second in zip(points, points[1:]) # noqa: RUF007 - Python 3.9. + ] + return points[0] + + +def _surface_net(surface): + return [[_homogeneous(point, weight) for point, weight in zip(row, weights)] for row, weights in zip(surface["points"], surface["weights"])] + + +def _fraction(interval, value): + return (value - interval[0]) / (interval[-1] - interval[0]) + + +def _evaluate(points, degree, knots, parameter): + if len(points) == degree + 1: + return _blend(points, [_fraction(knots, parameter)] * degree) + + # De Boor evaluation operates on one knot span in homogeneous space. + span = min(bisect_right(knots, parameter) - 1, len(points) - 1) + start = span - degree + values = points[start : span + 1] + for level in range(1, degree + 1): + for index in range(degree, level - 1, -1): + knot_index = start + index + lower = knots[knot_index] + upper = knots[knot_index + degree - level + 1] + weight = (parameter - lower) / (upper - lower) + values[index] = [a + weight * (b - a) for a, b in zip(values[index - 1], values[index])] + return values[-1] + + +def surface_point(surface, u, v): + """Evaluate a rational tensor-product surface, wrapping periodic axes.""" + du, dv = surface["degrees"] + knots_u, knots_v = surface["knots"] + periodic_u, periodic_v = surface.get("periodic", (False, False)) + if periodic_u: + u = _wrap(u, knots_u[du], knots_u[-du - 1]) + if periodic_v: + v = _wrap(v, knots_v[dv], knots_v[-dv - 1]) + rows = [_evaluate(row, du, knots_u, u) for row in _surface_net(surface)] + return _euclidean(_evaluate(rows, dv, knots_v, v)) + + +def _wrap(parameter, lower, upper): + if lower <= parameter <= upper: + return parameter + return lower + (parameter - lower) % (upper - lower) + + +def curve_point(curve, parameter): + """Evaluate a clamped rational curve in its knot interval.""" + points = [_homogeneous(point, weight) for point, weight in zip(curve["points"], curve["weights"])] + return _euclidean(_evaluate(points, curve["degree"], curve["knots"], parameter)) + + +def _restrict(surface, start, end, domain): + """Compose a rational Bézier surface with an affine UV line exactly.""" + du, dv = surface["degrees"] + u0, v0 = [_fraction(knots, value) for knots, value in zip(surface["knots"], start)] + u1, v1 = [_fraction(knots, value) for knots, value in zip(surface["knots"], end)] + # Restrict each axis by evaluating the Bézier blossom at its new ends. + restricted_u = [[_blend(row, [u0] * (du - i) + [u1] * i) for i in range(du + 1)] for row in _surface_net(surface)] + restricted = [[_blend(column, [v0] * (dv - j) + [v1] * j) for j in range(dv + 1)] for column in zip(*restricted_u)] + + # On the diagonal, a product of Bernstein basis functions combines + # into one Bernstein basis of degree du + dv. + degree = du + dv + poles = [[0.0] * 4 for _ in range(degree + 1)] + for i, column in enumerate(restricted): + for j, pole in enumerate(column): + k = i + j + factor = comb(du, i) * comb(dv, j) / comb(degree, k) + for coordinate, value in enumerate(pole): + poles[k][coordinate] += factor * value + return { + "degree": degree, + "knots": [domain[0]] * (degree + 1) + [domain[1]] * (degree + 1), + "points": [_euclidean(pole) for pole in poles], + "weights": [pole[-1] for pole in poles], + } + + +def fixture_data(): + """Define a curved patch with four oblique UV trims and exact 3D edges.""" + surface = { + "degrees": [1, 2], + "knots": [[2.0, 2.0, 5.0, 5.0], [-3.0, -3.0, -3.0, 1.0, 1.0, 1.0]], + "points": [ + [[0.0, 0.0, 0.0], [4.0, 0.2, 0.6]], + [[-0.4, 2.3, 1.9], [4.6, 2.0, 2.8]], + [[0.5, 5.0, -0.4], [5.1, 4.8, 1.1]], + ], + "weights": [[1.0, 1.2], [0.78, 1.45], [1.1, 0.9]], + } + uv = [[2.4, -2.5], [4.6, -2.1], [4.2, 0.25], [2.55, 0.55]] + domains = [[0.25, 2.5], [3.0, 7.0], [-4.0, -1.0], [0.5, 3.0]] + vertices = [surface_point(surface, *point) for point in uv] + edges, trims = [], [] + for index, domain in enumerate(domains): + end_index = (index + 1) % len(uv) + start, end = uv[index], uv[end_index] + edges.append( + { + "vertices": [index, end_index], + "curve": _restrict(surface, start, end, domain), + "domain": domain, + } + ) + trims.append( + { + "edge": index, + "reversed": False, + "curve": { + "degree": 1, + "knots": [domain[0], domain[0], domain[1], domain[1]], + "points": [start, end], + "weights": [1.0, 1.0], + }, + "domain": domain, + } + ) + return { + "schema": SCHEMA, + "version": 1, + "units": "mm", + "tolerance": TOLERANCE, + "solid": False, + "vertices": vertices, + "edges": edges, + "faces": [ + { + "surface": surface, + "domain": [[min(axis), max(axis)] for axis in zip(*uv)], + "reversed": True, + "loops": [{"role": "outer", "trims": trims}], + } + ], + } diff --git a/.github/brep-interchange/nurbs_multispan.py b/.github/brep-interchange/nurbs_multispan.py new file mode 100644 index 0000000..eff69f2 --- /dev/null +++ b/.github/brep-interchange/nurbs_multispan.py @@ -0,0 +1,146 @@ +"""Exact multi-span rational NURBS fixture with a curved UV trim.""" + +from math import comb + +from nurbs_fixture import SCHEMA +from nurbs_fixture import TOLERANCE +from nurbs_fixture import _blend +from nurbs_fixture import _euclidean +from nurbs_fixture import _fraction +from nurbs_fixture import _surface_net +from nurbs_fixture import surface_point + + +def _restrict_bezier(points, start, end): + degree = len(points) - 1 + return [_blend(points, [start] * (degree - index) + [end] * index) for index in range(degree + 1)] + + +def _surface_spans(surface): + u_min, u_knot, u_max = surface["knots"][0][2:5] + fraction = _fraction((u_min, u_max), u_knot) + first, second = [], [] + for row in _surface_net(surface): + # Insert the simple interior knot once to obtain two Bézier rows. + join = _blend(row[1:3], [fraction]) + first.append([*row[:2], join]) + second.append([join, *row[2:]]) + return (u_min, u_knot, u_max), (first, second) + + +def _span_edge(rows, u_domain, v_domain, uv): + """Compose a quadratic-by-linear homogeneous Bézier patch with a UV curve.""" + start = _fraction(u_domain, uv[0][0]) + end = _fraction(u_domain, uv[-1][0]) + lower, upper = (_restrict_bezier(row, start, end) for row in rows) + v_fractions = [_fraction(v_domain, point[1]) for point in uv] + trim_degree = len(uv) - 1 + degree = 2 + trim_degree + + # U is affine along each trim. The affine V field multiplies each of + # its quadratic U rows by the trim's degree-one or degree-two V polynomial. + poles = [[0.0] * 4 for _ in range(degree + 1)] + for i, (low, high) in enumerate(zip(lower, upper)): + for j, v in enumerate(v_fractions): + k = i + j + factor = comb(2, i) * comb(trim_degree, j) / comb(degree, k) + for coordinate, (low_value, high_value) in enumerate(zip(low, high)): + poles[k][coordinate] += factor * ((1.0 - v) * low_value + v * high_value) + return poles + + +def _edge_curve(surface, uv, domain): + u_knots, rows = _surface_spans(surface) + u_min, u_knot, u_max = u_knots + u_start, u_end = uv[0][0], uv[-1][0] + degree = 2 + len(uv) - 1 + fractions = [0.0, 1.0] + if min(u_start, u_end) < u_knot < max(u_start, u_end): + fractions.insert(1, _fraction((u_start, u_end), u_knot)) + + poles = [] + knots = [domain[0]] * (degree + 1) + for index in range(len(fractions) - 1): + start, end = fractions[index : index + 2] + restricted_uv = _restrict_bezier(uv, start, end) + # Each restriction belongs to one U span. Its endpoint on the + # interior knot is shared by the adjacent restrictions. + midpoint = (restricted_uv[0][0] + restricted_uv[-1][0]) / 2 + if midpoint < u_knot: + span_rows, span_domain = rows[0], (u_min, u_knot) + else: + span_rows, span_domain = rows[1], (u_knot, u_max) + segment = _span_edge(span_rows, span_domain, surface["knots"][1], restricted_uv) + if index: + poles.extend(segment[1:]) + knots.extend([domain[0] + (domain[1] - domain[0]) * start] * degree) + else: + poles.extend(segment) + knots.extend([domain[1]] * (degree + 1)) + return { + "degree": degree, + "knots": knots, + "points": [_euclidean(pole) for pole in poles], + "weights": [pole[-1] for pole in poles], + } + + +def fixture_data(): + """Define a reversed face whose curved UV boundary crosses an interior U knot.""" + surface = { + "degrees": [2, 1], + "knots": [[2.0, 2.0, 2.0, 3.5, 5.0, 5.0, 5.0], [-3.0, -3.0, 1.0, 1.0]], + "points": [ + [[0.0, 0.0, 0.0], [1.6, -0.15, 1.5], [3.0, 0.15, 0.9], [4.7, 0.45, 0.4]], + [[0.2, 4.0, 0.7], [1.7, 4.6, 2.1], [3.5, 4.25, 1.2], [5.0, 4.9, 0.2]], + ], + "weights": [[1.0, 0.8, 1.3, 1.0], [1.15, 1.35, 0.95, 1.25]], + } + uv = [[2.5, -2.0], [4.5, -2.0], [4.5, 0.5], [2.5, 0.5]] + bottom = [uv[0], [3.5, -2.75], uv[1]] + trim_points = [bottom, [uv[1], uv[2]], [uv[2], uv[3]], [uv[3], uv[0]]] + domains = [[0.25, 2.5], [3.0, 7.0], [-4.0, -1.0], [0.5, 3.0]] + vertices = [surface_point(surface, *point) for point in uv] + edges, trims = [], [] + for index, (points, domain) in enumerate(zip(trim_points, domains)): + pole_count = len(points) + edges.append( + { + "vertices": [index, (index + 1) % len(uv)], + "curve": _edge_curve(surface, points, domain), + "domain": domain, + } + ) + trims.append( + { + "edge": index, + "reversed": False, + "curve": { + "degree": pole_count - 1, + "knots": [domain[0]] * pole_count + [domain[1]] * pole_count, + "points": points, + "weights": [1.0] * pole_count, + }, + "domain": domain, + } + ) + return { + "schema": SCHEMA, + "version": 1, + "units": "mm", + "tolerance": TOLERANCE, + "solid": False, + "vertices": vertices, + "edges": edges, + "faces": [ + { + "surface": surface, + "domain": [ + [uv[0][0], uv[1][0]], + [_blend(bottom, [0.5, 0.5])[1], uv[2][1]], + ], + "reversed": True, + "loops": [{"role": "outer", "trims": trims}], + }, + ], + } diff --git a/.github/brep-interchange/nurbs_periodic.py b/.github/brep-interchange/nurbs_periodic.py new file mode 100644 index 0000000..7223b61 --- /dev/null +++ b/.github/brep-interchange/nurbs_periodic.py @@ -0,0 +1,125 @@ +"""Exact rational NURBS fixture with a trim that crosses a periodic seam.""" + +from math import floor + +from nurbs_fixture import SCHEMA +from nurbs_fixture import TOLERANCE +from nurbs_fixture import _blend +from nurbs_fixture import _euclidean +from nurbs_fixture import _fraction +from nurbs_fixture import _surface_net +from nurbs_fixture import surface_point +from nurbs_multispan import _restrict_bezier +from nurbs_multispan import _span_edge + +U_PERIOD = 8 + + +def _span_rows(net, span): + """Return the two quadratic Bézier rows for one uniform periodic span.""" + rows = [] + for row in net: + first, middle, end = [row[index % U_PERIOD] for index in range(span, span + 3)] + rows.append([_blend([first, middle], [0.5]), middle, _blend([middle, end], [0.5])]) + return rows + + +def _edge_curve(surface, uv, domain): + """Compose the support and trim exactly, splitting at the U seam.""" + net = _surface_net(surface) + u_start, u_end = uv[0][0], uv[-1][0] + degree = len(uv) + 1 + limits = [0.0, 1.0] + if min(u_start, u_end) < U_PERIOD < max(u_start, u_end): + limits.insert(1, _fraction((u_start, u_end), U_PERIOD)) + + poles = [] + knots = [domain[0]] * (degree + 1) + for index in range(len(limits) - 1): + start, end = limits[index : index + 2] + segment_uv = _restrict_bezier(uv, start, end) + span = floor((segment_uv[0][0] + segment_uv[-1][0]) / 2) + segment = _span_edge(_span_rows(net, span), (span, span + 1), surface["knots"][1], segment_uv) + if index: + join = domain[0] + (domain[1] - domain[0]) * start + knots.extend([join] * degree) + poles.extend(segment[1:]) + else: + poles.extend(segment) + knots.extend([domain[1]] * (degree + 1)) + return { + "degree": degree, + "knots": knots, + "points": [_euclidean(pole) for pole in poles], + "weights": [pole[-1] for pole in poles], + } + + +def fixture_data(): + """Define a reversed periodic face with a quadratic trim crossing U = 8.""" + ring = [ + [2.0, 0.0], + [1.5, 1.5], + [0.0, 2.0], + [-1.5, 1.5], + [-2.0, 0.0], + [-1.5, -1.5], + [0.0, -2.0], + [1.5, -1.5], + ] + weights = [1.0, 0.875, 1.125, 0.9375, 1.0625, 0.8125, 1.1875, 0.96875] + surface = { + "degrees": [2, 1], + "periodic": [True, False], + "knots": [list(range(-2, U_PERIOD + 3)), [0.0, 0.0, 2.0, 2.0]], + "points": [[[x, y, z] for x, y in ring + ring[:2]] for z in (0.0, 2.0)], + "weights": [weights + weights[:2], weights + weights[:2]], + } + + uv = [[7.5, 0.5], [8.5, 0.5], [8.5, 1.5], [7.5, 1.5]] + bottom = [uv[0], [8.0, 0.1], uv[1]] + trim_points = [bottom, [uv[1], uv[2]], [uv[2], uv[3]], [uv[3], uv[0]]] + ranges = [[0.25, 2.5], [3.0, 7.0], [-4.0, -1.0], [0.5, 3.0]] + edges, trims = [], [] + for index, (points, domain) in enumerate(zip(trim_points, ranges)): + count = len(points) + edges.append( + { + "vertices": [index, (index + 1) % len(uv)], + "curve": _edge_curve(surface, points, domain), + "domain": domain, + } + ) + trims.append( + { + "edge": index, + "reversed": False, + "curve": { + "degree": count - 1, + "knots": [domain[0]] * count + [domain[1]] * count, + "points": points, + "weights": [1.0] * count, + }, + "domain": domain, + } + ) + return { + "schema": SCHEMA, + "version": 1, + "units": "mm", + "tolerance": TOLERANCE, + "solid": False, + "vertices": [surface_point(surface, *point) for point in uv], + "edges": edges, + "faces": [ + { + "surface": surface, + "domain": [ + [uv[0][0], uv[1][0]], + [_blend(bottom, [0.5, 0.5])[1], uv[2][1]], + ], + "reversed": True, + "loops": [{"role": "outer", "trims": trims}], + }, + ], + } diff --git a/.github/brep-interchange/nurbs_pole.py b/.github/brep-interchange/nurbs_pole.py new file mode 100644 index 0000000..ccd50ff --- /dev/null +++ b/.github/brep-interchange/nurbs_pole.py @@ -0,0 +1,84 @@ +"""Exact rational spherical patch with a singular UV trim at its north pole.""" + +from math import sqrt + +from nurbs_fixture import SCHEMA +from nurbs_fixture import TOLERANCE + + +def _curve(points, weights): + count = len(points) + return { + "degree": count - 1, + "knots": [0.0] * count + [1.0] * count, + "points": points, + "weights": weights, + } + + +def fixture_data(): + """Define one eighth of a radius-two sphere as a rational NURBS face.""" + radius = 2.0 + domain = [0.0, 1.0] + angular_points = [(1.0, 0.0), (1.0, 1.0), (0.0, 1.0)] + meridian_points = [(0.0, radius), (radius, radius), (radius, 0.0)] + arc_weights = [1.0, sqrt(0.5), 1.0] + points = [[[radial * x, radial * y, z] for x, y in angular_points] for radial, z in meridian_points] + weights = [[v * u for u in arc_weights] for v in arc_weights] + knots = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0] + surface = { + "degrees": [2, 2], + "knots": [knots, knots], + "points": points, + "weights": weights, + } + + edges = [ + { + "vertices": [0, 2], + "curve": _curve([row[-1] for row in points], [row[-1] for row in weights]), + "domain": domain, + }, + { + "vertices": [1, 2], + "curve": _curve(points[-1], weights[-1]), + "domain": domain, + }, + { + "vertices": [0, 1], + "curve": _curve([row[0] for row in points], [row[0] for row in weights]), + "domain": domain, + }, + ] + uv_corners = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]] + trim_uses = [ + {"edge": None, "vertex": 0}, + {"edge": 0, "reversed": False}, + {"edge": 1, "reversed": True}, + {"edge": 2, "reversed": True}, + ] + trims = [ + { + **use, + "curve": _curve([start, end], [1.0, 1.0]), + "domain": domain, + } + for use, start, end in zip(trim_uses, uv_corners, uv_corners[1:] + uv_corners[:1]) + ] + return { + "schema": SCHEMA, + "version": 1, + "units": "mm", + "tolerance": TOLERANCE, + "solid": False, + "vertices": [points[0][0], points[-1][0], points[-1][-1]], + "edges": edges, + "faces": [ + { + "surface": surface, + "domain": [domain, domain], + "reversed": True, + "loops": [{"role": "outer", "trims": trims}], + }, + ], + } diff --git a/.github/brep-interchange/nurbs_seam.py b/.github/brep-interchange/nurbs_seam.py new file mode 100644 index 0000000..b6ee9d1 --- /dev/null +++ b/.github/brep-interchange/nurbs_seam.py @@ -0,0 +1,99 @@ +"""Exact periodic face with two UV trims on one shared 3D seam edge.""" + +from nurbs_fixture import SCHEMA +from nurbs_fixture import TOLERANCE +from nurbs_fixture import _blend +from nurbs_fixture import _euclidean +from nurbs_fixture import _fraction +from nurbs_fixture import _surface_net +from nurbs_fixture import surface_point +from nurbs_periodic import U_PERIOD +from nurbs_periodic import _span_rows +from nurbs_periodic import fixture_data as periodic_data + + +def _closed_iso_curve(surface, v): + """Build a clamped rational isocurve over one full period.""" + net = _surface_net(surface) + fraction = _fraction(surface["knots"][1], v) + poles = [] + for span in range(U_PERIOD): + lower, upper = _span_rows(net, span) + segment = [_blend([start, end], [fraction]) for start, end in zip(lower, upper)] + # Consecutive Bézier spans share the knot vertex in homogeneous space. + poles.extend(segment[1:] if poles else segment) + return { + "degree": 2, + "knots": [0] + [knot for knot in range(U_PERIOD + 1) for _ in range(2)] + [U_PERIOD], + "points": [_euclidean(pole) for pole in poles], + "weights": [pole[-1] for pole in poles], + } + + +def _line_curve(start, end, domain): + return { + "degree": 1, + "knots": [domain[0], domain[0], domain[1], domain[1]], + "points": [start, end], + "weights": [1.0, 1.0], + } + + +def fixture_data(): + """Define a full-period side face with distinct trims on both sides of its seam.""" + surface = periodic_data()["faces"][0]["surface"] + v_lower, v_upper = 0.25, 1.5 + u_domain, v_domain = [0.0, float(U_PERIOD)], [v_lower, v_upper] + lower = surface_point(surface, 0.0, v_lower) + upper = surface_point(surface, 0.0, v_upper) + edges = [ + { + "vertices": [0, 0], + "curve": _closed_iso_curve(surface, v_lower), + "domain": u_domain, + }, + { + "vertices": [0, 1], + "curve": _line_curve(lower, upper, v_domain), + "domain": v_domain, + }, + { + "vertices": [1, 1], + "curve": _closed_iso_curve(surface, v_upper), + "domain": u_domain, + }, + ] + uv_corners = [ + [0.0, v_lower], + [U_PERIOD, v_lower], + [U_PERIOD, v_upper], + [0.0, v_upper], + ] + trims = [] + for index, (edge, reversed_trim) in enumerate(((0, False), (1, False), (2, True), (1, True))): + domain = edges[edge]["domain"] + trims.append( + { + "edge": edge, + "reversed": reversed_trim, + "curve": _line_curve(uv_corners[index], uv_corners[(index + 1) % 4], domain), + "domain": domain, + } + ) + return { + "schema": SCHEMA, + "version": 1, + "units": "mm", + "tolerance": TOLERANCE, + "solid": False, + "vertices": [lower, upper], + "edges": edges, + "faces": [ + { + "surface": surface, + "domain": [u_domain, v_domain], + "reversed": True, + "loops": [{"role": "outer", "trims": trims}], + } + ], + } diff --git a/.github/brep-interchange/occ_adapter.py b/.github/brep-interchange/occ_adapter.py new file mode 100644 index 0000000..2147e12 --- /dev/null +++ b/.github/brep-interchange/occ_adapter.py @@ -0,0 +1,108 @@ +"""Open CASCADE adapter for the planar BRep interchange prototype.""" + +from OCC.Core import BRep +from OCC.Core import BRepBuilderAPI +from OCC.Core import BRepCheck +from OCC.Core import BRepClass3d +from OCC.Core import BRepGProp +from OCC.Core import BRepPrimAPI +from OCC.Core import GProp +from OCC.Core import TopAbs +from OCC.Core import TopExp +from OCC.Core import TopoDS +from OCC.Core import TopTools +from OCC.Core import gp + +SCHEMA = "compas.brep.planar-prototype" +TOLERANCE = 1e-7 + + +def _index(shape, shape_type): + index = TopTools.TopTools_IndexedMapOfShape() + TopExp.topexp.MapShapes(shape, shape_type, index) + return index + + +def _coordinates(value): + return list(value.Coord()) + + +def _is_reversed(shape): + orientation = shape.Orientation() + if orientation not in (TopAbs.TopAbs_FORWARD, TopAbs.TopAbs_REVERSED): + raise ValueError("Only forward and reversed topology are supported.") + return orientation == TopAbs.TopAbs_REVERSED + + +def _solid_from_shells(builder, shells): + solid = TopoDS.TopoDS_Solid() + builder.MakeSolid(solid) + for shell in shells: + builder.Add(solid, shell) + return solid + + +def _polygon_wire(points): + polygon = BRepBuilderAPI.BRepBuilderAPI_MakePolygon() + for x, y in points: + polygon.Add(gp.gp_Pnt(x, y, 0.0)) + polygon.Close() + return polygon.Wire() + + +def make_fixture(name: str) -> TopoDS.TopoDS_Shape: + """Create one of the interchange fixtures using native OCC constructors.""" + if name == "box": + return BRepPrimAPI.BRepPrimAPI_MakeBox(1.0, 2.0, 3.0).Solid() + if name == "cavity": + from planar_cavity import INNER_MAX + from planar_cavity import INNER_MIN + from planar_cavity import OUTER_MAX + from planar_cavity import OUTER_MIN + + outer = BRepPrimAPI.BRepPrimAPI_MakeBox(gp.gp_Pnt(*OUTER_MIN), gp.gp_Pnt(*OUTER_MAX)).Solid() + inner = BRepPrimAPI.BRepPrimAPI_MakeBox(gp.gp_Pnt(*INNER_MIN), gp.gp_Pnt(*INNER_MAX)).Solid() + return _solid_from_shells( + BRep.BRep_Builder(), + [ + BRepClass3d.brepclass3d.OuterShell(outer), + BRepClass3d.brepclass3d.OuterShell(inner).Reversed(), + ], + ) + if name == "face": + outer = _polygon_wire([(1, 2), (8, 2), (8, 7), (1, 7)]) + hole = _polygon_wire([(2, 3), (2, 5), (4, 5), (4, 3)]) + face = BRepBuilderAPI.BRepBuilderAPI_MakeFace(gp.gp_Pln(gp.gp_Ax3()), outer, True) + face.Add(hole) + shape = face.Face() + shape.Reverse() + return shape + raise ValueError(f"Unknown OCC fixture: {name}") + + +def measure(shape: TopoDS.TopoDS_Shape) -> dict[str, bool | float]: + """Measure native validity, area and solid volume.""" + area = GProp.GProp_GProps() + BRepGProp.brepgprop.SurfaceProperties(shape, area) + volume = GProp.GProp_GProps() + BRepGProp.brepgprop.VolumeProperties(shape, volume, True) + return { + "valid": BRepCheck.BRepCheck_Analyzer(shape).IsValid(), + "area": area.Mass(), + "volume": volume.Mass(), + } + + +def native_shell_count(shape: TopoDS.TopoDS_Shape) -> int: + """Count distinct native OCC shells.""" + return _index(shape, TopAbs.TopAbs_SHELL).Size() + + +def classify_points(shape: TopoDS.TopoDS_Shape, points) -> list[bool]: + """Classify points strictly inside the native OCC solid material.""" + classifier = BRepClass3d.BRepClass3d_SolidClassifier(shape) + inside = [] + for point in points: + classifier.Perform(gp.gp_Pnt(*point), TOLERANCE) + inside.append(classifier.State() == TopAbs.TopAbs_IN) + return inside diff --git a/.github/brep-interchange/occ_compound.py b/.github/brep-interchange/occ_compound.py new file mode 100644 index 0000000..e339ec5 --- /dev/null +++ b/.github/brep-interchange/occ_compound.py @@ -0,0 +1,48 @@ +"""Open CASCADE adapter for the planar compound interchange prototype.""" + +from collections.abc import Iterable + +import occ_adapter +from OCC.Core import BRep +from OCC.Core import BRepCheck +from OCC.Core import BRepPrimAPI +from OCC.Core import TopAbs +from OCC.Core import TopoDS +from OCC.Core import gp +from planar_compound import SECOND_MAX +from planar_compound import SECOND_MIN + + +def components(shape: TopoDS.TopoDS_Shape) -> list[TopoDS.TopoDS_Solid]: + """Return the direct solid children of a valid native compound.""" + if shape.IsNull() or shape.ShapeType() != TopAbs.TopAbs_COMPOUND: + raise ValueError("Expected a native OCC compound.") + + children = TopoDS.TopoDS_Iterator(shape) + solids = [] + while children.More(): + child = children.Value() + if child.ShapeType() != TopAbs.TopAbs_SOLID: + raise ValueError("Each direct child of the OCC compound must be a solid.") + solids.append(TopoDS.topods.Solid(child)) + children.Next() + if not solids or not BRepCheck.BRepCheck_Analyzer(shape).IsValid(): + raise ValueError("The OCC compound must contain valid solids.") + return solids + + +def _make_compound(solids: Iterable[TopoDS.TopoDS_Shape]) -> TopoDS.TopoDS_Compound: + builder = BRep.BRep_Builder() + compound = TopoDS.TopoDS_Compound() + builder.MakeCompound(compound) + for solid in solids: + builder.Add(compound, solid) + components(compound) + return compound + + +def make_fixture() -> TopoDS.TopoDS_Compound: + """Build a cavity solid and a separate box as two native compound children.""" + cavity = occ_adapter.make_fixture("cavity") + box = BRepPrimAPI.BRepPrimAPI_MakeBox(gp.gp_Pnt(*SECOND_MIN), gp.gp_Pnt(*SECOND_MAX)).Solid() + return _make_compound((cavity, box)) diff --git a/.github/brep-interchange/occ_nurbs.py b/.github/brep-interchange/occ_nurbs.py new file mode 100644 index 0000000..7d8dc26 --- /dev/null +++ b/.github/brep-interchange/occ_nurbs.py @@ -0,0 +1,330 @@ +"""Open CASCADE adapter for the trimmed NURBS BRep prototype.""" + +from itertools import groupby + +from OCC.Core import BRep +from OCC.Core import BRepAdaptor +from OCC.Core import BRepBuilderAPI +from OCC.Core import BRepCheck +from OCC.Core import BRepGProp +from OCC.Core import BRepTools +from OCC.Core import Geom +from OCC.Core import Geom2d +from OCC.Core import GProp +from OCC.Core import TColgp +from OCC.Core import TColStd +from OCC.Core import TopAbs +from OCC.Core import TopExp +from OCC.Core import TopoDS +from OCC.Core import gp +from occ_adapter import _coordinates +from occ_adapter import _index +from occ_adapter import _is_reversed + +SCHEMA = "compas.brep.nurbs-prototype" +TOLERANCE = 1e-7 + + +def _array(array_type, values): + values = list(values) + result = array_type(1, len(values)) + for index, value in enumerate(values, 1): + result.SetValue(index, value) + return result + + +def _knots(values): + distinct = [] + multiplicities = [] + for knot, repeats in groupby(values): + distinct.append(knot) + multiplicities.append(len(list(repeats))) + return ( + _array(TColStd.TColStd_Array1OfReal, distinct), + _array(TColStd.TColStd_Array1OfInteger, multiplicities), + ) + + +def _full_knots(count, knot, multiplicity): + return [knot(index) for index in range(1, count + 1) for _ in range(multiplicity(index))] + + +def _make_curve(record, dimension): + if dimension == 2: + curve_type, array_type, point_type = ( + Geom2d.Geom2d_BSplineCurve, + TColgp.TColgp_Array1OfPnt2d, + gp.gp_Pnt2d, + ) + else: + curve_type, array_type, point_type = ( + Geom.Geom_BSplineCurve, + TColgp.TColgp_Array1OfPnt, + gp.gp_Pnt, + ) + poles = _array(array_type, (point_type(*point) for point in record["points"])) + weights = _array(TColStd.TColStd_Array1OfReal, record["weights"]) + knots, multiplicities = _knots(record["knots"]) + return curve_type(poles, weights, knots, multiplicities, record["degree"], False) + + +def _make_surface(record): + u_periodic, v_periodic = record.get("periodic", (False, False)) + if v_periodic: + raise ValueError("This OCC NURBS probe supports periodicity in U only.") + points = record["points"] + u_count, v_count = len(points[0]), len(points) + poles = TColgp.TColgp_Array2OfPnt(1, u_count, 1, v_count) + weights = TColStd.TColStd_Array2OfReal(1, u_count, 1, v_count) + for v_index, row in enumerate(points, 1): + for u_index, point in enumerate(row, 1): + poles.SetValue(u_index, v_index, gp.gp_Pnt(*point)) + weights.SetValue(u_index, v_index, record["weights"][v_index - 1][u_index - 1]) + u_knots, u_mults = _knots(record["knots"][0]) + v_knots, v_mults = _knots(record["knots"][1]) + surface = Geom.Geom_BSplineSurface( + poles, + weights, + u_knots, + v_knots, + u_mults, + v_mults, + *record["degrees"], + False, + False, + ) + if u_periodic: + surface.SetUPeriodic() + if _surface_record(surface) != record: + raise ValueError("OCC could not restore periodicity with the original pole and knot data.") + return surface + + +def _surface_record(surface): + if surface.IsVPeriodic(): + raise ValueError("This OCC NURBS probe supports periodicity in U only.") + u_periodic = surface.IsUPeriodic() + if u_periodic: + # Expand the cyclic OCC control net over one complete period for JSON. + surface = Geom.Geom_BSplineSurface.DownCast(surface.Copy()) + surface.SetUNotPeriodic() + u_indices = range(1, surface.NbUPoles() + 1) + v_indices = range(1, surface.NbVPoles() + 1) + record = { + "degrees": [surface.UDegree(), surface.VDegree()], + "knots": [ + _full_knots(surface.NbUKnots(), surface.UKnot, surface.UMultiplicity), + _full_knots(surface.NbVKnots(), surface.VKnot, surface.VMultiplicity), + ], + "points": [[_coordinates(surface.Pole(u, v)) for u in u_indices] for v in v_indices], + "weights": [[surface.Weight(u, v) for u in u_indices] for v in v_indices], + } + if u_periodic: + record["periodic"] = [True, False] + return record + + +def _natural_face(shape): + return TopoDS.topods.Face(shape.Oriented(TopAbs.TopAbs_FORWARD)) + + +def _wire_edges(face, wire): + explorer = BRepTools.BRepTools_WireExplorer(wire, face) + edges = [] + while explorer.More(): + edges.append(explorer.Current()) + explorer.Next() + if len(edges) != wire.NbChildren(): + raise ValueError("Could not traverse all native edge uses in the loop.") + return edges + + +def _validate(shape): + analyzer = BRepCheck.BRepCheck_Analyzer(shape, True, False, True) + if not analyzer.IsValid(): + raise ValueError("The OCC NURBS face is invalid.") + + +def _pole_vertex(edge): + first = TopExp.topexp.FirstVertex(edge) + last = TopExp.topexp.LastVertex(edge) + if first.IsNull() or not first.IsSame(last) or BRep.BRep_Tool.Curve(edge)[0] is not None: + raise ValueError("An OCC degenerated trim must collapse to one vertex with no 3D curve.") + return first + + +def _make_singular_edge(builder, face, surface, vertex, pcurve, start, end, tolerance): + point = BRep.BRep_Tool.Pnt(vertex) + for step in range(9): + parameter = start + (end - start) * (step / 8) + u, v = _coordinates(pcurve.Value(parameter)) + if surface.Value(u, v).Distance(point) > tolerance: + raise ValueError("The UV curve does not collapse to its pole vertex.") + + edge = TopoDS.TopoDS_Edge() + builder.MakeEdge(edge) + builder.Add(edge, vertex.Oriented(TopAbs.TopAbs_FORWARD)) + builder.Add(edge, vertex.Oriented(TopAbs.TopAbs_REVERSED)) + builder.UpdateEdge(edge, pcurve, face, tolerance) + builder.Range(edge, face, start, end) + builder.Degenerated(edge, True) + builder.SameRange(edge, True) + builder.SameParameter(edge, True) + return edge + + +def read_brep(data): + """Construct an OCC BRep from explicit curves, with no sewing or repair.""" + if (data["schema"], data["version"], data["solid"]) != (SCHEMA, 1, False): + raise ValueError("Unsupported OCC NURBS probe payload.") + (face_record,) = data["faces"] + (loop_record,) = face_record["loops"] + if loop_record["role"] != "outer": + raise ValueError("This NURBS probe expects one outer loop.") + tolerance = data["tolerance"] + builder = BRep.BRep_Builder() + vertices = [] + for coordinates in data["vertices"]: + vertex = TopoDS.TopoDS_Vertex() + builder.MakeVertex(vertex, gp.gp_Pnt(*coordinates), tolerance) + vertices.append(vertex) + edges = [] + curves = [] + for edge_record in data["edges"]: + curve = _make_curve(edge_record["curve"], 3) + start, end = edge_record["vertices"] + edge = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(curve, vertices[start], vertices[end], *edge_record["domain"]).Edge() + builder.UpdateEdge(edge, tolerance) + edges.append(edge) + curves.append(curve) + + surface = _make_surface(face_record["surface"]) + face = TopoDS.TopoDS_Face() + builder.MakeFace(face, surface, tolerance) + pcurves = [{} for edge in edges] + wire_edges = [] + for trim in loop_record["trims"]: + index = trim["edge"] + pcurve = _make_curve(trim["curve"], 2) + start, end = trim["domain"] + if index is None: + vertex = vertices[trim["vertex"]] + edge = _make_singular_edge(builder, face, surface, vertex, pcurve, start, end, tolerance) + wire_edges.append(edge) + continue + edge_curve = curves[index] + reversed_trim = trim["reversed"] + if reversed_trim: + start, end = pcurve.ReversedParameter(end), pcurve.ReversedParameter(start) + pcurve.Reverse() + if [start, end] != data["edges"][index]["domain"]: + raise ValueError("The OCC NURBS probe requires matching edge and pcurve ranges.") + for step in range(9): + parameter = start + (end - start) * (step / 8) + u, v = _coordinates(pcurve.Value(parameter)) + if surface.Value(u, v).Distance(edge_curve.Value(parameter)) > tolerance: + raise ValueError("The UV curve and 3D edge have different parameterizations.") + uses = pcurves[index] + if reversed_trim in uses: + raise ValueError("Two uses of a seam edge must have opposite directions.") + uses[reversed_trim] = pcurve + edge = edges[index] + wire_edges.append(edge.Reversed() if reversed_trim else edge) + + for edge, uses, edge_record in zip(edges, pcurves, data["edges"]): + if len(uses) == 2: + # OCC selects the first pcurve for a forward edge use on a + # forward face and the second for the reversed use. + builder.UpdateEdge(edge, uses[False], uses[True], face, tolerance) + elif uses: + builder.UpdateEdge(edge, next(iter(uses.values())), face, tolerance) + else: + raise ValueError("Every OCC edge must be used by a trim.") + start, end = edge_record["domain"] + builder.Range(edge, face, start, end) + builder.SameRange(edge, True) + builder.SameParameter(edge, True) + + wire = TopoDS.TopoDS_Wire() + builder.MakeWire(wire) + for edge in wire_edges: + builder.Add(wire, edge) + wire.Closed(True) + builder.Add(face, wire) + if face_record["reversed"]: + face.Reverse() + _validate(face) + return face + + +def make_fixture(name): + """Build the common fixture definition with native OCC constructors.""" + if name == "nurbs": + from nurbs_fixture import fixture_data + elif name == "nurbs_multispan": + from nurbs_multispan import fixture_data + elif name == "nurbs_periodic": + from nurbs_periodic import fixture_data + elif name == "nurbs_seam": + from nurbs_seam import fixture_data + elif name == "nurbs_pole": + from nurbs_pole import fixture_data + else: + raise ValueError(f"Unknown OCC NURBS fixture: {name}") + return read_brep(fixture_data()) + + +def measure(shape): + """Return the native surface area and validity.""" + _validate(shape) + properties = GProp.GProp_GProps() + BRepGProp.brepgprop.SurfaceProperties(shape, properties, 1e-10) + return {"valid": True, "area": properties.Mass(), "volume": 0.0} + + +def native_u_domain(shape): + """Return the untrimmed OCC support surface's native U interval.""" + surface = BRepAdaptor.BRepAdaptor_Surface(_natural_face(shape)).BSpline() + u_start, u_end, _, _ = surface.Bounds() + return [u_start, u_end] + + +def native_seam_edges(shape): + """Count native edges with two pcurves on this face.""" + face = _natural_face(shape) + edges = _index(face, TopAbs.TopAbs_EDGE) + return sum(BRep.BRep_Tool.IsClosed(TopoDS.topods.Edge(edges.FindKey(index)), face) for index in range(1, edges.Size() + 1)) + + +def native_singular_trims(shape): + """Count native degenerated edge uses with a single pole and no 3D curve.""" + face = _natural_face(shape) + wire = BRepTools.breptools.OuterWire(face) + count = 0 + for edge in _wire_edges(face, wire): + if BRep.BRep_Tool.Degenerated(edge): + _pole_vertex(edge) + count += 1 + return count + + +def sample_surface(shape, u, v): + """Evaluate the native supporting surface at its original UV parameters.""" + return _coordinates(BRepAdaptor.BRepAdaptor_Surface(_natural_face(shape)).Value(u, v)) + + +def sample_trim(shape, loop_index, trim_index, fraction): + """Evaluate the native UV curve and 3D edge along the directed trim.""" + if loop_index != 0: + raise IndexError(loop_index) + face = _natural_face(shape) + wire = BRepTools.breptools.OuterWire(face) + edge = _wire_edges(face, wire)[trim_index] + if _is_reversed(edge): + fraction = 1.0 - fraction + pcurve = BRepAdaptor.BRepAdaptor_Curve2d(edge, face) + if BRep.BRep_Tool.Degenerated(edge): + parameter = pcurve.FirstParameter() + (pcurve.LastParameter() - pcurve.FirstParameter()) * fraction + return _coordinates(pcurve.Value(parameter)), _coordinates(BRep.BRep_Tool.Pnt(_pole_vertex(edge))) + curve = BRepAdaptor.BRepAdaptor_Curve(edge) + return tuple(_coordinates(adaptor.Value(adaptor.FirstParameter() + (adaptor.LastParameter() - adaptor.FirstParameter()) * fraction)) for adaptor in (pcurve, curve)) diff --git a/.github/brep-interchange/planar_cavity.py b/.github/brep-interchange/planar_cavity.py new file mode 100644 index 0000000..113f731 --- /dev/null +++ b/.github/brep-interchange/planar_cavity.py @@ -0,0 +1,16 @@ +"""Dimensions and test points for the enclosed box cavity fixture.""" + +OUTER_MIN = (0.0, 0.0, 0.0) +OUTER_MAX = (8.0, 7.0, 6.0) +INNER_MIN = (2.0, 1.0, 2.0) +INNER_MAX = (5.0, 4.0, 4.0) + +SHELL_VOLUMES = {"outer": 336.0, "inner": -18.0} +AREA = 334.0 +VOLUME = 318.0 + +POINTS = { + "material": [(1.0, 1.0, 1.0), (6.0, 3.0, 3.0), (3.0, 5.0, 3.0)], + "cavity": [(3.5, 2.5, 3.0), (2.5, 1.5, 2.5)], + "exterior": [(-1.0, 2.0, 2.0), (9.0, 8.0, 7.0)], +} diff --git a/.github/brep-interchange/planar_compound.py b/.github/brep-interchange/planar_compound.py new file mode 100644 index 0000000..a218b1f --- /dev/null +++ b/.github/brep-interchange/planar_compound.py @@ -0,0 +1,52 @@ +"""Wire envelope and test dimensions for disjoint planar solids.""" + +from planar_cavity import POINTS as CAVITY_POINTS + +SCHEMA = "compas.brep.compound-prototype" +SECOND_MIN = (12.0, 2.0, 1.0) +SECOND_MAX = (15.0, 6.0, 6.0) +SECOND_AREA = 94.0 +SECOND_VOLUME = 60.0 + +POINTS = { + "cavity_solid_material": CAVITY_POINTS["material"], + "plain_solid_material": [(13.0, 3.0, 2.0), (14.5, 5.5, 5.5)], + "cavity": CAVITY_POINTS["cavity"], + "gap": [(10.0, 3.0, 3.0), (11.0, 5.0, 4.0)], + "exterior": [(-1.0, 2.0, 2.0), (17.0, 3.0, 3.0)], +} + + +def compound_data(records): + """Wrap solid records whose vertex, edge and face indices are local.""" + data = { + "schema": SCHEMA, + "version": 1, + "units": "mm", + "components": list(records), + } + solid_records(data) + return data + + +def solid_records(data): + """Read the direct solid records from a planar compound envelope.""" + if (data.get("schema"), data.get("version"), data.get("units")) != ( + SCHEMA, + 1, + "mm", + ): + raise ValueError("Unsupported compound schema, version or units.") + records = data.get("components") + if not isinstance(records, list) or len(records) < 2: + raise ValueError("A compound requires at least two planar solid components.") + for record in records: + if ( + not isinstance(record, dict) + or record.get("schema") != "compas.brep.planar-prototype" + or record.get("version") != 1 + or record.get("units") != data["units"] + or record.get("solid") is not True + ): + raise ValueError("Each compound component must be a planar solid in the same units.") + return records diff --git a/.github/brep-interchange/rhino_adapter.py b/.github/brep-interchange/rhino_adapter.py new file mode 100644 index 0000000..148c3ad --- /dev/null +++ b/.github/brep-interchange/rhino_adapter.py @@ -0,0 +1,85 @@ +"""Planar BRep interchange probe for Rhino 8 and its embedded Python.""" + +import Rhino.Geometry as rg +from System import Array + +SCHEMA = "compas.brep.planar-prototype" +TOLERANCE = 1e-7 + + +def _face_components(brep): + remaining = set(range(brep.Faces.Count)) + components = [] + while remaining: + first = min(remaining) + remaining.remove(first) + pending = [first] + component = [] + while pending: + index = pending.pop() + component.append(index) + neighbors = remaining.intersection(brep.Faces[index].AdjacentFaces()) + remaining.difference_update(neighbors) + pending.extend(neighbors) + components.append(sorted(component)) + return components + + +def _polygon(points): + result = rg.PolyCurve() + for start, end in zip(points, points[1:] + points[:1]): + result.Append(rg.LineCurve(rg.Point3d(*start, 0.0), rg.Point3d(*end, 0.0))) + return result + + +def make_fixture(name): + if name == "box": + return rg.BoundingBox(rg.Point3d(0, 0, 0), rg.Point3d(1, 2, 3)).ToBrep() + if name == "cavity": + from planar_cavity import INNER_MAX + from planar_cavity import INNER_MIN + from planar_cavity import OUTER_MAX + from planar_cavity import OUTER_MIN + + outer = rg.BoundingBox(rg.Point3d(*OUTER_MIN), rg.Point3d(*OUTER_MAX)).ToBrep() + inner = rg.BoundingBox(rg.Point3d(*INNER_MIN), rg.Point3d(*INNER_MAX)).ToBrep() + inner.Flip() + outer.Append(inner) + return outer + if name == "face": + outer = _polygon([(1, 2), (8, 2), (8, 7), (1, 7)]) + hole = _polygon([(2, 3), (2, 5), (4, 5), (4, 3)]) + breps = rg.Brep.CreatePlanarBreps(Array[rg.Curve]([outer, hole]), TOLERANCE) + if breps is None or len(breps) != 1: + raise ValueError("Rhino did not construct one planar face from the two fixture loops.") + brep = breps[0] + for index in range(brep.Edges.Count): + if not brep.Edges[index].IsLinear(TOLERANCE) and not brep.Edges.SplitKinkyEdge(index, 0.01): + raise ValueError("Rhino could not split a polygonal fixture edge.") + brep.Compact() + if not brep.Faces[0].OrientationIsReversed: + brep.Flip() + return brep + raise ValueError("Unknown fixture: " + name) + + +def measure(brep): + return { + "valid": brep.IsValid, + "area": brep.GetArea(), + "volume": brep.GetVolume() if brep.IsSolid else 0.0, + } + + +def native_shell_count(brep): + """Count connected face components of the native closed manifold BRep.""" + if not brep.IsSolid or not brep.IsManifold: + raise ValueError("Native shell count requires a closed manifold Rhino BRep.") + return len(_face_components(brep)) + + +def classify_points(brep, points): + """Classify points against the oriented native solid boundary.""" + if not brep.IsSolid or not brep.IsManifold: + raise ValueError("Point classification requires a closed manifold Rhino BRep.") + return [brep.IsPointInside(rg.Point3d(*point), TOLERANCE, True) for point in points] diff --git a/.github/brep-interchange/rhino_compound.py b/.github/brep-interchange/rhino_compound.py new file mode 100644 index 0000000..4b46163 --- /dev/null +++ b/.github/brep-interchange/rhino_compound.py @@ -0,0 +1,23 @@ +"""Keep compound members as separate native Rhino BRep solids.""" + +import Rhino.Geometry as rg +import rhino_adapter as planar +from planar_compound import SECOND_MAX +from planar_compound import SECOND_MIN + + +def components(compound): + """Return the ordered native solids in a Rhino compound.""" + if not isinstance(compound, tuple) or not compound: + raise ValueError("Expected a nonempty tuple of native Rhino BRep solids.") + for brep in compound: + if not isinstance(brep, rg.Brep) or not brep.IsSolid or not brep.IsValid: + raise ValueError("Every Rhino compound member must be a valid BRep solid.") + return compound + + +def make_fixture(): + """Build a cavity solid and a disjoint box in the Rhino kernel.""" + cavity = planar.make_fixture("cavity") + box = rg.BoundingBox(rg.Point3d(*SECOND_MIN), rg.Point3d(*SECOND_MAX)).ToBrep() + return components((cavity, box)) diff --git a/.github/brep-interchange/rhino_nurbs.py b/.github/brep-interchange/rhino_nurbs.py new file mode 100644 index 0000000..afc2755 --- /dev/null +++ b/.github/brep-interchange/rhino_nurbs.py @@ -0,0 +1,102 @@ +"""RhinoCommon adapter for the trimmed rational NURBS interchange probe.""" + +from collections import defaultdict + +import Rhino.Geometry as rg + +SCHEMA = "compas.brep.nurbs-prototype" +TOLERANCE = 1e-7 +_WIRE_U_START = "compas.nurbs-prototype.wire-u-start" + + +def _xyz(value): + return [value.X, value.Y, value.Z] + + +def _interval(domain): + return [domain.T0, domain.T1] + + +def _single_face(brep): + if brep.IsSolid or brep.Faces.Count != 1: + raise ValueError("The Rhino NURBS prototype expects one open face.") + face = brep.Faces[0] + if face.Loops.Count != 1 or face.Loops[0].LoopType != rg.BrepLoopType.Outer: + raise ValueError("The Rhino NURBS prototype expects one outer loop.") + return face + + +def _singular_vertex(trim): + """Return the common native vertex of a singular trim.""" + start, end = trim.StartVertex, trim.EndVertex + if trim.TrimType != rg.BrepTrimType.Singular or trim.Edge is not None or start is None or end is None or start.VertexIndex != end.VertexIndex: + raise ValueError("Expected a native Rhino singular trim with one pole vertex.") + return start + + +def measure(brep): + properties = rg.AreaMassProperties.Compute(brep, True, False, False, False, 1e-10, 1e-10) + if properties is None: + raise ValueError("Rhino could not measure the area of the NURBS face.") + try: + return {"valid": brep.IsValid, "area": properties.Area, "volume": 0.0} + finally: + properties.Dispose() + + +def sample_surface(brep, u, v): + surface = brep.Faces[0].UnderlyingSurface() + if surface.IsPeriodic(0): + start, end = _interval(surface.Domain(0)) + if not start <= u <= end: + u = start + (u - start) % (end - start) + return _xyz(surface.PointAt(u, v)) + + +def native_u_domain(brep): + """Return the original Rhino support U interval before sampling wrap.""" + return _interval(brep.Faces[0].UnderlyingSurface().Domain(0)) + + +def native_seam_edges(brep): + """Count shared edges with two oppositely directed native seam trims.""" + edge_uses = defaultdict(list) + for trim in _single_face(brep).Loops[0].Trims: + if trim.Edge is None: + _singular_vertex(trim) + continue + edge_uses[trim.Edge.EdgeIndex].append(trim) + count = 0 + for trims in edge_uses.values(): + if len(trims) == 1 and trims[0].TrimType == rg.BrepTrimType.Boundary: + continue + if ( + len(trims) != 2 + or any(trim.TrimType != rg.BrepTrimType.Seam for trim in trims) + or trims[0].IsReversed() == trims[1].IsReversed() + or {trim.IsoStatus for trim in trims} != {rg.IsoStatus.East, rg.IsoStatus.West} + ): + raise ValueError("Expected two opposing native Rhino seam trims on opposite U boundaries.") + count += 1 + return count + + +def native_singular_trims(brep): + """Count native singular trims with a common vertex and no 3D edge.""" + count = 0 + for trim in _single_face(brep).Loops[0].Trims: + if trim.Edge is None or trim.TrimType == rg.BrepTrimType.Singular: + _singular_vertex(trim) + count += 1 + return count + + +def sample_trim(brep, loop_index, trim_index, fraction): + trim = brep.Faces[0].Loops[loop_index].Trims[trim_index] + uv = trim.PointAt(trim.Domain.ParameterAt(fraction)) + edge = trim.Edge + if edge is None: + return [uv.X, uv.Y], _xyz(_singular_vertex(trim).Location) + edge_fraction = 1.0 - fraction if trim.IsReversed() else fraction + xyz = edge.PointAt(edge.Domain.ParameterAt(edge_fraction)) + return [uv.X, uv.Y], _xyz(xyz) diff --git a/.github/brep-interchange/run_in_rhino.py b/.github/brep-interchange/run_in_rhino.py new file mode 100644 index 0000000..1884aee --- /dev/null +++ b/.github/brep-interchange/run_in_rhino.py @@ -0,0 +1,80 @@ +#! python 3 +# ruff: noqa: EXE001 +"""Run from a directory containing the staged Rhino probe scripts and OCC fixtures.""" + +import json +import sys +import traceback +from contextlib import contextmanager +from hashlib import sha256 +from importlib import import_module +from pathlib import Path + +import Rhino + + +def _codec_modules(): + return tuple(name for name in sys.modules if name == "brep_codec" or name.startswith("brep_codec.")) + + +def _bundle_evidence(directory, manifest): + paths = sorted(Path(sys.modules[name].__file__).resolve() for name in _codec_modules()) + return { + "manifest_sha256": sha256(manifest.read_bytes()).hexdigest(), + "codec_files": {path.relative_to(directory).as_posix(): sha256(path.read_bytes()).hexdigest() for path in paths}, + } + + +@contextmanager +def _staged_modules(directory): + """Use this run's sources even if Rhino is holding a previous probe in memory.""" + names = ( + "run_probe", + "run_interchange", + "interchange", + "interchange_validation", + "rhino_adapter", + "rhino_compound", + "rhino_nurbs", + "nurbs_checks", + "nurbs_fixture", + "nurbs_multispan", + "nurbs_periodic", + "nurbs_seam", + "nurbs_pole", + "planar_cavity", + "planar_compound", + ) + previous = {name: sys.modules.pop(name) for name in (*names, *_codec_modules()) if name in sys.modules} + write_bytecode = sys.dont_write_bytecode + sys.dont_write_bytecode = True + sys.path.insert(0, str(directory)) + try: + yield + finally: + sys.path.remove(str(directory)) + sys.dont_write_bytecode = write_bytecode + for name in (*names, *_codec_modules()): + sys.modules.pop(name, None) + sys.modules.update(previous) + + +def main(phases, report_name): + directory = Path(__file__).resolve().parent + report = {"rhino": str(Rhino.RhinoApp.Version), "python": sys.version.split()[0]} + with _staged_modules(directory): + try: + run = import_module("run_interchange").run + for phase in phases: + report[phase] = run("rhino", phase, directory, source="occ" if phase == "import" else None) + report["bundle"] = _bundle_evidence(directory, directory / "manifest.json") + except Exception: # noqa: BLE001 - Store the host traceback for external verification. + report["error"] = traceback.format_exc() + contents = json.dumps(report, indent=2, allow_nan=False) + "\n" + report_path = directory / report_name + temporary = report_path.with_suffix(".tmp") + temporary.write_text(contents, encoding="utf-8") + temporary.replace(report_path) + print(contents) + if "error" in report: + raise RuntimeError(report["error"]) diff --git a/.github/brep-interchange/run_interchange.py b/.github/brep-interchange/run_interchange.py new file mode 100644 index 0000000..b583e20 --- /dev/null +++ b/.github/brep-interchange/run_interchange.py @@ -0,0 +1,228 @@ +"""Run the native phases of the BRep JSON round-trip matrix.""" + +from __future__ import annotations + +import argparse +import importlib +import json +from copy import deepcopy +from hashlib import sha256 +from math import isfinite +from math import pi +from pathlib import Path +from typing import Literal + +from interchange import from_prototype_data +from interchange import to_prototype_data +from interchange_validation import validate +from nurbs_checks import area_difference +from nurbs_checks import check_nurbs +from run_probe import FIXTURES +from run_probe import NURBS_FIXTURES +from run_probe import _compound_signature +from run_probe import _measure +from run_probe import _measure_compound +from run_probe import _save +from run_probe import _signature + +FIXTURE_NAMES = (*FIXTURES, "compound", *NURBS_FIXTURES) +INVALID_GEOMETRY_CASES = ("face", "cavity") +Backend = Literal["occ", "rhino"] +Phase = Literal["export", "import", "return"] + + +def _fixture_adapter(backend, name): + if name == "compound": + return importlib.import_module(f"{backend}_compound") + if name in NURBS_FIXTURES: + return importlib.import_module(f"{backend}_nurbs") + return importlib.import_module(f"{backend}_adapter") + + +def _fixture_signature(name, data): + # Reuse the existing independent fixture assertions against the + # relevant topology and geometry after converting its record layout. + record = to_prototype_data(data) + if name == "compound": + return _compound_signature(record) + if name in NURBS_FIXTURES: + check_nurbs(record, reference=NURBS_FIXTURES[name]()) + return None + if name == "face" and not record["faces"][0]["reversed"]: + raise ValueError("The planar face must retain its reversed orientation.") + return _signature(name, record) + + +def _measure_fixture(backend, adapter, name, native, data): + if name == "compound": + planar_adapter = importlib.import_module(f"{backend}_adapter") + return _measure_compound(adapter, native, planar_adapter) + if name not in NURBS_FIXTURES: + return _measure(adapter, name, native) + + report = adapter.measure(native) + if not report["valid"] or not isfinite(report["area"]) or report["area"] <= 0: + raise ValueError(f"Invalid native NURBS fixture {name}.") + if report["volume"] != 0.0: + raise ValueError(f"Expected an open NURBS face for {name}.") + report.update(check_nurbs(to_prototype_data(data), adapter, native, reference=NURBS_FIXTURES[name]())) + if name == "nurbs_pole": + report["analytic_area_error_mm2"] = area_difference(2 * pi, report["area"]) + return report + + +def _codec(backend): + if backend == "rhino": + from brep_codec import read_brep + from brep_codec import write_brep + + return read_brep, write_brep + + from compas.geometry import Brep + from compas.geometry import brep_json_context + + def read_brep(data): + envelope = {"dtype": "compas.geometry/Brep", "data": data} + with brep_json_context(backend="occ"): + return Brep.from_jsonstring(json.dumps(envelope, allow_nan=False)).native_brep + + def write_brep(native, *, units): + brep = Brep(native_brep=native, units=units) + data = json.loads(brep.to_jsonstring(minimal=True))["data"] + if data["schema"] != "compas.brep.interchange": + raise ValueError("A supported OCC fixture fell back to legacy JSON.") + return data + + return read_brep, write_brep + + +def _check_invalid_geometry(backend, name, data, read_brep): + bad = deepcopy(data) + component = bad["components"][0] + if name == "face": + outer, inner = component["faces"][0]["loops"] + outer["role"], inner["role"] = inner["role"], outer["role"] + else: + # Move the entire inward shell, including its support surfaces and + # edges, outside the exterior. The wire references remain valid. + inner = next(shell for shell in component["shells"] if shell["role"] == "inner") + faces = [component["faces"][index] for index in inner["faces"]] + edges = {trim["edge"] for face in faces for loop in face["loops"] for trim in loop["trims"]} + vertices = {vertex for index in edges for vertex in component["edges"][index]["vertices"]} + for face in faces: + face["surface"]["origin"][0] += 20.0 + for index in vertices: + component["vertices"][index][0] += 20.0 + for index in edges: + for point in component["edges"][index]["curve"]["points"]: + point[0] += 20.0 + + expected_errors = (ValueError,) + if backend == "occ": + from compas.geometry.brep.errors import BrepInvalidError + + expected_errors += (BrepInvalidError,) + validate(bad) + try: + read_brep(bad) + except expected_errors: + return + raise ValueError(f"{backend} accepted invalid loop or shell geometry for {name}.") + + +def _compound_order(adapter, native, source, exported): + from rhino_adapter import native_shell_count + + actual = [native_shell_count(solid) for solid in adapter.components(native)] + expected = [len(component["shells"]) for component in source["components"]] + if actual != expected or actual != [len(component["shells"]) for component in exported["components"]]: + raise ValueError("Rhino changed the compound's solid order.") + return actual + + +def _stage(backend: Backend, phase: Phase, source: Backend | None) -> tuple[str, str | None, Backend]: + if phase == "export": + return f"{backend}-interchange", None, backend + other: Backend = "rhino" if backend == "occ" else "occ" + if phase == "import" and source == other: + return f"{other}-to-{backend}", f"{other}-interchange", other + if phase == "return" and source is None: + return f"{backend}-to-{other}-to-{backend}", f"{backend}-to-{other}", backend + raise ValueError(f"Invalid {backend} stage {phase!r} with source {source!r}.") + + +def run(backend: Backend, phase: Phase, directory: Path, source: Backend | None = None) -> dict: + """Export, reconstruct, or return all nine native fixtures.""" + directory.mkdir(parents=True, exist_ok=True) + read_brep, write_brep = _codec(backend) + output_prefix, input_prefix, origin = _stage(backend, phase, source) + baseline_prefix = f"{origin}-interchange" + baseline_report = None + if input_prefix is not None: + baseline_report = json.loads((directory / f"{baseline_prefix}-source-report.json").read_text(encoding="utf-8")) + + report = {} + for name in FIXTURE_NAMES: + adapter = _fixture_adapter(backend, name) + if input_prefix is None: + if backend == "rhino" and name in NURBS_FIXTURES: + native = read_brep(from_prototype_data(NURBS_FIXTURES[name]())) + elif name == "compound": + native = adapter.make_fixture() + else: + native = adapter.make_fixture(name) + data = write_brep(native, units="mm") + _fixture_signature(name, data) + else: + input_path = directory / f"{input_prefix}-{name}.json" + contents = input_path.read_bytes() + received = json.loads(contents) + expected = _fixture_signature(name, received) + if phase == "return": + baseline = json.loads((directory / f"{baseline_prefix}-{name}.json").read_text(encoding="utf-8")) + if _fixture_signature(name, baseline) != expected: + raise ValueError(f"{name} changed before the return to {backend}.") + native = read_brep(received) + data = write_brep(native, units=received["units"]) + if _fixture_signature(name, data) != expected: + raise ValueError(f"{backend} re-export changed topology for {name}.") + + properties = _measure_fixture(backend, adapter, name, native, data) + if input_prefix is not None: + properties["input_file"] = input_path.name + properties["input_sha256"] = sha256(contents).hexdigest() + if name in NURBS_FIXTURES: + assert baseline_report is not None + properties["area_difference_mm2"] = area_difference(baseline_report[name]["area"], properties["area"]) + if name in INVALID_GEOMETRY_CASES and phase == "import": + _check_invalid_geometry(backend, name, received, read_brep) + properties["rejected_invalid_geometry"] = True + if backend == "rhino" and name == "compound": + properties["native_component_shell_counts"] = _compound_order(adapter, native, received, data) + reversed_source = {**received, "components": received["components"][::-1]} + reversed_native = read_brep(reversed_source) + reversed_export = write_brep(reversed_native, units=received["units"]) + if _fixture_signature(name, reversed_export) != expected: + raise ValueError("Reversing the component order changed the compound topology.") + properties["reversed_source_component_shell_counts"] = _compound_order(adapter, reversed_native, reversed_source, reversed_export) + output_path = directory / f"{output_prefix}-{name}.json" + _save(output_path, data) + properties["output_sha256"] = sha256(output_path.read_bytes()).hexdigest() + report[name] = properties + + report_name = f"{output_prefix}{'-source' if phase == 'export' else ''}-report.json" + _save(directory / report_name, report) + return report + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("backend", choices=("occ",)) + parser.add_argument("phase", choices=("export", "import", "return")) + parser.add_argument("directory", type=Path) + parser.add_argument("--source", choices=("rhino",)) + args = parser.parse_args() + if (args.phase == "import") != (args.source is not None): + parser.error("only import requires --source rhino") + report = run(args.backend, args.phase, args.directory, args.source) + print(f"{args.backend} {args.phase} verified {len(report)} native fixtures.", flush=True) diff --git a/.github/brep-interchange/run_interchange_in_rhino.py b/.github/brep-interchange/run_interchange_in_rhino.py new file mode 100644 index 0000000..5ce0ea4 --- /dev/null +++ b/.github/brep-interchange/run_interchange_in_rhino.py @@ -0,0 +1,14 @@ +#! python 3 +# ruff: noqa: EXE001 +"""Run the shared interchange regressions in Rhino's embedded Python.""" + +from importlib.util import module_from_spec +from importlib.util import spec_from_file_location +from pathlib import Path + +if __name__ == "__main__": + host_path = Path(__file__).resolve().with_name("run_in_rhino.py") + spec = spec_from_file_location("_compas_interchange_rhino_host", host_path) + host = module_from_spec(spec) + spec.loader.exec_module(host) + host.main(("export", "import"), "rhino-interchange-host-report.json") diff --git a/.github/brep-interchange/run_probe.py b/.github/brep-interchange/run_probe.py new file mode 100644 index 0000000..a52eda8 --- /dev/null +++ b/.github/brep-interchange/run_probe.py @@ -0,0 +1,304 @@ +"""Write and verify the planar and NURBS BRep fixtures in either native host.""" + +import json +from collections import defaultdict +from math import dist +from math import isclose + +from nurbs_fixture import fixture_data as single_span_data +from nurbs_multispan import fixture_data as multi_span_data +from nurbs_periodic import fixture_data as periodic_data +from nurbs_pole import fixture_data as pole_data +from nurbs_seam import fixture_data as seam_data +from planar_cavity import AREA as CAVITY_AREA +from planar_cavity import POINTS as CAVITY_PROBE_POINTS +from planar_cavity import SHELL_VOLUMES as CAVITY_SHELL_VOLUMES +from planar_cavity import VOLUME as CAVITY_VOLUME +from planar_compound import POINTS as COMPOUND_PROBE_POINTS +from planar_compound import SECOND_AREA +from planar_compound import SECOND_VOLUME +from planar_compound import solid_records + +SCHEMA = "compas.brep.planar-prototype" +FIXTURES = { + "box": { + "solid": True, + "vertices": 8, + "edges": 12, + "faces": 6, + "holes": 0, + "area": 22.0, + "volume": 6.0, + }, + "face": { + "solid": False, + "vertices": 8, + "edges": 8, + "faces": 1, + "holes": 1, + "area": 31.0, + "volume": 0.0, + }, + "cavity": { + "solid": True, + "vertices": 16, + "edges": 24, + "faces": 12, + "holes": 0, + "area": CAVITY_AREA, + "volume": CAVITY_VOLUME, + "shell_volumes": CAVITY_SHELL_VOLUMES, + }, +} +NURBS_FIXTURES = { + "nurbs": single_span_data, + "nurbs_multispan": multi_span_data, + "nurbs_periodic": periodic_data, + "nurbs_seam": seam_data, + "nurbs_pole": pole_data, +} + + +def _check(condition, message): + if not condition: + raise ValueError(message) + + +def _cycle(items): + return min(items[offset:] + items[:offset] for offset in range(len(items))) + + +def _shell_signature(shells, face_signatures, face_volumes, edge_uses, expected_volumes): + _check( + sorted(shell["role"] for shell in shells) == sorted(expected_volumes), + "A cavity solid must have one outer and one inner shell.", + ) + _check( + sorted(index for shell in shells for index in shell["faces"]) == list(range(len(face_signatures))), + "Each face must belong to exactly one shell.", + ) + neighbors = defaultdict(set) + for incidents in edge_uses.values(): + (a, _), (b, _) = incidents + neighbors[a].add(b) + neighbors[b].add(a) + result = [] + for shell in shells: + role = shell["role"] + faces = shell["faces"] + _check(len(faces) == 6, f"Unexpected {role} shell face count.") + visited = set() + pending = [faces[0]] + while pending: + face = pending.pop() + if face not in visited: + visited.add(face) + pending.extend(neighbors[face] - visited) + _check( + visited == set(faces), + f"The {role} shell must be one closed face component.", + ) + volume = sum(face_volumes[index] for index in faces) + _check( + isclose(volume, expected_volumes[role], abs_tol=1e-7), + f"The {role} shell has an unexpected signed volume {volume}.", + ) + result.append((role, sorted(face_signatures[index] for index in faces))) + return sorted(result) + + +def _signature(name, data): + """Check connectivity and UV geometry, independent of table and loop start order.""" + fixture = FIXTURES[name] + _check( + (data["schema"], data["version"], data["units"]) == (SCHEMA, 1, "mm"), + "Unexpected schema, version or units.", + ) + _check(data["solid"] is fixture["solid"], "Unexpected solid classification.") + tolerance = data["tolerance"] + _check(tolerance == 1e-7, "Unexpected model tolerance.") + vertices, edges, faces = (data[key] for key in ("vertices", "edges", "faces")) + for key, values in zip(("vertices", "edges", "faces"), (vertices, edges, faces)): + _check(len(values) == fixture[key], f"Unexpected {key} count.") + points = [tuple(round(coordinate, 8) for coordinate in vertex) for vertex in vertices] + _check(len(set(points)) == len(points), "Duplicate vertex positions.") + face_signatures = [] + face_volumes = [] + uses = defaultdict(list) + holes = 0 + for face_index, face in enumerate(faces): + plane = face["plane"] + origin, xaxis, yaxis = (plane[key] for key in ("origin", "xaxis", "yaxis")) + loop_signatures = [] + face_area = 0.0 + uv_points = [] + _check( + sum(loop["role"] == "outer" for loop in face["loops"]) == 1, + "Expected one outer loop per face.", + ) + for loop in face["loops"]: + role = loop["role"] + _check(role in {"outer", "inner"}, "Unexpected loop role.") + holes += role == "inner" + directed_edges = [] + signed_area_twice = 0.0 + for trim in loop["trims"]: + index = trim["edge"] + _check(0 <= index < len(edges), "Invalid trim edge reference.") + edge = edges[index] + uses[index].append((face_index, trim["reversed"] != face["reversed"])) + start, end = edge["vertices"] + _check( + 0 <= start < len(vertices) and 0 <= end < len(vertices), + "Invalid edge vertex reference.", + ) + if trim["reversed"]: + start, end = end, start + directed_edges.append((points[start], points[end])) + length = dist(vertices[start], vertices[end]) + _check(length > tolerance, "Degenerate edge.") + for interval in (edge["domain"], trim["domain"]): + _check( + len(interval) == 2 and interval[0] == 0.0 and isclose(interval[1], length, abs_tol=tolerance), + "Unexpected line parameter domain.", + ) + uv = trim["uv"] + uv_points.extend(uv) + signed_area_twice += uv[0][0] * uv[1][1] - uv[1][0] * uv[0][1] + for (u, v), vertex in zip(uv, (vertices[start], vertices[end])): + lifted = [origin[i] + u * xaxis[i] + v * yaxis[i] for i in range(3)] + _check( + dist(lifted, vertex) <= tolerance, + "UV endpoint does not map to its directed 3D vertex.", + ) + _check(len(directed_edges) >= 3, "Expected a polygonal loop.") + _check( + all(edge[1] == next_edge[0] for edge, next_edge in zip(directed_edges, directed_edges[1:] + directed_edges[:1])), + "The loop is disconnected.", + ) + _check( + signed_area_twice > 0 if role == "outer" else signed_area_twice < 0, + "Unexpected UV winding.", + ) + face_area += signed_area_twice / 2.0 + loop_signatures.append((role, _cycle(directed_edges))) + for interval, coordinates in zip(face["domain"], zip(*uv_points)): + _check( + dist(interval, [min(coordinates), max(coordinates)]) <= tolerance, + "Face UV bounds differ from its trims.", + ) + parameterization = tuple(round(value, 8) for vector in (origin, xaxis, yaxis) for value in vector) + face_signatures.append((face["reversed"], parameterization, tuple(sorted(loop_signatures)))) + if "shell_volumes" in fixture: + # The signed divergence integral of a planar face is its area + # times its oriented normal projection, divided by three. + normal = [xaxis[a] * yaxis[b] - xaxis[b] * yaxis[a] for a, b in ((1, 2), (2, 0), (0, 1))] + direction = -1 if face["reversed"] else 1 + face_volumes.append(direction * face_area * sum(a * b for a, b in zip(origin, normal)) / 3.0) + _check(holes == fixture["holes"], "Unexpected hole count.") + _check(len(uses) == len(edges), "An edge has no incident face.") + for incidents in uses.values(): + if fixture["solid"]: + _check(len(incidents) == 2, "A solid edge requires two incident faces.") + first, second = incidents + _check( + first[0] != second[0] and first[1] != second[1], + "A solid edge must be used in opposite directions by distinct faces.", + ) + else: + _check( + len(incidents) == 1, + "A planar boundary edge requires one incident face.", + ) + if "shell_volumes" in fixture: + _check("shells" in data, "The cavity solid requires explicit shell membership.") + return _shell_signature( + data["shells"], + face_signatures, + face_volumes, + uses, + fixture["shell_volumes"], + ) + return sorted(face_signatures) + + +def _measure(adapter, name, shape): + properties = adapter.measure(shape) + _check(properties["valid"], f"{name} is invalid.") + for key in ("area", "volume"): + _check( + isclose(properties[key], FIXTURES[name][key], abs_tol=1e-7), + f"Unexpected {name} {key}: {properties[key]}.", + ) + if name == "cavity": + count = adapter.native_shell_count(shape) + _check(count == 2, f"The native cavity solid has {count} shells.") + classifications = {} + for region, points in CAVITY_PROBE_POINTS.items(): + results = adapter.classify_points(shape, points) + expected = [region == "material"] * len(points) + _check( + results == expected, + f"Wrong native classification for {region} points: {results}.", + ) + classifications[region] = results + properties.update(native_shell_count=count, point_classification=classifications) + return properties + + +def _compound_signature(data): + records = solid_records(data) + cavities = [record for record in records if "shells" in record] + boxes = [record for record in records if "shells" not in record] + _check( + len(cavities) == len(boxes) == 1, + "The fixture requires one cavity solid and one plain solid.", + ) + (cavity,), (box,) = cavities, boxes + signatures = (_signature("cavity", cavity), _signature("box", box)) + _check( + max(vertex[0] for vertex in cavity["vertices"]) < min(vertex[0] for vertex in box["vertices"]), + "The compound solids must have a gap between them.", + ) + return signatures + + +def _measure_compound(adapter, shape, planar_adapter): + components = adapter.components(shape) + _check(len(components) == 2, "The compound must have two native solids.") + solids = {} + for component in components: + count = planar_adapter.native_shell_count(component) + _check(count in (1, 2), f"Unexpected component shell count {count}.") + name = "cavity_solid" if count == 2 else "plain_solid" + _check(name not in solids, f"The compound has a duplicate {name}.") + area, volume = (CAVITY_AREA, CAVITY_VOLUME) if count == 2 else (SECOND_AREA, SECOND_VOLUME) + properties = planar_adapter.measure(component) + _check(properties["valid"], f"The native {name} is invalid.") + _check(isclose(properties["area"], area, abs_tol=1e-7), f"The {name} area changed.") + _check( + isclose(properties["volume"], volume, abs_tol=1e-7), + f"The {name} material volume changed.", + ) + classifications = {} + for region, points in COMPOUND_PROBE_POINTS.items(): + inside = planar_adapter.classify_points(component, points) + expected = [region == f"{name}_material"] * len(points) + _check(inside == expected, f"Wrong native {name} classification for {region}.") + classifications[region] = inside + properties.update(native_shell_count=count, point_classification=classifications) + solids[name] = properties + return { + "valid": True, + "native_solid_count": len(components), + "area": sum(solid["area"] for solid in solids.values()), + "volume": sum(solid["volume"] for solid in solids.values()), + "solids": solids, + "point_classification": { + region: [any(inside) for inside in zip(*(solid["point_classification"][region] for solid in solids.values()))] for region in COMPOUND_PROBE_POINTS + }, + } + + +def _save(path, value): + path.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n", encoding="utf-8") diff --git a/.github/brep-interchange/run_return_in_rhino.py b/.github/brep-interchange/run_return_in_rhino.py new file mode 100644 index 0000000..1a39a75 --- /dev/null +++ b/.github/brep-interchange/run_return_in_rhino.py @@ -0,0 +1,14 @@ +#! python 3 +# ruff: noqa: EXE001 +"""Run the shared interchange regressions in Rhino's embedded Python.""" + +from importlib.util import module_from_spec +from importlib.util import spec_from_file_location +from pathlib import Path + +if __name__ == "__main__": + host_path = Path(__file__).resolve().with_name("run_in_rhino.py") + spec = spec_from_file_location("_compas_interchange_rhino_host", host_path) + host = module_from_spec(spec) + spec.loader.exec_module(host) + host.main(("return",), "rhino-interchange-host-return-report.json") diff --git a/.github/brep-interchange/test_interchange.py b/.github/brep-interchange/test_interchange.py new file mode 100644 index 0000000..db49b21 --- /dev/null +++ b/.github/brep-interchange/test_interchange.py @@ -0,0 +1,129 @@ +"""Verify the BRep round-trip payloads, reports, and Rhino bundle evidence.""" + +import argparse +import json +from hashlib import sha256 +from importlib.resources import files +from pathlib import Path +from zipfile import ZipFile + +from interchange_validation import SCHEMA +from interchange_validation import VERSION +from interchange_validation import validate +from jsonschema import Draft202012Validator +from jsonschema.exceptions import ValidationError +from run_interchange import FIXTURE_NAMES +from run_interchange import INVALID_GEOMETRY_CASES + +SCHEMA_PATH = Path(__file__).resolve().with_name("brep-interchange-v1.schema.json") + + +def _read_json(path: Path) -> dict: + return json.loads(path.read_text(encoding="utf-8")) + + +def _check_bundle(archive: Path) -> dict: + with ZipFile(archive) as bundle: + manifest_bytes = bundle.read("manifest.json") + manifest = json.loads(manifest_bytes) + if (manifest["schema"], manifest["schema_version"]) != (SCHEMA, VERSION): + raise ValueError("The bundle targets a different interchange schema.") + expected_files = manifest["files"] + if set(bundle.namelist()) != {"manifest.json", *expected_files}: + raise ValueError("The bundle contains unexpected or missing files.") + codec_files = {} + for name, digest in expected_files.items(): + if sha256(bundle.read(name)).hexdigest() != digest: + raise ValueError(f"Bundle manifest does not match {name}.") + if name.startswith("brep_codec/"): + codec_files[name] = digest + if not codec_files: + raise ValueError("The bundle does not declare any Rhino codec files.") + return {"manifest_sha256": sha256(manifest_bytes).hexdigest(), "codec_files": codec_files} + + +def _verify_host(path: Path, bundle_evidence: dict) -> dict: + host = _read_json(path) + if "error" in host: + raise ValueError(f"Rhino failed in {path.name}:\n{host['error']}") + if not host.get("rhino", "").startswith("8."): + raise ValueError(f"{path.name} did not run in Rhino 8.") + if host.get("bundle") != bundle_evidence: + raise ValueError(f"The codec files Rhino loaded do not match the bundle in {path.name}.") + return host + + +def _validate_payload(path: Path, validator: Draft202012Validator) -> str: + contents = path.read_bytes() + data = json.loads(contents) + try: + validator.validate(data) + validate(data) + except (ValidationError, ValueError) as error: + raise ValueError(f"Invalid fixture {path}: {error}") from error + return sha256(contents).hexdigest() + + +def verify_exchange(directory: Path, *, bundle: Path) -> None: + """Require exact-file evidence for every stage of both native round trips.""" + core_schema = files("compas.geometry.brep").joinpath(SCHEMA_PATH.name) + if core_schema.read_bytes() != SCHEMA_PATH.read_bytes(): + raise ValueError("The packaged Core schema differs from the approved schema.") + schema = _read_json(SCHEMA_PATH) + Draft202012Validator.check_schema(schema) + validator = Draft202012Validator(schema) + bundle_evidence = _check_bundle(bundle) + host = _verify_host(directory / "rhino-interchange-host-report.json", bundle_evidence) + returned_host = _verify_host(directory / "rhino-interchange-host-return-report.json", bundle_evidence) + + stages = ( + ("occ-interchange", None, None), + ("rhino-interchange", None, host["export"]), + ("occ-to-rhino", "occ-interchange", host["import"]), + ("rhino-to-occ", "rhino-interchange", None), + ("occ-to-rhino-to-occ", "occ-to-rhino", None), + ("rhino-to-occ-to-rhino", "rhino-to-occ", returned_host["return"]), + ) + digests: dict[str, str] = {} + for stage, source, host_results in stages: + suffix = "-source" if source is None else "" + report = _read_json(directory / f"{stage}{suffix}-report.json") + if host_results is not None and host_results != report: + raise ValueError(f"The standalone {stage} report disagrees with the Rhino host report.") + if set(report) != set(FIXTURE_NAMES): + raise ValueError(f"{stage} has missing or unexpected fixture results: {set(report)}") + for fixture in FIXTURE_NAMES: + metrics = report[fixture] + if metrics.get("valid") is not True: + raise ValueError(f"{stage} did not record a valid native {fixture}.") + if source is not None: + input_name = f"{source}-{fixture}.json" + if (metrics.get("input_file"), metrics.get("input_sha256")) != (input_name, digests[input_name]): + raise ValueError(f"{stage} did not consume the preceding native export for {fixture}.") + payload = f"{stage}-{fixture}.json" + digest = _validate_payload(directory / payload, validator) + if metrics.get("output_sha256") != digest: + raise ValueError(f"{stage} report does not identify its output file {payload}.") + digests[payload] = digest + + for source, report in (("occ-interchange", host["import"]), ("rhino-to-occ", returned_host["return"])): + data = _read_json(directory / f"{source}-compound.json") + order = [len(component["shells"]) for component in data["components"]] + compound = report["compound"] + if compound.get("native_component_shell_counts") != order or compound.get("reversed_source_component_shell_counts") != order[::-1]: + raise ValueError(f"Rhino did not preserve both compound orderings from {source}.") + + for stage in ("occ-to-rhino", "rhino-to-occ"): + report = _read_json(directory / f"{stage}-report.json") + for fixture in INVALID_GEOMETRY_CASES: + if report[fixture].get("rejected_invalid_geometry") is not True: + raise ValueError(f"{stage} did not verify malformed geometry for {fixture}.") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("directory", type=Path) + parser.add_argument("--bundle", required=True, type=Path, help="The exact Rhino 8 codec ZIP used in both host phases.") + args = parser.parse_args() + verify_exchange(args.directory, bundle=args.bundle) + print(f"Verified {2 * len(FIXTURE_NAMES)} native full round trips and {6 * len(FIXTURE_NAMES)} JSON files.") diff --git a/.github/candidates/README.md b/.github/candidates/README.md index 93bd43f..ee3fe4d 100644 --- a/.github/candidates/README.md +++ b/.github/candidates/README.md @@ -78,6 +78,66 @@ protected and that `.github/workflows/build.yml` is the approved producer workflow. The live verifier rejects other workflow paths and events, but this repository-settings check remains an explicit human trust boundary. +## BRep JSON qualification + +Use a reviewed manifest that includes the BRep interchange revisions of +Core and `compas_occ`. Set `brep_json: true` when calling or dispatching +the native candidate workflow. The Linux job runs four required checks +outside the checkouts with the installed candidate wheels. + +- Standalone Core BRep JSON uses the shared schema and preserves the native solid, units, name, and GUID. +- Nested COMPAS JSON preserves BReps and other COMPAS objects. +- The frozen OCC v1 archive loads through the existing reader. +- A valid shape outside the shared codec's supported geometry uses readable legacy JSON. + +The frozen archive was written with pre-interchange Core +`1c0ce44eea89be64a208cca7f6e21b53040af8e9`, OCC +`7fdf2ffb57d1de16308020e14ec626d79e65a034`, and OCCT 7.9.0. Its SHA-256 is +`984fa34b7df5e21305b5cb1fe11e8cd3927d6da5632cef65a055871e755d242a`. +Keep it as a historical input when updating the writers. +[Frozen archive](brep_legacy_occ_v1.json) + +The Rhino workflow first requires those Linux checks. A reviewed manifest +at `.github/candidates/brep-linux-py312.json` triggers the workflow when +pushed to the protected BRep initiative branch. GitHub also permits a +manual run once the workflow is present on the default branch. +[GitHub workflow triggers](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows#workflow_dispatch) + +The workflow downloads the verified candidates and runs on a dedicated +self-hosted macOS runner in the `compas-rhino8` group with label `rhino8`. +Restrict that runner group to this reviewed framework workflow on protected +refs. The runner account needs an open Rhino 8 session with +RhinoCode enabled and Python 3.9 available in the host. Set +`RHINO8_OCC_PYTHON` to the absolute path of the runner's Python 3.12 +environment with `pythonocc-core`, `packaging`, and `jsonschema` available. +Set `RHINO8_BREP_CODEC_ZIP` to the runner-local path of the Rhino package's +verified bundle. The harness checks the archive hash and the hashes of +the codec modules that were loaded in Rhino. This job runs on a protected +framework ref and receives the candidate artifacts without repository +permissions. +[Rhino workflow](../workflows/rhino-brep-integration.yml) · [Runner group access](https://docs.github.com/en/actions/how-tos/manage-runners/self-hosted-runners/manage-access) + +Each of the nine fixtures travels OCC → Rhino 8 → OCC and Rhino 8 → OCC → +Rhino 8. The returning host reads the intermediate kernel's re-export. +The verifier checks the exact payload handed across each leg and compares +native validity, geometry, topology, and cavity membership. It also checks +both orders of the native Rhino compound tuple. + +For a local run from the framework checkout, use the OCC environment and +provide the exact wheels and Rhino ZIP. + +```sh +work=$(mktemp -d) +python .github/scripts/run_rhino_brep_candidate.py \ + --wheels /absolute/path/to/compas.whl /absolute/path/to/compas_occ.whl \ + --bundle /absolute/path/to/compas-rhino8-brep-codec-1.0.0.zip \ + --output "$work/results" +``` + +The runner installs both wheels without dependency resolution into the +temporary output and checks their import locations. It records the +artifact hashes and the reports for both closed loops there. + ## Promotion Before a dependent package is promoted, run `verify-public-candidates.yml` diff --git a/.github/candidates/brep_legacy_occ_v1.json b/.github/candidates/brep_legacy_occ_v1.json new file mode 100644 index 0000000..7112da5 --- /dev/null +++ b/.github/candidates/brep_legacy_occ_v1.json @@ -0,0 +1 @@ +{"dtype":"compas.geometry/Brep","data":{"schema":"compas.brep","version":1,"units":null,"geometry":{"representation":"embedded"},"topology":{"representation":"components","shape_type":2,"components":[{"shape_type":2,"faces":[{"type":0,"surface":{"dtype":"compas.geometry/Plane","data":{"point":[-0.5,-1.5,-1.0],"normal":[1.0,0.0,-0.0]},"guid":"f0a0cc73-9a6f-4e9b-9af4-bbb6be0bc5e0"},"domain_u":[0.0,2.0],"domain_v":[-3.0,0.0],"frame":{"dtype":"compas.geometry/Frame","data":{"point":[0.0,0.0,0.0],"xaxis":[1.0,0.0,0.0],"yaxis":[0.0,1.0,0.0]},"guid":"36e80935-5572-4968-8836-b58e677999f2"},"loops":[[{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,-1.5,-1.0],"end":[-0.5,-1.5,1.0]},"guid":"85aa848f-df99-465f-8955-38bba580b955"},"domain":[0.0,2.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,-1.0],"guid":"1e538268-ea1e-4a8e-ab02-d69b0f04ff85"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,1.0],"guid":"d4337443-a988-4754-a34d-8356afcb36b4"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,-1.5,1.0],"end":[-0.5,1.5,1.0]},"guid":"7ca57b7d-9490-4515-97a1-8967091a6549"},"domain":[0.0,3.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,1.0],"guid":"58798ce3-8e4a-43bb-a9ac-ca3d73120f81"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,1.0],"guid":"5c5de02e-6575-433f-87dd-8aab97593b48"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,1.5,1.0],"end":[-0.5,1.5,-1.0]},"guid":"1fb8bf88-cc07-4805-b5f8-0833dfc53f30"},"domain":[0.0,2.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,1.0],"guid":"d48b34a9-5363-48b3-9bd7-935c57e33d99"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,-1.0],"guid":"483a57fc-509a-46c3-a5cb-72cc9485be90"},"orientation":1,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,1.5,-1.0],"end":[-0.5,-1.5,-1.0]},"guid":"3991a03e-fe19-4e48-b94e-fdaad01b5f1c"},"domain":[0.0,3.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,-1.0],"guid":"6c5a363e-03ab-4f00-b4db-ab399b598e39"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,-1.0],"guid":"45130676-0cc8-4d2c-a568-f10f285bfb65"},"orientation":1,"dimension":3}]],"orientation":1},{"type":0,"surface":{"dtype":"compas.geometry/Plane","data":{"point":[0.5,-1.5,-1.0],"normal":[1.0,0.0,-0.0]},"guid":"b3b9ee1b-1d47-4e96-9aef-b3274101c693"},"domain_u":[0.0,2.0],"domain_v":[-3.0,0.0],"frame":{"dtype":"compas.geometry/Frame","data":{"point":[0.0,0.0,0.0],"xaxis":[1.0,0.0,0.0],"yaxis":[0.0,1.0,0.0]},"guid":"33b7fb3f-05b0-4994-8a75-3008ac1f7f89"},"loops":[[{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,-1.5,1.0],"end":[0.5,-1.5,-1.0]},"guid":"8f54b762-51cf-48a5-8264-ea4e9def2ad7"},"domain":[0.0,2.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,1.0],"guid":"40e54826-4e79-4c50-b661-84170ba54ba9"},"end":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,-1.0],"guid":"e76f831d-e6ea-4121-9245-92a08b262374"},"orientation":1,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,-1.5,-1.0],"end":[0.5,1.5,-1.0]},"guid":"66f9f977-1e69-4017-8c75-3eedd14b22cc"},"domain":[0.0,3.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,-1.0],"guid":"52620278-b82a-494f-9820-3eb966302a45"},"end":{"dtype":"compas.geometry/Point","data":[0.5,1.5,-1.0],"guid":"ae9ef2de-b319-4ea1-9c50-25ee91db1c2d"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,1.5,-1.0],"end":[0.5,1.5,1.0]},"guid":"4f0122f1-1225-4ff2-9005-fdee05ffbfb0"},"domain":[0.0,2.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,1.5,-1.0],"guid":"a2374c59-0f12-4b77-a0a3-509bfc369c4c"},"end":{"dtype":"compas.geometry/Point","data":[0.5,1.5,1.0],"guid":"4be2d015-9f04-4e9c-b4af-d48e4ab68f27"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,1.5,1.0],"end":[0.5,-1.5,1.0]},"guid":"57fd147a-8278-4e53-919a-bbd2a220841d"},"domain":[0.0,3.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,1.5,1.0],"guid":"ca38e916-9c6c-458e-9833-49e0520fbdb2"},"end":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,1.0],"guid":"346ebd02-e5fd-4b54-ae44-055a257a814c"},"orientation":1,"dimension":3}]],"orientation":0},{"type":0,"surface":{"dtype":"compas.geometry/Plane","data":{"point":[-0.5,-1.5,-1.0],"normal":[-0.0,1.0,0.0]},"guid":"429f099f-9f7d-4b07-a535-03e65645cc3c"},"domain_u":[0.0,2.0],"domain_v":[0.0,1.0],"frame":{"dtype":"compas.geometry/Frame","data":{"point":[0.0,0.0,0.0],"xaxis":[1.0,0.0,0.0],"yaxis":[0.0,1.0,0.0]},"guid":"708b9f62-a1e8-4158-bdc2-1dbad475e277"},"loops":[[{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,-1.5,-1.0],"end":[0.5,-1.5,-1.0]},"guid":"da6ac301-22bd-47f6-b758-612620a8ec35"},"domain":[0.0,1.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,-1.0],"guid":"6557c586-1d12-42a9-99a6-90947b03a160"},"end":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,-1.0],"guid":"db81fe10-abdc-47b6-99aa-5dda1e1bcbcb"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,-1.5,-1.0],"end":[0.5,-1.5,1.0]},"guid":"1162e79f-dcfd-4b30-b1f7-59facf6fbc71"},"domain":[0.0,2.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,-1.0],"guid":"3145473d-9988-4c35-bbe7-9393d35b0e78"},"end":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,1.0],"guid":"9ea1d74f-3340-41de-8148-d82b4e8e0d37"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,-1.5,1.0],"end":[-0.5,-1.5,1.0]},"guid":"2b7399dd-0169-448c-9cb6-ade5be947592"},"domain":[0.0,1.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,1.0],"guid":"d3c95f15-60a6-428b-bb3d-107b7eb6cfdc"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,1.0],"guid":"bb61f4b0-2de3-4b7f-8bc7-b5f1590fd384"},"orientation":1,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,-1.5,1.0],"end":[-0.5,-1.5,-1.0]},"guid":"26415c8d-c25a-424f-aa75-e5ea6201c3f4"},"domain":[0.0,2.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,1.0],"guid":"0990c754-8304-4b9b-a612-d056e72b9406"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,-1.0],"guid":"5cab1616-ed52-4859-b92e-12cd65facd1e"},"orientation":1,"dimension":3}]],"orientation":1},{"type":0,"surface":{"dtype":"compas.geometry/Plane","data":{"point":[-0.5,1.5,-1.0],"normal":[-0.0,1.0,0.0]},"guid":"4e75e340-f7c3-4434-905d-eb28585ad35f"},"domain_u":[0.0,2.0],"domain_v":[0.0,1.0],"frame":{"dtype":"compas.geometry/Frame","data":{"point":[0.0,0.0,0.0],"xaxis":[1.0,0.0,0.0],"yaxis":[0.0,1.0,0.0]},"guid":"553f7f47-fb1d-407b-978c-75ce0a349ebd"},"loops":[[{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,1.5,-1.0],"end":[-0.5,1.5,-1.0]},"guid":"5fe15820-3f8a-48f6-a420-7ac211d92109"},"domain":[0.0,1.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,1.5,-1.0],"guid":"76e2e85b-73fd-4eeb-bd01-addc10a8bb85"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,-1.0],"guid":"c6845db8-cecf-4833-b38c-51c6a7a8ca0e"},"orientation":1,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,1.5,-1.0],"end":[-0.5,1.5,1.0]},"guid":"adeec082-30e4-4827-a1ab-5a683eaa3ab4"},"domain":[0.0,2.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,-1.0],"guid":"8822b8f9-464d-4643-a26f-b39bdae86f01"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,1.0],"guid":"d6a46b7c-ced9-4305-89fe-5f96cb8e9b0a"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,1.5,1.0],"end":[0.5,1.5,1.0]},"guid":"6ab20f08-79a7-40bf-8faa-17b8d9ad705b"},"domain":[0.0,1.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,1.0],"guid":"7704c1c4-7ecf-4628-9eb8-fca571237177"},"end":{"dtype":"compas.geometry/Point","data":[0.5,1.5,1.0],"guid":"2a9e38c6-91c2-49b5-8912-49dc35fcc5b6"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,1.5,1.0],"end":[0.5,1.5,-1.0]},"guid":"c4ca0997-d728-4ce3-bc4d-201050660366"},"domain":[0.0,2.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,1.5,1.0],"guid":"2592436c-c032-430a-aa97-683a40d5a9af"},"end":{"dtype":"compas.geometry/Point","data":[0.5,1.5,-1.0],"guid":"02c36511-54d1-44df-a0b1-8c40c201f04b"},"orientation":1,"dimension":3}]],"orientation":0},{"type":0,"surface":{"dtype":"compas.geometry/Plane","data":{"point":[-0.5,-1.5,-1.0],"normal":[0.0,0.0,1.0]},"guid":"e9701190-2cc7-437c-9383-b12e8eec7f8c"},"domain_u":[0.0,1.0],"domain_v":[0.0,3.0],"frame":{"dtype":"compas.geometry/Frame","data":{"point":[0.0,0.0,0.0],"xaxis":[1.0,0.0,0.0],"yaxis":[0.0,1.0,0.0]},"guid":"49c7a0eb-ff78-4bce-8616-6f17d06daa7c"},"loops":[[{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,-1.5,-1.0],"end":[-0.5,1.5,-1.0]},"guid":"2ce9fd49-6179-45ac-a9e4-f670af98fde0"},"domain":[0.0,3.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,-1.0],"guid":"6deaddc8-fd68-42bd-aacd-24a48aa13e46"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,-1.0],"guid":"2d3f8b72-11bc-494f-b445-e3d7202533bf"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,1.5,-1.0],"end":[0.5,1.5,-1.0]},"guid":"bdd6dded-d608-457c-889b-7b46c9010972"},"domain":[0.0,1.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,-1.0],"guid":"52b3d59f-048f-4564-80e2-3e89da9918e1"},"end":{"dtype":"compas.geometry/Point","data":[0.5,1.5,-1.0],"guid":"249d4fa6-3a48-4f5b-8821-30c9331902f8"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,1.5,-1.0],"end":[0.5,-1.5,-1.0]},"guid":"bdac4b28-cb2f-40ca-88fa-1c934a5e3b53"},"domain":[0.0,3.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,1.5,-1.0],"guid":"0552a0e4-470c-4d08-a62e-b5caac5d79bf"},"end":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,-1.0],"guid":"c99e1025-6c0a-4584-98e2-cb22f9913dcf"},"orientation":1,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,-1.5,-1.0],"end":[-0.5,-1.5,-1.0]},"guid":"a67e8583-71ab-4ee3-8149-930bc9474a44"},"domain":[0.0,1.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,-1.0],"guid":"eff4329f-c1a5-427c-8577-b60523b88d4f"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,-1.0],"guid":"2621eb6e-f01c-4111-9f7a-3c8a97b7e847"},"orientation":1,"dimension":3}]],"orientation":1},{"type":0,"surface":{"dtype":"compas.geometry/Plane","data":{"point":[-0.5,-1.5,1.0],"normal":[0.0,0.0,1.0]},"guid":"3a8e219e-6dae-4749-803a-987ace596fb2"},"domain_u":[0.0,1.0],"domain_v":[0.0,3.0],"frame":{"dtype":"compas.geometry/Frame","data":{"point":[0.0,0.0,0.0],"xaxis":[1.0,0.0,0.0],"yaxis":[0.0,1.0,0.0]},"guid":"f1b4c5b0-74bc-49c6-9a2f-16dd274f4b5f"},"loops":[[{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,1.5,1.0],"end":[-0.5,-1.5,1.0]},"guid":"98f25553-051d-45da-b835-6475948dbaf6"},"domain":[0.0,3.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,1.0],"guid":"10fe73bf-8c54-4b0b-aeac-81244608c098"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,1.0],"guid":"ef4b8752-a5b2-4d76-bbd4-fe2c00491d50"},"orientation":1,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,-1.5,1.0],"end":[0.5,-1.5,1.0]},"guid":"acf2c49c-3c40-4ce2-8f1f-7d77b50594f4"},"domain":[0.0,1.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,1.0],"guid":"5500ae9a-73d3-4072-bc79-51fefa9f7ba7"},"end":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,1.0],"guid":"56986023-c089-4254-9dbb-80e5060f9f1d"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,-1.5,1.0],"end":[0.5,1.5,1.0]},"guid":"44ee520f-0f86-4589-8b13-cf11f544ae2d"},"domain":[0.0,3.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,1.0],"guid":"7e1fabb3-497e-4e33-908d-075e5dc7cbd8"},"end":{"dtype":"compas.geometry/Point","data":[0.5,1.5,1.0],"guid":"42e30571-c66e-43ee-a059-df0bffe522c8"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,1.5,1.0],"end":[-0.5,1.5,1.0]},"guid":"f0240586-c641-44c9-8279-199764f0bf33"},"domain":[0.0,1.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,1.5,1.0],"guid":"41391943-2f6e-46a1-8c67-7c5d2fc4cb87"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,1.0],"guid":"2fecc4d8-ff1e-4216-ba95-9a40e81fbeae"},"orientation":1,"dimension":3}]],"orientation":0}]}]},"native":{"backend":"occ","format":"brep","encoding":"base64","data":"REJSZXBfRHJhd2FibGVTaGFwZQoKQ0FTQ0FERSBUb3BvbG9neSBWMywgKGMpIE9wZW4gQ2FzY2FkZQpMb2NhdGlvbnMgMApDdXJ2ZTJkcyAyNAoxIDAgMCAxIDAgCjEgMCAwIDEgMCAKMSAyIDAgMCAtMSAKMSAwIDAgMCAxIAoxIDAgLTMgMSAwIAoxIDAgMCAxIDAgCjEgMCAwIDAgLTEgCjEgMCAwIDAgMSAKMSAwIDAgMSAwIAoxIDAgMSAxIDAgCjEgMiAwIDAgLTEgCjEgMSAwIDAgMSAKMSAwIC0zIDEgMCAKMSAwIDEgMSAwIAoxIDAgMCAwIC0xIAoxIDEgMCAwIDEgCjEgMCAwIDAgMSAKMSAwIDAgMSAwIAoxIDIgMCAwIDEgCjEgMCAwIDEgMCAKMSAwIDAgMCAxIAoxIDAgMyAxIDAgCjEgMiAwIDAgMSAKMSAwIDMgMSAwIApDdXJ2ZXMgMTIKMSAtMC41IC0xLjUgLTEgMCAwIDEgCjEgLTAuNSAtMS41IDEgLTAgMSAwIAoxIC0wLjUgMS41IC0xIDAgMCAxIAoxIC0wLjUgLTEuNSAtMSAtMCAxIDAgCjEgMC41IC0xLjUgLTEgMCAwIDEgCjEgMC41IC0xLjUgMSAtMCAxIDAgCjEgMC41IDEuNSAtMSAwIDAgMSAKMSAwLjUgLTEuNSAtMSAtMCAxIDAgCjEgLTAuNSAtMS41IC0xIDEgMCAtMCAKMSAtMC41IC0xLjUgMSAxIDAgLTAgCjEgLTAuNSAxLjUgLTEgMSAwIC0wIAoxIC0wLjUgMS41IDEgMSAwIC0wIApQb2x5Z29uM0QgMApQb2x5Z29uT25Ucmlhbmd1bGF0aW9ucyAwClN1cmZhY2VzIDYKMSAtMC41IC0xLjUgLTEgMSAwIC0wIDAgMCAxIDAgLTEgMCAKMSAtMC41IC0xLjUgLTEgLTAgMSAwIDAgMCAxIDEgMCAtMCAKMSAtMC41IC0xLjUgMSAwIDAgMSAxIDAgLTAgLTAgMSAwIAoxIC0wLjUgMS41IC0xIC0wIDEgMCAwIDAgMSAxIDAgLTAgCjEgLTAuNSAtMS41IC0xIDAgMCAxIDEgMCAtMCAtMCAxIDAgCjEgMC41IC0xLjUgLTEgMSAwIC0wIDAgMCAxIDAgLTEgMCAKVHJpYW5ndWxhdGlvbnMgMAoKVFNoYXBlcyAzNApWZQoxZS0wNwotMC41IC0xLjUgMQowIDAKCjAxMDExMDEKKgpWZQoxZS0wNwotMC41IC0xLjUgLTEKMCAwCgowMTAxMTAxCioKRWQKIDFlLTA3IDEgMSAwCjEgIDEgMCAwIDIKMiAgMSAxIDAgMCAyCjIgIDIgMiAwIDAgMgowCgowMTAxMDAwCi0zNCAwICszMyAwICoKVmUKMWUtMDcKLTAuNSAxLjUgMQowIDAKCjAxMDExMDEKKgpFZAogMWUtMDcgMSAxIDAKMSAgMiAwIDAgMwoyICAzIDEgMCAwIDMKMiAgNCAzIDAgMCAzCjAKCjAxMDEwMDAKLTMxIDAgKzM0IDAgKgpWZQoxZS0wNwotMC41IDEuNSAtMQowIDAKCjAxMDExMDEKKgpFZAogMWUtMDcgMSAxIDAKMSAgMyAwIDAgMgoyICA1IDEgMCAwIDIKMiAgNiA0IDAgMCAyCjAKCjAxMDEwMDAKLTMxIDAgKzI5IDAgKgpFZAogMWUtMDcgMSAxIDAKMSAgNCAwIDAgMwoyICA3IDEgMCAwIDMKMiAgOCA1IDAgMCAzCjAKCjAxMDEwMDAKLTI5IDAgKzMzIDAgKgpXaQoKMDEwMTEwMAotMzIgMCAtMzAgMCArMjggMCArMjcgMCAqCkZhCjAgIDFlLTA3IDEgMAoKMDExMTAwMAorMjYgMCAqClZlCjFlLTA3CjAuNSAtMS41IDEKMCAwCgowMTAxMTAxCioKVmUKMWUtMDcKMC41IC0xLjUgLTEKMCAwCgowMTAxMTAxCioKRWQKIDFlLTA3IDEgMSAwCjEgIDUgMCAwIDIKMiAgOSA2IDAgMCAyCjIgIDEwIDIgMCAwIDIKMAoKMDEwMTAwMAotMjQgMCArMjMgMCAqClZlCjFlLTA3CjAuNSAxLjUgMQowIDAKCjAxMDExMDEKKgpFZAogMWUtMDcgMSAxIDAKMSAgNiAwIDAgMwoyICAxMSA2IDAgMCAzCjIgIDEyIDMgMCAwIDMKMAoKMDEwMTAwMAotMjEgMCArMjQgMCAqClZlCjFlLTA3CjAuNSAxLjUgLTEKMCAwCgowMTAxMTAxCioKRWQKIDFlLTA3IDEgMSAwCjEgIDcgMCAwIDIKMiAgMTMgNiAwIDAgMgoyICAxNCA0IDAgMCAyCjAKCjAxMDEwMDAKLTIxIDAgKzE5IDAgKgpFZAogMWUtMDcgMSAxIDAKMSAgOCAwIDAgMwoyICAxNSA2IDAgMCAzCjIgIDE2IDUgMCAwIDMKMAoKMDEwMTAwMAotMTkgMCArMjMgMCAqCldpCgowMTAxMTAwCi0yMiAwIC0yMCAwICsxOCAwICsxNyAwICoKRmEKMCAgMWUtMDcgNiAwCgowMTExMDAwCisxNiAwICoKRWQKIDFlLTA3IDEgMSAwCjEgIDkgMCAwIDEKMiAgMTcgMiAwIDAgMQoyICAxOCA1IDAgMCAxCjAKCjAxMDEwMDAKLTIzIDAgKzMzIDAgKgpFZAogMWUtMDcgMSAxIDAKMSAgMTAgMCAwIDEKMiAgMTkgMiAwIDAgMQoyICAyMCAzIDAgMCAxCjAKCjAxMDEwMDAKLTI0IDAgKzM0IDAgKgpXaQoKMDEwMTEwMAotMTQgMCAtMjIgMCArMTMgMCArMzIgMCAqCkZhCjAgIDFlLTA3IDIgMAoKMDExMTAwMAorMTIgMCAqCkVkCiAxZS0wNyAxIDEgMAoxICAxMSAwIDAgMQoyICAyMSA0IDAgMCAxCjIgIDIyIDUgMCAwIDEKMAoKMDEwMTAwMAotMTkgMCArMjkgMCAqCkVkCiAxZS0wNyAxIDEgMAoxICAxMiAwIDAgMQoyICAyMyA0IDAgMCAxCjIgIDI0IDMgMCAwIDEKMAoKMDEwMTAwMAotMjEgMCArMzEgMCAqCldpCgowMTAxMTAwCi0xMCAwIC0xOCAwICs5IDAgKzI4IDAgKgpGYQowICAxZS0wNyA0IDAKCjAxMTEwMDAKKzggMCAqCldpCgowMTAxMTAwCi0yNyAwIC0xMCAwICsxNyAwICsxNCAwICoKRmEKMCAgMWUtMDcgNSAwCgowMTExMDAwCis2IDAgKgpXaQoKMDEwMTEwMAotMzAgMCAtOSAwICsyMCAwICsxMyAwICoKRmEKMCAgMWUtMDcgMyAwCgowMTExMDAwCis0IDAgKgpTaAoKMDEwMTEwMAotMjUgMCArMTUgMCAtMTEgMCArNyAwIC01IDAgKzMgMCAqClNvCgoxMTAwMDAwCisyIDAgKgoKKzEgMCA="}},"name":"Legacy asymmetric box","guid":"2aeeb908-a305-4faf-8db5-821bc5c78ded"} \ No newline at end of file diff --git a/.github/candidates/candidate_brep_json.py b/.github/candidates/candidate_brep_json.py new file mode 100644 index 0000000..4b6662b --- /dev/null +++ b/.github/candidates/candidate_brep_json.py @@ -0,0 +1,113 @@ +"""Public BRep JSON contracts for installed Core and OCC candidate wheels.""" + +import json +from math import pi +from pathlib import Path +from uuid import UUID + +import compas +import pytest +from compas.geometry import Box +from compas.geometry import Brep +from compas.geometry import Point +from compas.geometry import Sphere +from compas.geometry import brep_json_context + +_LEGACY_ARCHIVE = Path(__file__).with_name("brep_legacy_occ_v1.json") +_LEGACY_GUID = UUID("2aeeb908-a305-4faf-8db5-821bc5c78ded") + + +def _box_brep() -> Brep: + brep = Brep.from_box(Box.from_width_height_depth(1.0, 2.0, 3.0)) + brep.name = "Candidate asymmetric box" + brep.units = "mm" + return brep + + +def _assert_box(brep: Brep, *, name: str, guid: UUID, units: str | None) -> None: + assert type(brep) is Brep + assert (brep.name, brep.guid, brep.units) == (name, guid, units) + assert brep.is_valid + assert brep.is_solid + assert len(brep.vertices) == 8 + assert len(brep.edges) == 12 + assert len(brep.faces) == 6 + assert brep.area == pytest.approx(22.0) + assert brep.volume == pytest.approx(6.0) + + +def test_candidate_brep_standalone_json_roundtrip(tmp_path: Path) -> None: + source = _box_brep() + archive = tmp_path / "box.json" + + source.to_json(archive) + envelope = json.loads(archive.read_text(encoding="utf-8")) + assert envelope["dtype"] == "compas.geometry/Brep" + assert envelope["data"]["schema"] == "compas.brep.interchange" + assert envelope["data"]["version"] == 1 + assert envelope["data"]["units"] == "mm" + assert "native" not in envelope["data"] + + with brep_json_context(backend="occ"): + restored = Brep.from_json(archive) + + _assert_box(restored, name=source.name, guid=source.guid, units="mm") + + +def test_candidate_brep_nested_json_roundtrip(tmp_path: Path) -> None: + source = _box_brep() + point = Point(2.0, 3.0, 4.0) + archive = tmp_path / "document.json" + + compas.json_dump({"objects": [{"geometry": source, "label": "solid"}, point]}, archive) + encoded_objects = json.loads(archive.read_text(encoding="utf-8"))["objects"] + assert encoded_objects[0]["geometry"]["data"]["schema"] == "compas.brep.interchange" + assert encoded_objects[1]["dtype"] == "compas.geometry/Point" + + with brep_json_context(backend="occ"): + restored = compas.json_load(archive)["objects"] + + _assert_box(restored[0]["geometry"], name=source.name, guid=source.guid, units="mm") + assert restored[0]["label"] == "solid" + assert isinstance(restored[1], Point) + assert restored[1] == point + + +def test_candidate_brep_reads_historical_occ_json() -> None: + envelope = json.loads(_LEGACY_ARCHIVE.read_text(encoding="utf-8")) + assert envelope["dtype"] == "compas.geometry/Brep" + assert envelope["data"]["schema"] == "compas.brep" + assert envelope["data"]["version"] == 1 + assert envelope["data"]["native"]["backend"] == "occ" + + restored = Brep.from_json(_LEGACY_ARCHIVE) + + _assert_box(restored, name="Legacy asymmetric box", guid=_LEGACY_GUID, units=None) + + +def _legacy_roundtrip(source: Brep, archive: Path) -> Brep: + source.to_json(archive) + envelope = json.loads(archive.read_text(encoding="utf-8")) + assert envelope["dtype"] == "compas.geometry/Brep" + assert envelope["data"]["schema"] == "compas.brep" + assert envelope["data"]["version"] == 1 + assert envelope["data"]["units"] == source.units + assert envelope["data"]["native"]["backend"] == "occ" + return Brep.from_json(archive) + + +def test_candidate_brep_legacy_fallback_remains_readable(tmp_path: Path) -> None: + box = _box_brep() + box.units = None + restored_box = _legacy_roundtrip(box, tmp_path / "unitless-box.json") + _assert_box(restored_box, name=box.name, guid=box.guid, units=None) + + sphere = Brep.from_sphere(Sphere(2.0)) + sphere.name = "Candidate analytic sphere" + sphere.units = "mm" + restored_sphere = _legacy_roundtrip(sphere, tmp_path / "sphere.json") + assert type(restored_sphere) is Brep + assert (restored_sphere.name, restored_sphere.guid, restored_sphere.units) == (sphere.name, sphere.guid, "mm") + assert restored_sphere.is_valid + assert restored_sphere.is_solid + assert restored_sphere.volume == pytest.approx(32.0 * pi / 3.0) diff --git a/.github/scripts/run_rhino_brep_candidate.py b/.github/scripts/run_rhino_brep_candidate.py new file mode 100644 index 0000000..247edf3 --- /dev/null +++ b/.github/scripts/run_rhino_brep_candidate.py @@ -0,0 +1,138 @@ +"""Run the BRep round trips with installed candidate wheels and the Rhino 8 bundle.""" + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +from pathlib import Path +from time import monotonic +from time import sleep +from zipfile import ZipFile + +from candidate_artifacts import sha256_file +from candidate_artifacts import verify_offline_bundle + +RHINO_BUNDLE_SHA256 = "7fde860d021bf1b1066c417310211f23a71943647304e60670a24551011b73a6" +DEFAULT_RHINOCODE = Path("/Applications/Rhino 8.app/Contents/Resources/bin/rhinocode") +HARNESS = Path(__file__).resolve().parents[1] / "brep-interchange" + +_INSTALLATION_CHECK = """ +import importlib +import sys +from importlib.metadata import distribution +from pathlib import Path + +site = Path(sys.argv[1]).resolve() +for name in ("compas", "compas_occ"): + module = importlib.import_module(name) + installed = distribution(name) + assert Path(module.__file__).resolve().is_relative_to(site), module.__file__ + assert Path(installed.locate_file("")).resolve() == site, installed.locate_file("") + print(f"{name} {installed.version} installed from the selected wheel") +""" + + +def _candidate_wheels(bundle: Path) -> tuple[Path, Path]: + manifest = verify_offline_bundle(bundle) + wheels = {item.distribution: bundle / "wheels" / item.wheel.filename for item in manifest.packages} + return wheels["compas"], wheels["compas-occ"] + + +def _rhino_id(rhinocode: Path) -> str: + result = subprocess.run([rhinocode, "list"], check=True, capture_output=True, text=True, timeout=30) + ids = re.findall(r"^\s*\d+\s+(rhinocode_remotepipe_\S+)", result.stdout, re.MULTILINE) + if len(ids) != 1: + raise ValueError("Start one Rhino 8 session or select it explicitly with --rhino-id.") + return ids[0] + + +def _run_host(rhinocode: Path, host: str, directory: Path, script: str, report_name: str) -> None: + deadline = monotonic() + 180 + subprocess.run([rhinocode, "--rhino", host, "script", directory / script], check=True, cwd=directory, timeout=180) + report_path = directory / report_name + # RhinoCode can return after dispatch, before ScriptEditor finishes. + while not report_path.is_file(): + if monotonic() >= deadline: + raise TimeoutError(f"Rhino did not produce {report_name} after running {script}.") + sleep(0.25) + report = json.loads(report_path.read_text(encoding="utf-8")) + if "error" in report: + raise ValueError(f"Rhino failed.\n{report['error']}") + if not report["rhino"].startswith("8.") or not report["python"].startswith("3.9."): + raise ValueError(f"Expected Rhino 8 with embedded Python 3.9, found Rhino {report['rhino']} with Python {report['python']}.") + for name, phase in report.items(): + if isinstance(phase, dict) and "error" in phase: + raise ValueError(f"Rhino {name} failed.\n{phase['error']}") + + +def run(wheels: tuple[Path, Path], bundle: Path, output: Path, rhinocode: Path, host: str | None) -> None: + """Install exact wheels and execute both native round trips for each fixture.""" + if sys.version_info[:2] != (3, 12): + raise ValueError("Run the OCC candidate side with Python 3.12.") + bundle = bundle.resolve(strict=True) + bundle_digest = sha256_file(bundle) + if bundle_digest != RHINO_BUNDLE_SHA256: + raise ValueError(f"Unexpected Rhino 8 bundle SHA-256 {bundle_digest}.") + + core, occ = wheels + wheels = core.resolve(strict=True), occ.resolve(strict=True) + output = output.resolve() + output.mkdir() + matrix = output / "matrix" + site = output / "site" + shutil.copytree(HARNESS, matrix, ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) + with ZipFile(bundle) as archive: + archive.extractall(matrix) + + environment = os.environ.copy() + environment.update(PIP_NO_INDEX="1", PYTHONPATH="", PYTHONNOUSERSITE="1", PYTHONDONTWRITEBYTECODE="1") + environment.pop("PYTHONOPTIMIZE", None) + subprocess.run( + [sys.executable, "-m", "pip", "install", "--no-index", "--no-deps", "--target", site, *wheels], + check=True, + cwd=matrix, + env=environment, + ) + environment["PYTHONPATH"] = str(site) + subprocess.run([sys.executable, "-c", _INSTALLATION_CHECK, site], check=True, cwd=matrix, env=environment) + evidence = { + "rhino_bundle": {"filename": bundle.name, "sha256": bundle_digest}, + "wheels": {wheel.name: sha256_file(wheel) for wheel in wheels}, + } + (output / "artifact-evidence.json").write_text(json.dumps(evidence, indent=2, sort_keys=True) + "\n", encoding="utf-8") + + def run_python(*arguments: str | Path) -> None: + subprocess.run([sys.executable, *arguments], check=True, cwd=matrix, env=environment) + + host = host or _rhino_id(rhinocode) + run_python("run_interchange.py", "occ", "export", matrix) + _run_host(rhinocode, host, matrix, "run_interchange_in_rhino.py", "rhino-interchange-host-report.json") + run_python("run_interchange.py", "occ", "import", matrix, "--source", "rhino") + run_python("run_interchange.py", "occ", "return", matrix) + _run_host(rhinocode, host, matrix, "run_return_in_rhino.py", "rhino-interchange-host-return-report.json") + run_python("test_interchange.py", matrix, "--bundle", bundle) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + selection = parser.add_mutually_exclusive_group(required=True) + selection.add_argument("--candidate-bundle", type=Path, help="Credential-free bundle from candidate artifact retrieval.") + selection.add_argument("--wheels", nargs=2, type=Path, metavar=("CORE", "OCC"), help="Two explicit local candidate wheels.") + parser.add_argument("--bundle", type=Path, required=True, help="Exact Rhino 8 codec ZIP.") + parser.add_argument("--output", type=Path, required=True, help="New directory under temporary storage.") + parser.add_argument("--rhinocode", type=Path, default=DEFAULT_RHINOCODE) + parser.add_argument("--rhino-id") + options = parser.parse_args() + if options.candidate_bundle: + wheels = _candidate_wheels(options.candidate_bundle) + else: + core, occ = options.wheels + wheels = core, occ + run(wheels, options.bundle, options.output, options.rhinocode, options.rhino_id) + + +if __name__ == "__main__": + main() diff --git a/.github/workflows/native-candidate-integration.yml b/.github/workflows/native-candidate-integration.yml index 89241b6..d75a658 100644 --- a/.github/workflows/native-candidate-integration.yml +++ b/.github/workflows/native-candidate-integration.yml @@ -11,6 +11,11 @@ on: required: false default: .github/candidates/native-linux-py312.json type: string + brep_json: + description: Require BRep JSON contracts with interchange-capable Core and OCC candidates + required: false + default: false + type: boolean workflow_dispatch: inputs: manifest_path: @@ -18,6 +23,11 @@ on: required: false default: .github/candidates/native-linux-py312.json type: string + brep_json: + description: Require BRep JSON contracts with interchange-capable Core and OCC candidates + required: false + default: false + type: boolean permissions: contents: read @@ -31,6 +41,8 @@ jobs: if: github.repository == 'compas-dev/compas_framework' && github.ref_protected runs-on: ubuntu-24.04 environment: candidate-artifact-retrieval + env: + CANDIDATE_MANIFEST: ${{ inputs.manifest_path || '.github/candidates/native-linux-py312.json' }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -42,6 +54,15 @@ jobs: with: version: "0.12.7" - run: uv sync --frozen --only-group candidate --no-install-project + - name: Locate the reviewed candidate manifest + shell: bash + run: | + if [[ ! "${CANDIDATE_MANIFEST}" =~ ^\.github/candidates/[a-zA-Z0-9][a-zA-Z0-9._-]*\.json$ ]] || + [[ ! -f "${CANDIDATE_MANIFEST}" || -L "${CANDIDATE_MANIFEST}" ]] || + ! git ls-files --error-unmatch -- "${CANDIDATE_MANIFEST}" >/dev/null; then + printf 'Select a tracked JSON manifest in .github/candidates.\n' >&2 + exit 1 + fi - id: app-token uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 with: @@ -58,7 +79,7 @@ jobs: CANDIDATE_ARTIFACT_TOKEN: ${{ steps.app-token.outputs.token }} run: >- uv run --no-sync python .github/scripts/candidate_artifacts.py retrieve - "${{ inputs.manifest_path || '.github/candidates/native-linux-py312.json' }}" + "${CANDIDATE_MANIFEST}" "${RUNNER_TEMP}/verified-native-candidates" - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: @@ -94,6 +115,8 @@ jobs: cp .github/scripts/candidate_artifacts.py "${RUNNER_TEMP}/framework-integration/harness/" cp .github/candidates/candidate_integration.py "${RUNNER_TEMP}/framework-integration/harness/" cp .github/candidates/candidate_typing_consumer.py "${RUNNER_TEMP}/framework-integration/harness/" + cp .github/candidates/candidate_brep_json.py "${RUNNER_TEMP}/framework-integration/harness/" + cp .github/candidates/brep_legacy_occ_v1.json "${RUNNER_TEMP}/framework-integration/harness/" cp .github/candidates/environment-native-linux-py312.yml "${RUNNER_TEMP}/framework-integration/harness/" cp .github/candidates/runtime-linux-py312.txt "${RUNNER_TEMP}/framework-integration/harness/" - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -155,4 +178,20 @@ jobs: --required test_installed_entry_points_discover_lightweight_plugins \ --required test_cgal_result_passes_directly_to_core_and_libigl \ --required test_occ_backend_constructs_core_brep + - name: Require installed BRep JSON contracts + if: inputs.brep_json + shell: bash -el {0} + env: + PIP_NO_INDEX: "1" + PYTHONPATH: "" + run: | + cd "${RUNNER_TEMP}/candidate-execution" + cp "${RUNNER_TEMP}/framework-integration/harness/candidate_brep_json.py" . + cp "${RUNNER_TEMP}/framework-integration/harness/brep_legacy_occ_v1.json" . + python -m pytest candidate_brep_json.py --junitxml candidate-brep-json-junit.xml + python "${RUNNER_TEMP}/framework-integration/harness/candidate_artifacts.py" verify-junit candidate-brep-json-junit.xml \ + --required test_candidate_brep_standalone_json_roundtrip \ + --required test_candidate_brep_nested_json_roundtrip \ + --required test_candidate_brep_reads_historical_occ_json \ + --required test_candidate_brep_legacy_fallback_remains_readable diff --git a/.github/workflows/rhino-brep-integration.yml b/.github/workflows/rhino-brep-integration.yml new file mode 100644 index 0000000..3ac16ec --- /dev/null +++ b/.github/workflows/rhino-brep-integration.yml @@ -0,0 +1,85 @@ +name: rhino-brep-integration + +on: + push: + branches: + - initiative/brep-json-interchange + paths: + - .github/candidates/brep-linux-py312.json + workflow_dispatch: + inputs: + manifest_path: + description: Reviewed Linux candidate manifest with BRep interchange Core and OCC wheels + required: true + type: string + +permissions: + contents: read + +concurrency: + group: rhino-brep-integration + cancel-in-progress: false + +jobs: + qualify-linux-candidates: + if: github.repository == 'compas-dev/compas_framework' && github.ref_protected + uses: ./.github/workflows/native-candidate-integration.yml + with: + manifest_path: ${{ inputs.manifest_path || '.github/candidates/brep-linux-py312.json' }} + brep_json: true + + assemble-rhino-harness: + if: github.repository == 'compas-dev/compas_framework' && github.ref_protected + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Stage the framework fixture harness + run: | + mkdir -p "${RUNNER_TEMP}/rhino-harness/scripts" + cp .github/scripts/{candidate_artifacts,run_rhino_brep_candidate}.py "${RUNNER_TEMP}/rhino-harness/scripts/" + cp -R .github/brep-interchange "${RUNNER_TEMP}/rhino-harness/" + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: rhino-brep-harness + path: ${{ runner.temp }}/rhino-harness + if-no-files-found: error + retention-days: 1 + + execute-rhino: + needs: [qualify-linux-candidates, assemble-rhino-harness] + permissions: {} + runs-on: + group: compas-rhino8 + labels: [self-hosted, macOS, rhino8] + timeout-minutes: 20 + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: verified-native-candidates + path: ${{ runner.temp }}/rhino-input-${{ github.run_id }}-${{ github.run_attempt }}/candidates + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: rhino-brep-harness + path: ${{ runner.temp }}/rhino-input-${{ github.run_id }}-${{ github.run_attempt }}/harness + - name: Run all nine fixtures through both complete native round trips + env: + RHINO8_OCC_PYTHON: ${{ vars.RHINO8_OCC_PYTHON }} + RHINO8_BREP_CODEC_ZIP: ${{ vars.RHINO8_BREP_CODEC_ZIP }} + PYTHONPATH: "" + PYTHONDONTWRITEBYTECODE: "1" + run: | + inputs="${RUNNER_TEMP}/rhino-input-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + "${RHINO8_OCC_PYTHON:?Set the path to the runner OCC Python 3.12 environment}" \ + "${inputs}/harness/scripts/run_rhino_brep_candidate.py" \ + --candidate-bundle "${inputs}/candidates" \ + --bundle "${RHINO8_BREP_CODEC_ZIP:?Set the path to the verified Rhino 8 codec ZIP}" \ + --output "${RUNNER_TEMP}/rhino-brep-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: rhino-brep-round-trip-results + path: | + ${{ runner.temp }}/rhino-brep-${{ github.run_id }}-${{ github.run_attempt }}/artifact-evidence.json + ${{ runner.temp }}/rhino-brep-${{ github.run_id }}-${{ github.run_attempt }}/matrix/*.json + if-no-files-found: error From b6379d9f4716282c90f6d71776265f2240e2ab99 Mon Sep 17 00:00:00 2001 From: tomvanmele Date: Mon, 30 Nov 2026 16:37:20 +0100 Subject: [PATCH 2/8] Document framework BRep qualification and hosted status --- .github/candidates/README.md | 7 ++++--- docs/testing.md | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/.github/candidates/README.md b/.github/candidates/README.md index ee3fe4d..9340842 100644 --- a/.github/candidates/README.md +++ b/.github/candidates/README.md @@ -147,7 +147,8 @@ non-yanked PyPI file. With no `before` value it checks all four packages before the framework can be published. Promotion reuses the selected wheels; it does not rebuild them. -The framework repository currently contains no publication job. The protected -candidate gate now passes, but framework publishing remains structurally -disabled and still requires separate explicit approval and implementation. +The framework repository currently contains no publication job. The existing +protected native gate passed for the admitted manifest above. Hosted BRep +qualification requires its own reviewed manifest and Rhino runner. +Framework publishing requires separate explicit approval and implementation. diff --git a/docs/testing.md b/docs/testing.md index 04ecce2..ae008cd 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -95,3 +95,18 @@ machine variance rather than tessellation regressions. Future benchmarks should use the existing `performance` marker with recorded input sizes, warm-up policy, backend versions, and per-backend baselines. + +## BRep JSON qualification + +The native candidate workflow can require four installed-wheel BRep +checks with `brep_json: true`. These cover standalone and nested COMPAS +JSON, a frozen OCC legacy archive, and legacy fallback. Select a reviewed +manifest containing Core and OCC wheels with the BRep interchange API. + +The separate `rhino-brep-integration.yml` workflow runs nine fixtures +through OCC → Rhino 8 → OCC and Rhino 8 → OCC → Rhino 8. It verifies each +JSON handoff and the exact Rhino codec bundle on a dedicated protected +macOS runner. The initiative's first local run passed both layers. +Hosted qualification requires the reviewed BRep-enabled manifest and +the protected Rhino runner. +[Candidate and Rhino runner instructions](https://github.com/compas-dev/compas_framework/blob/c3-upgrade/.github/candidates/README.md) From 00fa3e814623a9dc0c6f37ce74edfb7bf9008df7 Mon Sep 17 00:00:00 2001 From: tomvanmele Date: Mon, 30 Nov 2026 16:38:35 +0100 Subject: [PATCH 3/8] Preserve the documented publication gate assertion --- .github/candidates/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/candidates/README.md b/.github/candidates/README.md index 9340842..ee435bc 100644 --- a/.github/candidates/README.md +++ b/.github/candidates/README.md @@ -147,8 +147,8 @@ non-yanked PyPI file. With no `before` value it checks all four packages before the framework can be published. Promotion reuses the selected wheels; it does not rebuild them. -The framework repository currently contains no publication job. The existing -protected native gate passed for the admitted manifest above. Hosted BRep -qualification requires its own reviewed manifest and Rhino runner. -Framework publishing requires separate explicit approval and implementation. +The existing protected native gate passed for the admitted manifest above. +Hosted BRep qualification requires its own reviewed manifest and Rhino runner. +The repository has no publication job, so framework publishing remains structurally +disabled and still requires separate explicit approval and implementation. From 20fa705afd758af48709f47ac302872f0a70b02e Mon Sep 17 00:00:00 2001 From: tomvanmele Date: Mon, 30 Nov 2026 22:05:36 +0100 Subject: [PATCH 4/8] Qualify analytic BRep interchange in both kernels --- .github/brep-interchange/analytic_fixture.py | 96 +++++ .../brep-interchange-v1.schema.json | 269 +++++++++++--- .github/brep-interchange/interchange.py | 83 ++++- .../interchange_validation.py | 346 +++++++++++------- .github/brep-interchange/occ_adapter.py | 31 ++ .github/brep-interchange/rhino_adapter.py | 32 ++ .github/brep-interchange/run_in_rhino.py | 1 + .github/brep-interchange/run_interchange.py | 20 +- .github/candidates/README.md | 30 +- .github/candidates/brep_legacy_occ_v1.json | 1 - .github/candidates/candidate_brep_json.py | 60 ++- .github/scripts/run_rhino_brep_candidate.py | 10 +- .../native-candidate-integration.yml | 6 +- .github/workflows/rhino-brep-integration.yml | 4 +- docs/testing.md | 11 +- 15 files changed, 723 insertions(+), 277 deletions(-) create mode 100644 .github/brep-interchange/analytic_fixture.py delete mode 100644 .github/candidates/brep_legacy_occ_v1.json diff --git a/.github/brep-interchange/analytic_fixture.py b/.github/brep-interchange/analytic_fixture.py new file mode 100644 index 0000000..f69f50c --- /dev/null +++ b/.github/brep-interchange/analytic_fixture.py @@ -0,0 +1,96 @@ +"""Independent dimensions and invariants for the analytic solid fixtures.""" + +from collections import Counter +from collections import defaultdict +from math import hypot +from math import isclose +from math import pi + +from interchange_validation import validate + +CENTER = (1.0, -2.0, 0.5) +XAXIS = (0.6, 0.8, 0.0) +YAXIS = (-0.48, 0.36, 0.8) +ZAXIS = (0.64, -0.48, 0.6) +RADIUS = 2.0 +HEIGHT = 3.0 +MAJOR_RADIUS = 4.0 +MINOR_RADIUS = 1.0 + +# Surface types, canonical edge count, shared seam count, singular trim count. +ANALYTIC_FIXTURES = { + "sphere": (("sphere",), 1, 1, 2), + "cylinder": (("cylinder", "plane", "plane"), 3, 1, 0), + "cone": (("cone", "plane"), 2, 1, 1), + "torus": (("torus",), 2, 2, 0), +} + + +def point(x=0.0, y=0.0, z=0.0): + return tuple(center + x * axis_x + y * axis_y + z * axis_z for center, axis_x, axis_y, axis_z in zip(CENTER, XAXIS, YAXIS, ZAXIS)) + + +def signature(name, data): + validate(data) + if data["kind"] != "solid" or data["units"] != "mm": + raise ValueError(f"{name} must be an analytic solid measured in millimetres.") + component = data["components"][0] + faces = component["faces"] + shells = component["shells"] + if len(shells) != 1 or shells[0]["role"] != "outer" or sorted(shells[0]["faces"]) != list(range(len(faces))): + raise ValueError(f"{name} must have one exterior shell.") + + surfaces = tuple(sorted(face["surface"]["type"] for face in faces)) + edge_uses = defaultdict(list) + singular_trims = 0 + for face_index, face in enumerate(faces): + if len(face["loops"]) != 1 or face["loops"][0]["role"] != "outer": + raise ValueError(f"Unexpected boundary loops on {name}.") + for trim in face["loops"][0]["trims"]: + if trim["edge"] is None: + singular_trims += 1 + else: + edge_uses[trim["edge"]].append((face_index, trim["reversed"])) + seams = sum(len(uses) == 2 and uses[0][0] == uses[1][0] and uses[0][1] != uses[1][1] for uses in edge_uses.values()) + observed = (surfaces, len(component["edges"]), seams, singular_trims) + if observed != ANALYTIC_FIXTURES[name]: + raise ValueError(f"{name} has unexpected analytic topology {observed}.") + + circular_edges = sum(edge["curve"]["type"] in {"circle", "arc"} for edge in component["edges"]) + if circular_edges != {"sphere": 1, "cylinder": 2, "cone": 1, "torus": 2}[name]: + raise ValueError(f"{name} lost the analytic representation of a circular edge.") + return observed + + +def measure(name, adapter, native, data): + expected = { + "sphere": (4 * pi * RADIUS**2, 4 * pi * RADIUS**3 / 3), + "cylinder": (2 * pi * RADIUS * (RADIUS + HEIGHT), pi * RADIUS**2 * HEIGHT), + "cone": (pi * RADIUS * (RADIUS + hypot(RADIUS, HEIGHT)), pi * RADIUS**2 * HEIGHT / 3), + "torus": (4 * pi**2 * MAJOR_RADIUS * MINOR_RADIUS, 2 * pi**2 * MAJOR_RADIUS * MINOR_RADIUS**2), + } + inside = { + "sphere": point(), + "cylinder": point(z=HEIGHT / 2), + "cone": point(z=HEIGHT / 2), + "torus": point(x=MAJOR_RADIUS), + } + report = adapter.measure(native) + if not report["valid"]: + raise ValueError(f"Invalid native {name}.") + for quantity, reference in zip(("area", "volume"), expected[name]): + if not isclose(report[quantity], reference, rel_tol=1e-6): + raise ValueError(f"{name} {quantity} {report[quantity]} differs from {reference}.") + points = (inside[name], point(x=MAJOR_RADIUS + RADIUS)) + if name == "torus": + points += (point(),) + containment = adapter.classify_points(native, points) + if containment != [True] + [False] * (len(points) - 1): + raise ValueError(f"{name} changed native point containment.") + + native_surfaces = adapter.analytic_surface_types(native) + surfaces, edges, seams, singular = signature(name, data) + if Counter(native_surfaces) != Counter(surfaces): + raise ValueError(f"{name} native support surfaces {native_surfaces} disagree with the wire record.") + report.update(surface_types=sorted(native_surfaces), edges=edges, shared_seams=seams, singular_trims=singular, containment=containment) + return report diff --git a/.github/brep-interchange/brep-interchange-v1.schema.json b/.github/brep-interchange/brep-interchange-v1.schema.json index 5030702..142705b 100644 --- a/.github/brep-interchange/brep-interchange-v1.schema.json +++ b/.github/brep-interchange/brep-interchange-v1.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "urn:compas:brep:interchange:1", - "title": "Proposed COMPAS BRep interchange, version 1", + "title": "COMPAS BRep interchange, version 1", "description": "Structural validation for the plain JSON boundary representation. Reference ranges, domain ordering, knot consistency, and topology require semantic validation.", "type": "object", "additionalProperties": false, @@ -235,38 +235,30 @@ }, "curve2": { "oneOf": [ - { - "$ref": "#/$defs/line", - "properties": { "points": { "items": { "$ref": "#/$defs/point2" } } } - }, - { - "$ref": "#/$defs/nurbsCurve", - "properties": { "points": { "items": { "$ref": "#/$defs/point2" } } } - } + { "$ref": "#/$defs/uvLine" }, + { "$ref": "#/$defs/uvNurbs" }, + { "$ref": "#/$defs/circle" }, + { "$ref": "#/$defs/arc" } ] }, "curve3": { "oneOf": [ - { - "$ref": "#/$defs/line", - "properties": { "points": { "items": { "$ref": "#/$defs/point3" } } } - }, - { - "$ref": "#/$defs/nurbsCurve", - "properties": { "points": { "items": { "$ref": "#/$defs/point3" } } } - } + { "$ref": "#/$defs/line" }, + { "$ref": "#/$defs/nurbsCurve" }, + { "$ref": "#/$defs/circle" }, + { "$ref": "#/$defs/arc" } ] }, - "line": { + "uvLine": { "type": "object", "additionalProperties": false, "required": ["type", "points"], "properties": { "type": { "const": "line" }, - "points": { "type": "array", "minItems": 2, "maxItems": 2 } + "points": { "type": "array", "minItems": 2, "maxItems": 2, "items": { "$ref": "#/$defs/point2" } } } }, - "nurbsCurve": { + "uvNurbs": { "type": "object", "additionalProperties": false, "required": ["type", "degree", "knots", "points", "weights"], @@ -274,67 +266,224 @@ "type": { "const": "nurbs" }, "degree": { "$ref": "#/$defs/degree" }, "knots": { "$ref": "#/$defs/knots" }, - "points": { "type": "array", "minItems": 2 }, + "points": { "type": "array", "minItems": 2, "items": { "$ref": "#/$defs/point2" } }, "weights": { "$ref": "#/$defs/weights" } } }, + "uniqueKnots": { + "type": "array", + "minItems": 2, + "items": { "type": "number" } + }, + "multiplicities": { + "type": "array", + "minItems": 2, + "items": { "type": "integer", "minimum": 1 } + }, + "frame": { + "type": "object", + "additionalProperties": false, + "required": ["point", "xaxis", "yaxis"], + "properties": { + "point": { "$ref": "#/$defs/point3" }, + "xaxis": { "$ref": "#/$defs/point3" }, + "yaxis": { "$ref": "#/$defs/point3" } + } + }, "surface": { "oneOf": [ { "$ref": "#/$defs/plane" }, - { "$ref": "#/$defs/nurbsSurface" } + { "$ref": "#/$defs/nurbsSurface" }, + { "$ref": "#/$defs/sphere" }, + { "$ref": "#/$defs/cylinder" }, + { "$ref": "#/$defs/cone" }, + { "$ref": "#/$defs/torus" } ] }, + "line": { + "type": "object", + "additionalProperties": false, + "required": ["type", "data"], + "properties": { + "type": { "const": "line" }, + "data": { + "type": "object", + "additionalProperties": false, + "required": ["start", "end"], + "properties": { + "start": { "$ref": "#/$defs/point3" }, + "end": { "$ref": "#/$defs/point3" } + } + } + } + }, + "nurbsCurve": { + "type": "object", + "additionalProperties": false, + "required": ["type", "data"], + "properties": { + "type": { "const": "nurbs" }, + "data": { + "type": "object", + "additionalProperties": false, + "required": ["degree", "knots", "multiplicities", "points", "weights", "is_periodic"], + "properties": { + "degree": { "$ref": "#/$defs/degree" }, + "knots": { "$ref": "#/$defs/uniqueKnots" }, + "multiplicities": { "$ref": "#/$defs/multiplicities" }, + "points": { "type": "array", "minItems": 2, "items": { "$ref": "#/$defs/point3" } }, + "weights": { "$ref": "#/$defs/weights" }, + "is_periodic": { "type": "boolean" } + } + } + } + }, + "circle": { + "type": "object", + "additionalProperties": false, + "required": ["type", "data"], + "properties": { + "type": { "const": "circle" }, + "data": { + "type": "object", + "additionalProperties": false, + "required": ["radius", "frame"], + "properties": { + "radius": { "$ref": "#/$defs/positiveNumber" }, + "frame": { "$ref": "#/$defs/frame" } + } + } + } + }, + "arc": { + "type": "object", + "additionalProperties": false, + "required": ["type", "data"], + "properties": { + "type": { "const": "arc" }, + "data": { + "type": "object", + "additionalProperties": false, + "required": ["radius", "frame", "start_angle", "end_angle"], + "properties": { + "radius": { "$ref": "#/$defs/positiveNumber" }, + "frame": { "$ref": "#/$defs/frame" }, + "start_angle": { "type": "number", "minimum": 0, "maximum": 6.283185307179586 }, + "end_angle": { "type": "number", "minimum": 0, "maximum": 6.283185307179586 } + } + } + } + }, "plane": { "type": "object", "additionalProperties": false, - "required": ["type", "origin", "xaxis", "yaxis"], + "required": ["type", "data"], "properties": { "type": { "const": "plane" }, - "origin": { "$ref": "#/$defs/point3" }, - "xaxis": { "$ref": "#/$defs/point3" }, - "yaxis": { "$ref": "#/$defs/point3" } + "data": { + "type": "object", + "additionalProperties": false, + "required": ["frame", "xsize", "ysize"], + "properties": { + "frame": { "$ref": "#/$defs/frame" }, + "xsize": { "const": 1 }, + "ysize": { "const": 1 } + } + } } }, "nurbsSurface": { "type": "object", "additionalProperties": false, - "required": ["type", "degrees", "knots", "points", "weights", "periodic"], + "required": ["type", "data"], "properties": { "type": { "const": "nurbs" }, - "degrees": { - "type": "array", - "minItems": 2, - "maxItems": 2, - "items": { "$ref": "#/$defs/degree" } - }, - "knots": { - "type": "array", - "minItems": 2, - "maxItems": 2, - "items": { "$ref": "#/$defs/knots" } - }, - "points": { - "description": "Control points in points[v][u] order.", - "type": "array", - "minItems": 2, - "items": { - "type": "array", - "minItems": 2, - "items": { "$ref": "#/$defs/point3" } + "data": { + "type": "object", + "additionalProperties": false, + "required": ["control_points", "weights", "degree_u", "degree_v", "knots_u", "knots_v", "mults_u", "mults_v", "is_periodic_u", "is_periodic_v"], + "properties": { + "control_points": { "description": "Control points in control_points[v][u] order.", "type": "array", "minItems": 2, "items": { "type": "array", "minItems": 2, "items": { "$ref": "#/$defs/point3" } } }, + "weights": { "description": "Control weights in weights[v][u] order.", "type": "array", "minItems": 2, "items": { "$ref": "#/$defs/weights" } }, + "degree_u": { "$ref": "#/$defs/degree" }, + "degree_v": { "$ref": "#/$defs/degree" }, + "knots_u": { "$ref": "#/$defs/uniqueKnots" }, + "knots_v": { "$ref": "#/$defs/uniqueKnots" }, + "mults_u": { "$ref": "#/$defs/multiplicities" }, + "mults_v": { "$ref": "#/$defs/multiplicities" }, + "is_periodic_u": { "type": "boolean" }, + "is_periodic_v": { "type": "boolean" } + } + } + } + }, + "sphere": { + "type": "object", + "additionalProperties": false, + "required": ["type", "data"], + "properties": { + "type": { "const": "sphere" }, + "data": { + "type": "object", + "additionalProperties": false, + "required": ["radius", "frame"], + "properties": { + "radius": { "$ref": "#/$defs/positiveNumber" }, + "frame": { "$ref": "#/$defs/frame" } + } + } + } + }, + "cylinder": { + "type": "object", + "additionalProperties": false, + "required": ["type", "data"], + "properties": { + "type": { "const": "cylinder" }, + "data": { + "type": "object", + "additionalProperties": false, + "required": ["radius", "frame"], + "properties": { + "radius": { "$ref": "#/$defs/positiveNumber" }, + "frame": { "$ref": "#/$defs/frame" } + } + } + } + }, + "cone": { + "type": "object", + "additionalProperties": false, + "required": ["type", "data"], + "properties": { + "type": { "const": "cone" }, + "data": { + "type": "object", + "additionalProperties": false, + "required": ["radius", "frame", "height"], + "properties": { + "radius": { "$ref": "#/$defs/positiveNumber" }, + "frame": { "$ref": "#/$defs/frame" }, + "height": { "$ref": "#/$defs/positiveNumber" } + } + } + } + }, + "torus": { + "type": "object", + "additionalProperties": false, + "required": ["type", "data"], + "properties": { + "type": { "const": "torus" }, + "data": { + "type": "object", + "additionalProperties": false, + "required": ["radius_axis", "radius_pipe", "frame"], + "properties": { + "radius_axis": { "$ref": "#/$defs/positiveNumber" }, + "radius_pipe": { "$ref": "#/$defs/positiveNumber" }, + "frame": { "$ref": "#/$defs/frame" } } - }, - "weights": { - "description": "Control weights in weights[v][u] order.", - "type": "array", - "minItems": 2, - "items": { "$ref": "#/$defs/weights" } - }, - "periodic": { - "description": "Periodicity flags in U, V order.", - "type": "array", - "minItems": 2, - "maxItems": 2, - "items": { "type": "boolean" } } } } diff --git a/.github/brep-interchange/interchange.py b/.github/brep-interchange/interchange.py index e4d3387..f8118e9 100644 --- a/.github/brep-interchange/interchange.py +++ b/.github/brep-interchange/interchange.py @@ -1,6 +1,7 @@ """Executable reference API for the proposed shared BRep interchange format.""" from copy import deepcopy +from itertools import groupby from math import dist from interchange_validation import SCHEMA @@ -29,6 +30,42 @@ def _geometry_format(kind, surfaces): raise NotImplementedError("The reference adapters support planar solids and individual NURBS faces.") +def _separate_knots(full_knots): + knots = [] + multiplicities = [] + for knot, equal_knots in groupby(full_knots): + knots.append(knot) + multiplicities.append(sum(1 for _ in equal_knots)) + return knots, multiplicities + + +def _expand_knots(knots, multiplicities): + return [knot for knot, multiplicity in zip(knots, multiplicities) for _ in range(multiplicity)] + + +def _nurbs_curve_data(curve): + knots, multiplicities = _separate_knots(curve["knots"]) + return {**curve, "knots": knots, "multiplicities": multiplicities, "is_periodic": False} + + +def _nurbs_surface_data(surface): + (knots_u, mults_u), (knots_v, mults_v) = map(_separate_knots, surface["knots"]) + degree_u, degree_v = surface["degrees"] + periodic_u, periodic_v = surface.get("periodic", [False, False]) + return { + "control_points": surface["points"], + "weights": surface["weights"], + "knots_u": knots_u, + "knots_v": knots_v, + "mults_u": mults_u, + "mults_v": mults_v, + "degree_u": degree_u, + "degree_v": degree_v, + "is_periodic_u": periodic_u, + "is_periodic_v": periodic_v, + } + + def _shared_component(record): planar = record["schema"] == _PLANAR kind = "solid" if record["solid"] else "face" @@ -47,17 +84,18 @@ def _shared_component(record): if planar: edge["curve"] = { "type": "line", - "points": [list(component["vertices"][index]) for index in edge["vertices"]], + "data": dict(zip(("start", "end"), (list(component["vertices"][index]) for index in edge["vertices"]))), } else: - edge["curve"]["type"] = "nurbs" + edge["curve"] = {"type": "nurbs", "data": _nurbs_curve_data(edge["curve"])} for face in component["faces"]: face["uv_bounds"] = face.pop("domain") if planar: - face["surface"] = {"type": "plane", **face.pop("plane")} + plane = face.pop("plane") + frame = {"point": plane["origin"], "xaxis": plane["xaxis"], "yaxis": plane["yaxis"]} + face["surface"] = {"type": "plane", "data": {"frame": frame, "xsize": 1, "ysize": 1}} else: - face["surface"]["type"] = "nurbs" - face["surface"].setdefault("periodic", [False, False]) + face["surface"] = {"type": "nurbs", "data": _nurbs_surface_data(face["surface"])} for loop in face["loops"]: for trim in loop["trims"]: if planar: @@ -117,27 +155,42 @@ def _prototype_component(component): planar = schema == _PLANAR curve_type = "line" if planar else "nurbs" for edge in edges: - curve = edge["curve"] - if curve.pop("type") != curve_type: + record = edge["curve"] + if record["type"] != curve_type: raise NotImplementedError("Reference edge geometry must match the planar or NURBS adapter.") + curve = record["data"] if planar: points = [vertices[index] for index in edge["vertices"]] - if curve["points"] != points: + if [curve["start"], curve["end"]] != points: raise NotImplementedError("Reference planar edge endpoints must match the vertices exactly.") _require_linear_domain(edge["domain"], points) del edge["curve"] else: + if curve.pop("is_periodic"): + raise NotImplementedError("Reference NURBS fixtures use nonperiodic edges.") + curve["knots"] = _expand_knots(curve["knots"], curve.pop("multiplicities")) + edge["curve"] = curve _require_complete_curve(edge["domain"], curve) for face in faces: face["domain"] = face.pop("uv_bounds") - surface = face["surface"] - del surface["type"] + surface = face["surface"]["data"] if planar: - face["plane"] = face.pop("surface") - elif surface["periodic"] == [False, False]: - del surface["periodic"] - elif surface["periodic"] != [True, False]: - raise NotImplementedError("The reference NURBS adapters support periodicity in U only.") + if surface["xsize"] != 1 or surface["ysize"] != 1: + raise NotImplementedError("Reference planar fixtures use model length parameters.") + frame = surface["frame"] + face["plane"] = {"origin": frame["point"], "xaxis": frame["xaxis"], "yaxis": frame["yaxis"]} + del face["surface"] + else: + face["surface"] = { + "points": surface["control_points"], + "weights": surface["weights"], + "degrees": [surface["degree_u"], surface["degree_v"]], + "knots": [_expand_knots(surface["knots_u"], surface["mults_u"]), _expand_knots(surface["knots_v"], surface["mults_v"])], + } + if surface["is_periodic_v"]: + raise NotImplementedError("The reference NURBS adapters support periodicity in U only.") + if surface["is_periodic_u"]: + face["surface"]["periodic"] = [True, False] for loop in face["loops"]: for trim in loop["trims"]: curve = trim["curve"] diff --git a/.github/brep-interchange/interchange_validation.py b/.github/brep-interchange/interchange_validation.py index bdaf01f..82c3726 100644 --- a/.github/brep-interchange/interchange_validation.py +++ b/.github/brep-interchange/interchange_validation.py @@ -1,152 +1,200 @@ """Validate shared BRep JSON structure and indexed topology without a native kernel.""" +from __future__ import annotations + from collections import defaultdict from math import isclose -from math import isfinite +from math import tau +from sys import float_info SCHEMA = "compas.brep.interchange" VERSION = 1 -def _require(condition, path, message): +def _require(condition: object, path: str, message: str) -> None: if not condition: raise ValueError(f"{path}: {message}") -def _record(value, path, fields=None): - _require(isinstance(value, dict), path, "expected a JSON object") +def _record(value: object, path: str, fields: str | None = None) -> dict[str, object]: + if not isinstance(value, dict): + raise ValueError(f"{path}: expected a JSON object") if fields is not None: _require(value.keys() == set(fields.split()), path, f"expected fields {fields}") return value -def _array(value, path, size=None): - _require(isinstance(value, list), path, "expected a JSON array") +def _array(value: object, path: str, size: int | None = None) -> list[object]: + if not isinstance(value, list): + raise ValueError(f"{path}: expected a JSON array") if size is not None: _require(len(value) == size, path, f"expected {size} entries") return value -def _number(value, path): - _require( - type(value) is int or (type(value) is float and isfinite(value)), - path, - "expected a finite number", - ) - return value +def _number(value: object, path: str) -> float: + if (type(value) is int or type(value) is float) and -float_info.max <= value <= float_info.max: + return value + raise ValueError(f"{path}: expected a finite number in the floating-point range") -def _positive(value, path): +def _positive(value: object, path: str) -> None: _require(_number(value, path) > 0, path, "expected a positive number") -def _flag(value, path): - _require(type(value) is bool, path, "expected a boolean") +def _flag(value: object, path: str) -> bool: + if type(value) is not bool: + raise ValueError(f"{path}: expected a boolean") + return value -def _reference(value, size, path): - _require(type(value) is int and 0 <= value < size, path, "index out of range") +def _reference(value: object, size: int, path: str) -> int: + if type(value) is not int or not 0 <= value < size: + raise ValueError(f"{path}: index out of range") return value -def _coordinates(value, dimension, path): - for index, coordinate in enumerate(_array(value, path, dimension)): - _number(coordinate, f"{path}[{index}]") +def _coordinates(value: object, dimension: int, path: str) -> list[float]: + return [_number(coordinate, f"{path}[{index}]") for index, coordinate in enumerate(_array(value, path, dimension))] -def _interval(value, path): - _coordinates(value, 2, path) - _require(value[0] < value[1], path, "expected an ascending interval") +def _interval(value: object, path: str) -> tuple[float, float]: + start, end = _coordinates(value, 2, path) + _require(start < end, path, "expected an ascending interval") + return start, end -def _knots(knots, degree, count, path): - _require( - type(degree) is int and 1 <= degree < count, - path, - "degree must be positive and less than the control point count", - ) - values = _array(knots, path, count + degree + 1) - for index, value in enumerate(values): - _number(value, f"{path}[{index}]") +def _knots(knots: object, degree: object, count: int, path: str) -> tuple[int, list[float]]: + if type(degree) is not int or not 1 <= degree < count: + raise ValueError(f"{path}: degree must be positive and less than the control point count") + values = _coordinates(knots, count + degree + 1, path) _require(values == sorted(values), path, "knots must be nondecreasing") _require(values[degree] < values[count], path, "knot support must have positive length") - return values[degree], values[count] + return degree, values -def _weights(value, count, path): - for index, weight in enumerate(_array(value, path, count)): +def _weights(value: object, count: int, path: str) -> list[object]: + weights = _array(value, path, count) + for index, weight in enumerate(weights): _positive(weight, f"{path}[{index}]") + return weights + + +def _native_knots(knots: object, mults: object, degree: object, count: int, path: str) -> tuple[int, list[float]]: + values = _coordinates(knots, len(_array(knots, path)), path) + _require(all(a < b for a, b in zip(values, values[1:])), path, "unique knots must increase") + counts = _array(mults, f"{path} multiplicities", len(values)) + if type(degree) is not int or not 1 <= degree < count: + raise ValueError(f"{path}: degree must be positive and less than the control point count") + multiplicities: list[int] = [] + for value in counts: + if type(value) is not int or not 1 <= value <= degree + 1: + raise ValueError(f"{path}: invalid knot multiplicity") + multiplicities.append(value) + _require(sum(multiplicities) == count + degree + 1, path, "wrong expanded knot count") + return _knots([knot for knot, mult in zip(values, multiplicities) for _ in range(mult)], degree, count, path) + + +def _frame(value: object, path: str, *, planar: bool = False) -> None: + frame = _record(value, path, "point xaxis yaxis") + point = _coordinates(frame["point"], 3, f"{path}.point") + xaxis = _coordinates(frame["xaxis"], 3, f"{path}.xaxis") + yaxis = _coordinates(frame["yaxis"], 3, f"{path}.yaxis") + for key, axis in (("xaxis", xaxis), ("yaxis", yaxis)): + _require( + all(abs(value) <= 1.0 + 1e-9 for value in axis) and isclose(sum(value * value for value in axis), 1, rel_tol=0, abs_tol=1e-9), + f"{path}.{key}", + "expected a unit axis", + ) + _require(abs(sum(x * y for x, y in zip(xaxis, yaxis))) <= 1e-9, path, "frame axes must be orthogonal") + if planar: + _require(all(abs(vector[2]) <= 1e-9 for vector in (point, xaxis, yaxis)), path, "a UV frame must lie in the XY plane") + + +def _circular_curve(curve: dict[str, object], domain: tuple[float, float], path: str, *, planar: bool) -> None: + _record(curve, path, "type data") + path = f"{path}.data" + fields = "frame radius" if curve["type"] == "circle" else "frame radius start_angle end_angle" + geometry = _record(curve["data"], path, fields) + _frame(geometry["frame"], f"{path}.frame", planar=planar) + _positive(geometry["radius"], f"{path}.radius") + if curve["type"] == "circle": + _require(domain[1] - domain[0] <= tau + 1e-9, path, "expected at most one full turn") + else: + start = _number(geometry["start_angle"], f"{path}.start_angle") + end = _number(geometry["end_angle"], f"{path}.end_angle") + _require(0 <= start < end <= tau, path, "expected increasing angles within [0, 2π]") + _require(start - 1e-9 <= domain[0] < domain[1] <= end + 1e-9, path, "effective domain falls outside the arc") -def _curve(curve, dimension, domain, path): - curve = _record(curve, path) +def _curve(value: object, dimension: int, domain: tuple[float, float], path: str) -> None: + curve = _record(value, path) kind = curve.get("type") - if kind == "line": + if kind in ("circle", "arc"): + _circular_curve(curve, domain, path, planar=dimension == 2) + return + if dimension == 3: + _record(curve, path, "type data") + path = f"{path}.data" + geometry = _record(curve["data"], path) + if kind == "line": + _record(geometry, path, "start end") + _coordinates(geometry["start"], 3, f"{path}.start") + _coordinates(geometry["end"], 3, f"{path}.end") + return + _require(kind == "nurbs", path, "expected a line, NURBS, circle or arc") + _record(geometry, path, "degree knots multiplicities points weights is_periodic") + points = _array(geometry["points"], f"{path}.points") + _flag(geometry["is_periodic"], f"{path}.is_periodic") + degree, knots = _native_knots(geometry["knots"], geometry["multiplicities"], geometry["degree"], len(points), f"{path}.knots") + elif kind == "line": _record(curve, path, "type points") - points = _array(curve["points"], f"{path}.points", 2) + for index, point in enumerate(_array(curve["points"], f"{path}.points", 2)): + _coordinates(point, 2, f"{path}.points[{index}]") + return else: - _require(kind == "nurbs", path, "expected a line or NURBS curve") - _record(curve, path, "type degree knots points weights") - points = _array(curve["points"], f"{path}.points") - _weights(curve["weights"], len(points), f"{path}.weights") - lower, upper = _knots(curve["knots"], curve["degree"], len(points), f"{path}.knots") - _require( - lower <= domain[0] < domain[1] <= upper, - path, - "effective domain falls outside the knot support", - ) + _require(kind == "nurbs", path, "expected a line, NURBS, circle or arc") + geometry = _record(curve, path, "type degree knots points weights") + points = _array(geometry["points"], f"{path}.points") + degree, knots = _knots(geometry["knots"], geometry["degree"], len(points), f"{path}.knots") + _weights(geometry["weights"], len(points), f"{path}.weights") + _require(knots[degree] <= domain[0] < domain[1] <= knots[len(points)], path, "effective domain falls outside the knot support") for index, point in enumerate(points): _coordinates(point, dimension, f"{path}.points[{index}]") -def _surface(surface, path): - surface = _record(surface, path) - kind = surface.get("type") - if kind == "plane": - _record(surface, path, "type origin xaxis yaxis") - for key in ("origin", "xaxis", "yaxis"): - _coordinates(surface[key], 3, f"{path}.{key}") - xaxis, yaxis = surface["xaxis"], surface["yaxis"] - for key, axis in (("xaxis", xaxis), ("yaxis", yaxis)): - _require( - all(abs(value) <= 1.0 + 1e-9 for value in axis) and isclose(sum(value * value for value in axis), 1, rel_tol=0, abs_tol=1e-9), - f"{path}.{key}", - "expected a unit axis", - ) - _require( - abs(sum(x * y for x, y in zip(xaxis, yaxis))) <= 1e-9, - path, - "plane axes must be orthogonal", - ) - return - - _require(kind == "nurbs", path, "expected a plane or NURBS surface") - _record(surface, path, "type degrees knots points weights periodic") - degrees = _array(surface["degrees"], f"{path}.degrees", 2) - knots = _array(surface["knots"], f"{path}.knots", 2) - points = _array(surface["points"], f"{path}.points") - _require(points, f"{path}.points", "expected a control net") - count_u = len(_array(points[0], f"{path}.points[0]")) - weights = _array(surface["weights"], f"{path}.weights", len(points)) - for v, (row, weight_row) in enumerate(zip(points, weights)): - for u, point in enumerate(_array(row, f"{path}.points[{v}]", count_u)): - _coordinates(point, 3, f"{path}.points[{v}][{u}]") - _weights(weight_row, count_u, f"{path}.weights[{v}]") - periodic = _array(surface["periodic"], f"{path}.periodic", 2) - for axis, count in enumerate((count_u, len(points))): - degree, axis_knots = degrees[axis], knots[axis] - knot_path = f"{path}.knots[{axis}]" - lower, upper = _knots(axis_knots, degree, count, knot_path) - _flag(periodic[axis], f"{path}.periodic[{axis}]") - if periodic[axis]: +def _nurbs_surface(surface: object, path: str) -> None: + geometry = _record( + surface, + path, + "degree_u degree_v knots_u knots_v mults_u mults_v control_points weights is_periodic_u is_periodic_v", + ) + points = _array(geometry["control_points"], f"{path}.control_points") + _require(points, f"{path}.control_points", "expected a control net") + count_u = len(_array(points[0], f"{path}.control_points[0]")) + weights = _array(geometry["weights"], f"{path}.weights", len(points)) + point_rows = [] + weight_rows = [] + for v, (point_row, weight_row) in enumerate(zip(points, weights)): + row = _array(point_row, f"{path}.control_points[{v}]", count_u) + for u, point in enumerate(row): + _coordinates(point, 3, f"{path}.control_points[{v}][{u}]") + point_rows.append(row) + weight_rows.append(_weights(weight_row, count_u, f"{path}.weights[{v}]")) + for axis, count in (("u", count_u), ("v", len(points))): + knot_path = f"{path}.knots_{axis}" + degree, axis_knots = _native_knots(geometry[f"knots_{axis}"], geometry[f"mults_{axis}"], geometry[f"degree_{axis}"], count, knot_path) + if _flag(geometry[f"is_periodic_{axis}"], f"{path}.is_periodic_{axis}"): shift = count - degree + period = axis_knots[count] - axis_knots[degree] _require( - all(isclose(end - start, upper - lower, rel_tol=1e-9) for start, end in zip(axis_knots, axis_knots[shift:])), + 0 < period <= float_info.max + and all(delta <= float_info.max and isclose(delta, period, rel_tol=1e-9) for delta in (end - start for start, end in zip(axis_knots, axis_knots[shift:]))), knot_path, "periodic knots must repeat at the active period", ) - for key, net in (("points", points), ("weights", weights)): - rows = net if axis == 0 else zip(*net) + for key, net in (("control_points", point_rows), ("weights", weight_rows)): + rows = net if axis == "u" else zip(*net) _require( all(row[:degree] == row[-degree:] for row in rows), f"{path}.{key}", @@ -154,40 +202,70 @@ def _surface(surface, path): ) -def _edge(edge, vertex_count, path): - edge = _record(edge, path, "vertices domain curve") - endpoints = _array(edge["vertices"], f"{path}.vertices", 2) - for index, vertex in enumerate(endpoints): - _reference(vertex, vertex_count, f"{path}.vertices[{index}]") - _interval(edge["domain"], f"{path}.domain") - _curve(edge["curve"], 3, edge["domain"], f"{path}.curve") - return endpoints - - -def _trim(trim, edges, vertex_count, path): - trim = _record(trim, path) +def _surface(data: object, path: str) -> None: + surface = _record(data, path, "type data") + kind = surface["type"] + path = f"{path}.data" + if kind == "nurbs": + _nurbs_surface(surface["data"], path) + return + geometry = _record(surface["data"], path) + if kind == "plane": + _record(geometry, path, "frame xsize ysize") + for key in ("xsize", "ysize"): + _require(_number(geometry[key], f"{path}.{key}") == 1, f"{path}.{key}", "planar chart sizes must be one") + elif kind == "torus": + _record(geometry, path, "frame radius_axis radius_pipe") + for key in ("radius_axis", "radius_pipe"): + _positive(geometry[key], f"{path}.{key}") + _require(_number(geometry["radius_axis"], path) > _number(geometry["radius_pipe"], path), path, "expected a ring torus") + else: + _require(kind in ("sphere", "cylinder", "cone"), path, "expected a supported analytic or NURBS surface") + _record(geometry, path, "frame radius height" if kind == "cone" else "frame radius") + _positive(geometry["radius"], f"{path}.radius") + if kind == "cone": + _positive(geometry["height"], f"{path}.height") + _frame(geometry["frame"], f"{path}.frame") + + +def _edge(data: object, vertex_count: int, path: str) -> tuple[int, int]: + edge = _record(data, path, "vertices domain curve") + start, end = _array(edge["vertices"], f"{path}.vertices", 2) + start = _reference(start, vertex_count, f"{path}.vertices[0]") + end = _reference(end, vertex_count, f"{path}.vertices[1]") + domain = _interval(edge["domain"], f"{path}.domain") + _curve(edge["curve"], 3, domain, f"{path}.curve") + return start, end + + +def _trim(data: object, edges: list[tuple[int, int]], vertex_count: int, path: str) -> tuple[tuple[int, int], tuple[int, bool] | None]: + trim = _record(data, path) if trim.get("edge") is None: _record(trim, path, "edge vertex domain curve") pole = _reference(trim["vertex"], vertex_count, f"{path}.vertex") endpoints = (pole, pole) + use = None else: _record(trim, path, "edge reversed domain curve") edge = _reference(trim["edge"], len(edges), f"{path}.edge") - _flag(trim["reversed"], f"{path}.reversed") - endpoints = edges[edge][::-1] if trim["reversed"] else edges[edge] - _interval(trim["domain"], f"{path}.domain") - _curve(trim["curve"], 2, trim["domain"], f"{path}.curve") - return endpoints + reversed_trim = _flag(trim["reversed"], f"{path}.reversed") + start, end = edges[edge] + endpoints = (end, start) if reversed_trim else (start, end) + use = edge, reversed_trim + domain = _interval(trim["domain"], f"{path}.domain") + _curve(trim["curve"], 2, domain, f"{path}.curve") + return endpoints, use -def _face(face, edges, vertex_count, path): - face = _record(face, path, "surface uv_bounds reversed loops") +def _face(data: object, edges: list[tuple[int, int]], vertex_count: int, path: str) -> tuple[dict[int, list[bool]], set[int]]: + face = _record(data, path, "surface uv_bounds reversed loops") _surface(face["surface"], f"{path}.surface") for axis, bounds in enumerate(_array(face["uv_bounds"], f"{path}.uv_bounds", 2)): _interval(bounds, f"{path}.uv_bounds[{axis}]") - _flag(face["reversed"], f"{path}.reversed") + reversed_face = _flag(face["reversed"], f"{path}.reversed") roles = [] - uses = defaultdict(list) + uses: dict[int, list[bool]] = defaultdict(list) + singular_vertices: set[int] = set() for loop_index, loop in enumerate(_array(face["loops"], f"{path}.loops")): loop_path = f"{path}.loops[{loop_index}]" loop = _record(loop, loop_path, "role trims") @@ -201,9 +279,13 @@ def _face(face, edges, vertex_count, path): _require(trims, loop_path, "a loop requires at least one trim") endpoints = [] for index, trim in enumerate(trims): - endpoints.append(_trim(trim, edges, vertex_count, f"{loop_path}.trims[{index}]")) - if trim["edge"] is not None: - uses[trim["edge"]].append(trim["reversed"] != face["reversed"]) + vertices, use = _trim(trim, edges, vertex_count, f"{loop_path}.trims[{index}]") + endpoints.append(vertices) + if use is None: + singular_vertices.add(vertices[0]) + else: + edge, reversed_trim = use + uses[edge].append(reversed_trim != reversed_face) for index, (_, end) in enumerate(endpoints): _require( end == endpoints[(index + 1) % len(endpoints)][0], @@ -219,12 +301,12 @@ def _face(face, edges, vertex_count, path): path, "paired seam trims must use opposite orientations", ) - return uses + return uses, singular_vertices -def _shells(shells, face_count, uses, path): - face_owners = {} - members = [] +def _shells(shells: object, face_count: int, uses: dict[int, list[tuple[int, bool]]], path: str) -> None: + face_owners: dict[int, int] = {} + members: list[set[int]] = [] roles = [] for index, shell in enumerate(_array(shells, path)): shell_path = f"{path}[{index}]" @@ -235,10 +317,9 @@ def _shells(shells, face_count, uses, path): "expected an outer or inner shell", ) roles.append(shell["role"]) - faces = _array(shell["faces"], f"{shell_path}.faces") + faces = [_reference(face, face_count, f"{shell_path}.faces") for face in _array(shell["faces"], f"{shell_path}.faces")] _require(faces, shell_path, "a shell requires at least one face") for face in faces: - _reference(face, face_count, f"{shell_path}.faces") _require( face not in face_owners, shell_path, @@ -249,7 +330,7 @@ def _shells(shells, face_count, uses, path): _require(roles.count("outer") == 1, path, "a solid requires exactly one outer shell") _require(len(face_owners) == face_count, path, "shells must partition all solid faces") - adjacent = defaultdict(set) + adjacent: dict[int, set[int]] = defaultdict(set) for incidences in uses.values(): _require(len(incidences) == 2, path, "a shell edge requires two incidences") (first, forward), (second, backward) = incidences @@ -276,9 +357,9 @@ def _shells(shells, face_count, uses, path): _require(visited == faces, f"{path}[{index}]", "shell faces must be connected") -def _component(component, kind, path): +def _component(data: object, kind: object, path: str) -> None: fields = "kind vertices edges faces shells" if kind == "solid" else "kind vertices edges faces" - component = _record(component, path, fields) + component = _record(data, path, fields) _require(component["kind"] == kind, path, f"expected a {kind} component") vertices = _array(component["vertices"], f"{path}.vertices") _require(vertices, path, "a component requires at least one vertex") @@ -288,13 +369,14 @@ def _component(component, kind, path): faces = _array(component["faces"], f"{path}.faces") if kind == "face": _require(len(faces) == 1, path, "a face component contains exactly one face") - uses = defaultdict(list) + uses: dict[int, list[tuple[int, bool]]] = defaultdict(list) + referenced_vertices = {vertex for edge in edges for vertex in edge} for face_index, face in enumerate(faces): - for edge, orientations in _face(face, edges, len(vertices), f"{path}.faces[{face_index}]").items(): + face_uses, singular_vertices = _face(face, edges, len(vertices), f"{path}.faces[{face_index}]") + referenced_vertices.update(singular_vertices) + for edge, orientations in face_uses.items(): uses[edge].extend((face_index, orientation) for orientation in orientations) _require(len(uses) == len(edges), path, "every edge must have a trim") - referenced_vertices = {vertex for edge in edges for vertex in edge} - referenced_vertices.update(trim["vertex"] for face in faces for loop in face["loops"] for trim in loop["trims"] if trim["edge"] is None) _require( len(referenced_vertices) == len(vertices), f"{path}.vertices", @@ -304,9 +386,9 @@ def _component(component, kind, path): _shells(component["shells"], len(faces), uses, f"{path}.shells") -def validate(data): +def validate(value: object) -> None: """Raise ValueError for malformed structure or invalid indexed topology.""" - data = _record(data, "$", "schema version units tolerances kind components") + data = _record(value, "$", "schema version units tolerances kind components") _require(data["schema"] == SCHEMA, "$.schema", "unsupported BRep interchange schema") _require( type(data["version"]) is int and data["version"] == VERSION, diff --git a/.github/brep-interchange/occ_adapter.py b/.github/brep-interchange/occ_adapter.py index 2147e12..b132bc2 100644 --- a/.github/brep-interchange/occ_adapter.py +++ b/.github/brep-interchange/occ_adapter.py @@ -1,11 +1,20 @@ """Open CASCADE adapter for the planar BRep interchange prototype.""" +from analytic_fixture import CENTER +from analytic_fixture import HEIGHT +from analytic_fixture import MAJOR_RADIUS +from analytic_fixture import MINOR_RADIUS +from analytic_fixture import RADIUS +from analytic_fixture import XAXIS +from analytic_fixture import ZAXIS from OCC.Core import BRep +from OCC.Core import BRepAdaptor from OCC.Core import BRepBuilderAPI from OCC.Core import BRepCheck from OCC.Core import BRepClass3d from OCC.Core import BRepGProp from OCC.Core import BRepPrimAPI +from OCC.Core import GeomAbs from OCC.Core import GProp from OCC.Core import TopAbs from OCC.Core import TopExp @@ -77,9 +86,31 @@ def make_fixture(name: str) -> TopoDS.TopoDS_Shape: shape = face.Face() shape.Reverse() return shape + axis = gp.gp_Ax2(gp.gp_Pnt(*CENTER), gp.gp_Dir(*ZAXIS), gp.gp_Dir(*XAXIS)) + if name == "sphere": + return BRepPrimAPI.BRepPrimAPI_MakeSphere(axis, RADIUS).Solid() + if name == "cylinder": + return BRepPrimAPI.BRepPrimAPI_MakeCylinder(axis, RADIUS, HEIGHT).Solid() + if name == "cone": + return BRepPrimAPI.BRepPrimAPI_MakeCone(axis, RADIUS, 0.0, HEIGHT).Solid() + if name == "torus": + return BRepPrimAPI.BRepPrimAPI_MakeTorus(axis, MAJOR_RADIUS, MINOR_RADIUS).Solid() raise ValueError(f"Unknown OCC fixture: {name}") +def analytic_surface_types(shape: TopoDS.TopoDS_Shape) -> list[str]: + """Read the analytic support types from native OCC face adaptors.""" + kinds = { + GeomAbs.GeomAbs_Plane: "plane", + GeomAbs.GeomAbs_Sphere: "sphere", + GeomAbs.GeomAbs_Cylinder: "cylinder", + GeomAbs.GeomAbs_Cone: "cone", + GeomAbs.GeomAbs_Torus: "torus", + } + faces = _index(shape, TopAbs.TopAbs_FACE) + return [kinds.get(BRepAdaptor.BRepAdaptor_Surface(TopoDS.topods.Face(faces(i))).GetType(), "other") for i in range(1, faces.Size() + 1)] + + def measure(shape: TopoDS.TopoDS_Shape) -> dict[str, bool | float]: """Measure native validity, area and solid volume.""" area = GProp.GProp_GProps() diff --git a/.github/brep-interchange/rhino_adapter.py b/.github/brep-interchange/rhino_adapter.py index 148c3ad..2216fc8 100644 --- a/.github/brep-interchange/rhino_adapter.py +++ b/.github/brep-interchange/rhino_adapter.py @@ -1,6 +1,14 @@ """Planar BRep interchange probe for Rhino 8 and its embedded Python.""" import Rhino.Geometry as rg +from analytic_fixture import CENTER +from analytic_fixture import HEIGHT +from analytic_fixture import MAJOR_RADIUS +from analytic_fixture import MINOR_RADIUS +from analytic_fixture import RADIUS +from analytic_fixture import XAXIS +from analytic_fixture import YAXIS +from analytic_fixture import point from System import Array SCHEMA = "compas.brep.planar-prototype" @@ -60,9 +68,33 @@ def make_fixture(name): if not brep.Faces[0].OrientationIsReversed: brep.Flip() return brep + frame = rg.Plane(rg.Point3d(*CENTER), rg.Vector3d(*XAXIS), rg.Vector3d(*YAXIS)) + if name == "sphere": + return rg.Sphere(frame, RADIUS).ToBrep() + if name == "cylinder": + return rg.Cylinder(rg.Circle(frame, RADIUS), HEIGHT).ToBrep(True, True) + if name == "cone": + # Rhino places the apex at the plane origin and the base along its normal. + apex = rg.Plane(rg.Point3d(*point(z=HEIGHT)), rg.Vector3d(*XAXIS), -rg.Vector3d(*YAXIS)) + return rg.Cone(apex, HEIGHT, RADIUS).ToBrep(True) + if name == "torus": + return rg.Torus(frame, MAJOR_RADIUS, MINOR_RADIUS).ToBrep() raise ValueError("Unknown fixture: " + name) +def analytic_surface_types(brep): + """Read the analytic support types from the underlying Rhino surfaces.""" + kinds = { + "plane": "IsPlanar", + "sphere": "IsSphere", + "cylinder": "IsCylinder", + "cone": "IsCone", + "torus": "IsTorus", + } + surfaces = [face.UnderlyingSurface() for face in brep.Faces] + return [next((kind for kind, method in kinds.items() if getattr(surface, method)(TOLERANCE)), "other") for surface in surfaces] + + def measure(brep): return { "valid": brep.IsValid, diff --git a/.github/brep-interchange/run_in_rhino.py b/.github/brep-interchange/run_in_rhino.py index 1884aee..3ff0b78 100644 --- a/.github/brep-interchange/run_in_rhino.py +++ b/.github/brep-interchange/run_in_rhino.py @@ -31,6 +31,7 @@ def _staged_modules(directory): names = ( "run_probe", "run_interchange", + "analytic_fixture", "interchange", "interchange_validation", "rhino_adapter", diff --git a/.github/brep-interchange/run_interchange.py b/.github/brep-interchange/run_interchange.py index b583e20..5c78c75 100644 --- a/.github/brep-interchange/run_interchange.py +++ b/.github/brep-interchange/run_interchange.py @@ -12,6 +12,9 @@ from pathlib import Path from typing import Literal +from analytic_fixture import ANALYTIC_FIXTURES +from analytic_fixture import measure as measure_analytic +from analytic_fixture import signature as analytic_signature from interchange import from_prototype_data from interchange import to_prototype_data from interchange_validation import validate @@ -25,7 +28,7 @@ from run_probe import _save from run_probe import _signature -FIXTURE_NAMES = (*FIXTURES, "compound", *NURBS_FIXTURES) +FIXTURE_NAMES = (*FIXTURES, "compound", *NURBS_FIXTURES, *ANALYTIC_FIXTURES) INVALID_GEOMETRY_CASES = ("face", "cavity") Backend = Literal["occ", "rhino"] Phase = Literal["export", "import", "return"] @@ -40,6 +43,8 @@ def _fixture_adapter(backend, name): def _fixture_signature(name, data): + if name in ANALYTIC_FIXTURES: + return analytic_signature(name, data) # Reuse the existing independent fixture assertions against the # relevant topology and geometry after converting its record layout. record = to_prototype_data(data) @@ -54,6 +59,8 @@ def _fixture_signature(name, data): def _measure_fixture(backend, adapter, name, native, data): + if name in ANALYTIC_FIXTURES: + return measure_analytic(name, adapter, native, data) if name == "compound": planar_adapter = importlib.import_module(f"{backend}_adapter") return _measure_compound(adapter, native, planar_adapter) @@ -89,8 +96,6 @@ def read_brep(data): def write_brep(native, *, units): brep = Brep(native_brep=native, units=units) data = json.loads(brep.to_jsonstring(minimal=True))["data"] - if data["schema"] != "compas.brep.interchange": - raise ValueError("A supported OCC fixture fell back to legacy JSON.") return data return read_brep, write_brep @@ -110,12 +115,13 @@ def _check_invalid_geometry(backend, name, data, read_brep): edges = {trim["edge"] for face in faces for loop in face["loops"] for trim in loop["trims"]} vertices = {vertex for index in edges for vertex in component["edges"][index]["vertices"]} for face in faces: - face["surface"]["origin"][0] += 20.0 + face["surface"]["data"]["frame"]["point"][0] += 20.0 for index in vertices: component["vertices"][index][0] += 20.0 for index in edges: - for point in component["edges"][index]["curve"]["points"]: - point[0] += 20.0 + line = component["edges"][index]["curve"]["data"] + line["start"][0] += 20.0 + line["end"][0] += 20.0 expected_errors = (ValueError,) if backend == "occ": @@ -152,7 +158,7 @@ def _stage(backend: Backend, phase: Phase, source: Backend | None) -> tuple[str, def run(backend: Backend, phase: Phase, directory: Path, source: Backend | None = None) -> dict: - """Export, reconstruct, or return all nine native fixtures.""" + """Export, reconstruct, or return the native fixture matrix.""" directory.mkdir(parents=True, exist_ok=True) read_brep, write_brep = _codec(backend) output_prefix, input_prefix, origin = _stage(backend, phase, source) diff --git a/.github/candidates/README.md b/.github/candidates/README.md index ee435bc..e93a470 100644 --- a/.github/candidates/README.md +++ b/.github/candidates/README.md @@ -87,15 +87,8 @@ outside the checkouts with the installed candidate wheels. - Standalone Core BRep JSON uses the shared schema and preserves the native solid, units, name, and GUID. - Nested COMPAS JSON preserves BReps and other COMPAS objects. -- The frozen OCC v1 archive loads through the existing reader. -- A valid shape outside the shared codec's supported geometry uses readable legacy JSON. - -The frozen archive was written with pre-interchange Core -`1c0ce44eea89be64a208cca7f6e21b53040af8e9`, OCC -`7fdf2ffb57d1de16308020e14ec626d79e65a034`, and OCCT 7.9.0. Its SHA-256 is -`984fa34b7df5e21305b5cb1fe11e8cd3927d6da5632cef65a055871e755d242a`. -Keep it as a historical input when updating the writers. -[Frozen archive](brep_legacy_occ_v1.json) +- A BRep with unknown units raises an error through the standard writer. +- A native analytic sphere round-trips through the shared schema, including its pole trims. The Rhino workflow first requires those Linux checks. A reviewed manifest at `.github/candidates/brep-linux-py312.json` triggers the workflow when @@ -111,17 +104,21 @@ RhinoCode enabled and Python 3.9 available in the host. Set `RHINO8_OCC_PYTHON` to the absolute path of the runner's Python 3.12 environment with `pythonocc-core`, `packaging`, and `jsonschema` available. Set `RHINO8_BREP_CODEC_ZIP` to the runner-local path of the Rhino package's -verified bundle. The harness checks the archive hash and the hashes of +verified bundle and `RHINO8_BREP_CODEC_SHA256` to its reviewed SHA-256. +The harness checks the archive hash and the hashes of the codec modules that were loaded in Rhino. This job runs on a protected framework ref and receives the candidate artifacts without repository permissions. [Rhino workflow](../workflows/rhino-brep-integration.yml) · [Runner group access](https://docs.github.com/en/actions/how-tos/manage-runners/self-hosted-runners/manage-access) -Each of the nine fixtures travels OCC → Rhino 8 → OCC and Rhino 8 → OCC → -Rhino 8. The returning host reads the intermediate kernel's re-export. -The verifier checks the exact payload handed across each leg and compares -native validity, geometry, topology, and cavity membership. It also checks -both orders of the native Rhino compound tuple. +All thirteen fixtures travel OCC → Rhino 8 → OCC and Rhino 8 → OCC → +Rhino 8. They cover the original nine fixtures and native spherical, +capped cylindrical, capped conical, and toroidal solids. The returning +host reads the intermediate kernel's re-export. The verifier checks each +handoff, native validity, geometry, topology, and cavity membership. For +analytic solids it checks native surface types, shared seam edges, singular +trims, area, volume, and point containment. It also checks both orders of +the native Rhino compound tuple. For a local run from the framework checkout, use the OCC environment and provide the exact wheels and Rhino ZIP. @@ -130,7 +127,8 @@ provide the exact wheels and Rhino ZIP. work=$(mktemp -d) python .github/scripts/run_rhino_brep_candidate.py \ --wheels /absolute/path/to/compas.whl /absolute/path/to/compas_occ.whl \ - --bundle /absolute/path/to/compas-rhino8-brep-codec-1.0.0.zip \ + --bundle /absolute/path/to/compas-rhino8-brep-codec-1.1.0.zip \ + --bundle-sha256 '' \ --output "$work/results" ``` diff --git a/.github/candidates/brep_legacy_occ_v1.json b/.github/candidates/brep_legacy_occ_v1.json deleted file mode 100644 index 7112da5..0000000 --- a/.github/candidates/brep_legacy_occ_v1.json +++ /dev/null @@ -1 +0,0 @@ -{"dtype":"compas.geometry/Brep","data":{"schema":"compas.brep","version":1,"units":null,"geometry":{"representation":"embedded"},"topology":{"representation":"components","shape_type":2,"components":[{"shape_type":2,"faces":[{"type":0,"surface":{"dtype":"compas.geometry/Plane","data":{"point":[-0.5,-1.5,-1.0],"normal":[1.0,0.0,-0.0]},"guid":"f0a0cc73-9a6f-4e9b-9af4-bbb6be0bc5e0"},"domain_u":[0.0,2.0],"domain_v":[-3.0,0.0],"frame":{"dtype":"compas.geometry/Frame","data":{"point":[0.0,0.0,0.0],"xaxis":[1.0,0.0,0.0],"yaxis":[0.0,1.0,0.0]},"guid":"36e80935-5572-4968-8836-b58e677999f2"},"loops":[[{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,-1.5,-1.0],"end":[-0.5,-1.5,1.0]},"guid":"85aa848f-df99-465f-8955-38bba580b955"},"domain":[0.0,2.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,-1.0],"guid":"1e538268-ea1e-4a8e-ab02-d69b0f04ff85"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,1.0],"guid":"d4337443-a988-4754-a34d-8356afcb36b4"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,-1.5,1.0],"end":[-0.5,1.5,1.0]},"guid":"7ca57b7d-9490-4515-97a1-8967091a6549"},"domain":[0.0,3.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,1.0],"guid":"58798ce3-8e4a-43bb-a9ac-ca3d73120f81"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,1.0],"guid":"5c5de02e-6575-433f-87dd-8aab97593b48"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,1.5,1.0],"end":[-0.5,1.5,-1.0]},"guid":"1fb8bf88-cc07-4805-b5f8-0833dfc53f30"},"domain":[0.0,2.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,1.0],"guid":"d48b34a9-5363-48b3-9bd7-935c57e33d99"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,-1.0],"guid":"483a57fc-509a-46c3-a5cb-72cc9485be90"},"orientation":1,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,1.5,-1.0],"end":[-0.5,-1.5,-1.0]},"guid":"3991a03e-fe19-4e48-b94e-fdaad01b5f1c"},"domain":[0.0,3.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,-1.0],"guid":"6c5a363e-03ab-4f00-b4db-ab399b598e39"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,-1.0],"guid":"45130676-0cc8-4d2c-a568-f10f285bfb65"},"orientation":1,"dimension":3}]],"orientation":1},{"type":0,"surface":{"dtype":"compas.geometry/Plane","data":{"point":[0.5,-1.5,-1.0],"normal":[1.0,0.0,-0.0]},"guid":"b3b9ee1b-1d47-4e96-9aef-b3274101c693"},"domain_u":[0.0,2.0],"domain_v":[-3.0,0.0],"frame":{"dtype":"compas.geometry/Frame","data":{"point":[0.0,0.0,0.0],"xaxis":[1.0,0.0,0.0],"yaxis":[0.0,1.0,0.0]},"guid":"33b7fb3f-05b0-4994-8a75-3008ac1f7f89"},"loops":[[{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,-1.5,1.0],"end":[0.5,-1.5,-1.0]},"guid":"8f54b762-51cf-48a5-8264-ea4e9def2ad7"},"domain":[0.0,2.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,1.0],"guid":"40e54826-4e79-4c50-b661-84170ba54ba9"},"end":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,-1.0],"guid":"e76f831d-e6ea-4121-9245-92a08b262374"},"orientation":1,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,-1.5,-1.0],"end":[0.5,1.5,-1.0]},"guid":"66f9f977-1e69-4017-8c75-3eedd14b22cc"},"domain":[0.0,3.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,-1.0],"guid":"52620278-b82a-494f-9820-3eb966302a45"},"end":{"dtype":"compas.geometry/Point","data":[0.5,1.5,-1.0],"guid":"ae9ef2de-b319-4ea1-9c50-25ee91db1c2d"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,1.5,-1.0],"end":[0.5,1.5,1.0]},"guid":"4f0122f1-1225-4ff2-9005-fdee05ffbfb0"},"domain":[0.0,2.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,1.5,-1.0],"guid":"a2374c59-0f12-4b77-a0a3-509bfc369c4c"},"end":{"dtype":"compas.geometry/Point","data":[0.5,1.5,1.0],"guid":"4be2d015-9f04-4e9c-b4af-d48e4ab68f27"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,1.5,1.0],"end":[0.5,-1.5,1.0]},"guid":"57fd147a-8278-4e53-919a-bbd2a220841d"},"domain":[0.0,3.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,1.5,1.0],"guid":"ca38e916-9c6c-458e-9833-49e0520fbdb2"},"end":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,1.0],"guid":"346ebd02-e5fd-4b54-ae44-055a257a814c"},"orientation":1,"dimension":3}]],"orientation":0},{"type":0,"surface":{"dtype":"compas.geometry/Plane","data":{"point":[-0.5,-1.5,-1.0],"normal":[-0.0,1.0,0.0]},"guid":"429f099f-9f7d-4b07-a535-03e65645cc3c"},"domain_u":[0.0,2.0],"domain_v":[0.0,1.0],"frame":{"dtype":"compas.geometry/Frame","data":{"point":[0.0,0.0,0.0],"xaxis":[1.0,0.0,0.0],"yaxis":[0.0,1.0,0.0]},"guid":"708b9f62-a1e8-4158-bdc2-1dbad475e277"},"loops":[[{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,-1.5,-1.0],"end":[0.5,-1.5,-1.0]},"guid":"da6ac301-22bd-47f6-b758-612620a8ec35"},"domain":[0.0,1.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,-1.0],"guid":"6557c586-1d12-42a9-99a6-90947b03a160"},"end":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,-1.0],"guid":"db81fe10-abdc-47b6-99aa-5dda1e1bcbcb"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,-1.5,-1.0],"end":[0.5,-1.5,1.0]},"guid":"1162e79f-dcfd-4b30-b1f7-59facf6fbc71"},"domain":[0.0,2.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,-1.0],"guid":"3145473d-9988-4c35-bbe7-9393d35b0e78"},"end":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,1.0],"guid":"9ea1d74f-3340-41de-8148-d82b4e8e0d37"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,-1.5,1.0],"end":[-0.5,-1.5,1.0]},"guid":"2b7399dd-0169-448c-9cb6-ade5be947592"},"domain":[0.0,1.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,1.0],"guid":"d3c95f15-60a6-428b-bb3d-107b7eb6cfdc"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,1.0],"guid":"bb61f4b0-2de3-4b7f-8bc7-b5f1590fd384"},"orientation":1,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,-1.5,1.0],"end":[-0.5,-1.5,-1.0]},"guid":"26415c8d-c25a-424f-aa75-e5ea6201c3f4"},"domain":[0.0,2.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,1.0],"guid":"0990c754-8304-4b9b-a612-d056e72b9406"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,-1.0],"guid":"5cab1616-ed52-4859-b92e-12cd65facd1e"},"orientation":1,"dimension":3}]],"orientation":1},{"type":0,"surface":{"dtype":"compas.geometry/Plane","data":{"point":[-0.5,1.5,-1.0],"normal":[-0.0,1.0,0.0]},"guid":"4e75e340-f7c3-4434-905d-eb28585ad35f"},"domain_u":[0.0,2.0],"domain_v":[0.0,1.0],"frame":{"dtype":"compas.geometry/Frame","data":{"point":[0.0,0.0,0.0],"xaxis":[1.0,0.0,0.0],"yaxis":[0.0,1.0,0.0]},"guid":"553f7f47-fb1d-407b-978c-75ce0a349ebd"},"loops":[[{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,1.5,-1.0],"end":[-0.5,1.5,-1.0]},"guid":"5fe15820-3f8a-48f6-a420-7ac211d92109"},"domain":[0.0,1.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,1.5,-1.0],"guid":"76e2e85b-73fd-4eeb-bd01-addc10a8bb85"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,-1.0],"guid":"c6845db8-cecf-4833-b38c-51c6a7a8ca0e"},"orientation":1,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,1.5,-1.0],"end":[-0.5,1.5,1.0]},"guid":"adeec082-30e4-4827-a1ab-5a683eaa3ab4"},"domain":[0.0,2.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,-1.0],"guid":"8822b8f9-464d-4643-a26f-b39bdae86f01"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,1.0],"guid":"d6a46b7c-ced9-4305-89fe-5f96cb8e9b0a"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,1.5,1.0],"end":[0.5,1.5,1.0]},"guid":"6ab20f08-79a7-40bf-8faa-17b8d9ad705b"},"domain":[0.0,1.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,1.0],"guid":"7704c1c4-7ecf-4628-9eb8-fca571237177"},"end":{"dtype":"compas.geometry/Point","data":[0.5,1.5,1.0],"guid":"2a9e38c6-91c2-49b5-8912-49dc35fcc5b6"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,1.5,1.0],"end":[0.5,1.5,-1.0]},"guid":"c4ca0997-d728-4ce3-bc4d-201050660366"},"domain":[0.0,2.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,1.5,1.0],"guid":"2592436c-c032-430a-aa97-683a40d5a9af"},"end":{"dtype":"compas.geometry/Point","data":[0.5,1.5,-1.0],"guid":"02c36511-54d1-44df-a0b1-8c40c201f04b"},"orientation":1,"dimension":3}]],"orientation":0},{"type":0,"surface":{"dtype":"compas.geometry/Plane","data":{"point":[-0.5,-1.5,-1.0],"normal":[0.0,0.0,1.0]},"guid":"e9701190-2cc7-437c-9383-b12e8eec7f8c"},"domain_u":[0.0,1.0],"domain_v":[0.0,3.0],"frame":{"dtype":"compas.geometry/Frame","data":{"point":[0.0,0.0,0.0],"xaxis":[1.0,0.0,0.0],"yaxis":[0.0,1.0,0.0]},"guid":"49c7a0eb-ff78-4bce-8616-6f17d06daa7c"},"loops":[[{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,-1.5,-1.0],"end":[-0.5,1.5,-1.0]},"guid":"2ce9fd49-6179-45ac-a9e4-f670af98fde0"},"domain":[0.0,3.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,-1.0],"guid":"6deaddc8-fd68-42bd-aacd-24a48aa13e46"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,-1.0],"guid":"2d3f8b72-11bc-494f-b445-e3d7202533bf"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,1.5,-1.0],"end":[0.5,1.5,-1.0]},"guid":"bdd6dded-d608-457c-889b-7b46c9010972"},"domain":[0.0,1.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,-1.0],"guid":"52b3d59f-048f-4564-80e2-3e89da9918e1"},"end":{"dtype":"compas.geometry/Point","data":[0.5,1.5,-1.0],"guid":"249d4fa6-3a48-4f5b-8821-30c9331902f8"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,1.5,-1.0],"end":[0.5,-1.5,-1.0]},"guid":"bdac4b28-cb2f-40ca-88fa-1c934a5e3b53"},"domain":[0.0,3.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,1.5,-1.0],"guid":"0552a0e4-470c-4d08-a62e-b5caac5d79bf"},"end":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,-1.0],"guid":"c99e1025-6c0a-4584-98e2-cb22f9913dcf"},"orientation":1,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,-1.5,-1.0],"end":[-0.5,-1.5,-1.0]},"guid":"a67e8583-71ab-4ee3-8149-930bc9474a44"},"domain":[0.0,1.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,-1.0],"guid":"eff4329f-c1a5-427c-8577-b60523b88d4f"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,-1.0],"guid":"2621eb6e-f01c-4111-9f7a-3c8a97b7e847"},"orientation":1,"dimension":3}]],"orientation":1},{"type":0,"surface":{"dtype":"compas.geometry/Plane","data":{"point":[-0.5,-1.5,1.0],"normal":[0.0,0.0,1.0]},"guid":"3a8e219e-6dae-4749-803a-987ace596fb2"},"domain_u":[0.0,1.0],"domain_v":[0.0,3.0],"frame":{"dtype":"compas.geometry/Frame","data":{"point":[0.0,0.0,0.0],"xaxis":[1.0,0.0,0.0],"yaxis":[0.0,1.0,0.0]},"guid":"f1b4c5b0-74bc-49c6-9a2f-16dd274f4b5f"},"loops":[[{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,1.5,1.0],"end":[-0.5,-1.5,1.0]},"guid":"98f25553-051d-45da-b835-6475948dbaf6"},"domain":[0.0,3.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,1.0],"guid":"10fe73bf-8c54-4b0b-aeac-81244608c098"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,1.0],"guid":"ef4b8752-a5b2-4d76-bbd4-fe2c00491d50"},"orientation":1,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[-0.5,-1.5,1.0],"end":[0.5,-1.5,1.0]},"guid":"acf2c49c-3c40-4ce2-8f1f-7d77b50594f4"},"domain":[0.0,1.0],"start":{"dtype":"compas.geometry/Point","data":[-0.5,-1.5,1.0],"guid":"5500ae9a-73d3-4072-bc79-51fefa9f7ba7"},"end":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,1.0],"guid":"56986023-c089-4254-9dbb-80e5060f9f1d"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,-1.5,1.0],"end":[0.5,1.5,1.0]},"guid":"44ee520f-0f86-4589-8b13-cf11f544ae2d"},"domain":[0.0,3.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,-1.5,1.0],"guid":"7e1fabb3-497e-4e33-908d-075e5dc7cbd8"},"end":{"dtype":"compas.geometry/Point","data":[0.5,1.5,1.0],"guid":"42e30571-c66e-43ee-a059-df0bffe522c8"},"orientation":0,"dimension":3},{"type":0,"curve":{"dtype":"compas.geometry/LineCurve","data":{"start":[0.5,1.5,1.0],"end":[-0.5,1.5,1.0]},"guid":"f0240586-c641-44c9-8279-199764f0bf33"},"domain":[0.0,1.0],"start":{"dtype":"compas.geometry/Point","data":[0.5,1.5,1.0],"guid":"41391943-2f6e-46a1-8c67-7c5d2fc4cb87"},"end":{"dtype":"compas.geometry/Point","data":[-0.5,1.5,1.0],"guid":"2fecc4d8-ff1e-4216-ba95-9a40e81fbeae"},"orientation":1,"dimension":3}]],"orientation":0}]}]},"native":{"backend":"occ","format":"brep","encoding":"base64","data":"REJSZXBfRHJhd2FibGVTaGFwZQoKQ0FTQ0FERSBUb3BvbG9neSBWMywgKGMpIE9wZW4gQ2FzY2FkZQpMb2NhdGlvbnMgMApDdXJ2ZTJkcyAyNAoxIDAgMCAxIDAgCjEgMCAwIDEgMCAKMSAyIDAgMCAtMSAKMSAwIDAgMCAxIAoxIDAgLTMgMSAwIAoxIDAgMCAxIDAgCjEgMCAwIDAgLTEgCjEgMCAwIDAgMSAKMSAwIDAgMSAwIAoxIDAgMSAxIDAgCjEgMiAwIDAgLTEgCjEgMSAwIDAgMSAKMSAwIC0zIDEgMCAKMSAwIDEgMSAwIAoxIDAgMCAwIC0xIAoxIDEgMCAwIDEgCjEgMCAwIDAgMSAKMSAwIDAgMSAwIAoxIDIgMCAwIDEgCjEgMCAwIDEgMCAKMSAwIDAgMCAxIAoxIDAgMyAxIDAgCjEgMiAwIDAgMSAKMSAwIDMgMSAwIApDdXJ2ZXMgMTIKMSAtMC41IC0xLjUgLTEgMCAwIDEgCjEgLTAuNSAtMS41IDEgLTAgMSAwIAoxIC0wLjUgMS41IC0xIDAgMCAxIAoxIC0wLjUgLTEuNSAtMSAtMCAxIDAgCjEgMC41IC0xLjUgLTEgMCAwIDEgCjEgMC41IC0xLjUgMSAtMCAxIDAgCjEgMC41IDEuNSAtMSAwIDAgMSAKMSAwLjUgLTEuNSAtMSAtMCAxIDAgCjEgLTAuNSAtMS41IC0xIDEgMCAtMCAKMSAtMC41IC0xLjUgMSAxIDAgLTAgCjEgLTAuNSAxLjUgLTEgMSAwIC0wIAoxIC0wLjUgMS41IDEgMSAwIC0wIApQb2x5Z29uM0QgMApQb2x5Z29uT25Ucmlhbmd1bGF0aW9ucyAwClN1cmZhY2VzIDYKMSAtMC41IC0xLjUgLTEgMSAwIC0wIDAgMCAxIDAgLTEgMCAKMSAtMC41IC0xLjUgLTEgLTAgMSAwIDAgMCAxIDEgMCAtMCAKMSAtMC41IC0xLjUgMSAwIDAgMSAxIDAgLTAgLTAgMSAwIAoxIC0wLjUgMS41IC0xIC0wIDEgMCAwIDAgMSAxIDAgLTAgCjEgLTAuNSAtMS41IC0xIDAgMCAxIDEgMCAtMCAtMCAxIDAgCjEgMC41IC0xLjUgLTEgMSAwIC0wIDAgMCAxIDAgLTEgMCAKVHJpYW5ndWxhdGlvbnMgMAoKVFNoYXBlcyAzNApWZQoxZS0wNwotMC41IC0xLjUgMQowIDAKCjAxMDExMDEKKgpWZQoxZS0wNwotMC41IC0xLjUgLTEKMCAwCgowMTAxMTAxCioKRWQKIDFlLTA3IDEgMSAwCjEgIDEgMCAwIDIKMiAgMSAxIDAgMCAyCjIgIDIgMiAwIDAgMgowCgowMTAxMDAwCi0zNCAwICszMyAwICoKVmUKMWUtMDcKLTAuNSAxLjUgMQowIDAKCjAxMDExMDEKKgpFZAogMWUtMDcgMSAxIDAKMSAgMiAwIDAgMwoyICAzIDEgMCAwIDMKMiAgNCAzIDAgMCAzCjAKCjAxMDEwMDAKLTMxIDAgKzM0IDAgKgpWZQoxZS0wNwotMC41IDEuNSAtMQowIDAKCjAxMDExMDEKKgpFZAogMWUtMDcgMSAxIDAKMSAgMyAwIDAgMgoyICA1IDEgMCAwIDIKMiAgNiA0IDAgMCAyCjAKCjAxMDEwMDAKLTMxIDAgKzI5IDAgKgpFZAogMWUtMDcgMSAxIDAKMSAgNCAwIDAgMwoyICA3IDEgMCAwIDMKMiAgOCA1IDAgMCAzCjAKCjAxMDEwMDAKLTI5IDAgKzMzIDAgKgpXaQoKMDEwMTEwMAotMzIgMCAtMzAgMCArMjggMCArMjcgMCAqCkZhCjAgIDFlLTA3IDEgMAoKMDExMTAwMAorMjYgMCAqClZlCjFlLTA3CjAuNSAtMS41IDEKMCAwCgowMTAxMTAxCioKVmUKMWUtMDcKMC41IC0xLjUgLTEKMCAwCgowMTAxMTAxCioKRWQKIDFlLTA3IDEgMSAwCjEgIDUgMCAwIDIKMiAgOSA2IDAgMCAyCjIgIDEwIDIgMCAwIDIKMAoKMDEwMTAwMAotMjQgMCArMjMgMCAqClZlCjFlLTA3CjAuNSAxLjUgMQowIDAKCjAxMDExMDEKKgpFZAogMWUtMDcgMSAxIDAKMSAgNiAwIDAgMwoyICAxMSA2IDAgMCAzCjIgIDEyIDMgMCAwIDMKMAoKMDEwMTAwMAotMjEgMCArMjQgMCAqClZlCjFlLTA3CjAuNSAxLjUgLTEKMCAwCgowMTAxMTAxCioKRWQKIDFlLTA3IDEgMSAwCjEgIDcgMCAwIDIKMiAgMTMgNiAwIDAgMgoyICAxNCA0IDAgMCAyCjAKCjAxMDEwMDAKLTIxIDAgKzE5IDAgKgpFZAogMWUtMDcgMSAxIDAKMSAgOCAwIDAgMwoyICAxNSA2IDAgMCAzCjIgIDE2IDUgMCAwIDMKMAoKMDEwMTAwMAotMTkgMCArMjMgMCAqCldpCgowMTAxMTAwCi0yMiAwIC0yMCAwICsxOCAwICsxNyAwICoKRmEKMCAgMWUtMDcgNiAwCgowMTExMDAwCisxNiAwICoKRWQKIDFlLTA3IDEgMSAwCjEgIDkgMCAwIDEKMiAgMTcgMiAwIDAgMQoyICAxOCA1IDAgMCAxCjAKCjAxMDEwMDAKLTIzIDAgKzMzIDAgKgpFZAogMWUtMDcgMSAxIDAKMSAgMTAgMCAwIDEKMiAgMTkgMiAwIDAgMQoyICAyMCAzIDAgMCAxCjAKCjAxMDEwMDAKLTI0IDAgKzM0IDAgKgpXaQoKMDEwMTEwMAotMTQgMCAtMjIgMCArMTMgMCArMzIgMCAqCkZhCjAgIDFlLTA3IDIgMAoKMDExMTAwMAorMTIgMCAqCkVkCiAxZS0wNyAxIDEgMAoxICAxMSAwIDAgMQoyICAyMSA0IDAgMCAxCjIgIDIyIDUgMCAwIDEKMAoKMDEwMTAwMAotMTkgMCArMjkgMCAqCkVkCiAxZS0wNyAxIDEgMAoxICAxMiAwIDAgMQoyICAyMyA0IDAgMCAxCjIgIDI0IDMgMCAwIDEKMAoKMDEwMTAwMAotMjEgMCArMzEgMCAqCldpCgowMTAxMTAwCi0xMCAwIC0xOCAwICs5IDAgKzI4IDAgKgpGYQowICAxZS0wNyA0IDAKCjAxMTEwMDAKKzggMCAqCldpCgowMTAxMTAwCi0yNyAwIC0xMCAwICsxNyAwICsxNCAwICoKRmEKMCAgMWUtMDcgNSAwCgowMTExMDAwCis2IDAgKgpXaQoKMDEwMTEwMAotMzAgMCAtOSAwICsyMCAwICsxMyAwICoKRmEKMCAgMWUtMDcgMyAwCgowMTExMDAwCis0IDAgKgpTaAoKMDEwMTEwMAotMjUgMCArMTUgMCAtMTEgMCArNyAwIC01IDAgKzMgMCAqClNvCgoxMTAwMDAwCisyIDAgKgoKKzEgMCA="}},"name":"Legacy asymmetric box","guid":"2aeeb908-a305-4faf-8db5-821bc5c78ded"} \ No newline at end of file diff --git a/.github/candidates/candidate_brep_json.py b/.github/candidates/candidate_brep_json.py index 4b6662b..1fa27b1 100644 --- a/.github/candidates/candidate_brep_json.py +++ b/.github/candidates/candidate_brep_json.py @@ -11,11 +11,9 @@ from compas.geometry import Brep from compas.geometry import Point from compas.geometry import Sphere +from compas.geometry import SphericalSurface from compas.geometry import brep_json_context -_LEGACY_ARCHIVE = Path(__file__).with_name("brep_legacy_occ_v1.json") -_LEGACY_GUID = UUID("2aeeb908-a305-4faf-8db5-821bc5c78ded") - def _box_brep() -> Brep: brep = Brep.from_box(Box.from_width_height_depth(1.0, 2.0, 3.0)) @@ -46,7 +44,7 @@ def test_candidate_brep_standalone_json_roundtrip(tmp_path: Path) -> None: assert envelope["data"]["schema"] == "compas.brep.interchange" assert envelope["data"]["version"] == 1 assert envelope["data"]["units"] == "mm" - assert "native" not in envelope["data"] + assert envelope["data"] == source.__data__ with brep_json_context(backend="occ"): restored = Brep.from_json(archive) @@ -73,39 +71,39 @@ def test_candidate_brep_nested_json_roundtrip(tmp_path: Path) -> None: assert restored[1] == point -def test_candidate_brep_reads_historical_occ_json() -> None: - envelope = json.loads(_LEGACY_ARCHIVE.read_text(encoding="utf-8")) - assert envelope["dtype"] == "compas.geometry/Brep" - assert envelope["data"]["schema"] == "compas.brep" - assert envelope["data"]["version"] == 1 - assert envelope["data"]["native"]["backend"] == "occ" - - restored = Brep.from_json(_LEGACY_ARCHIVE) - - _assert_box(restored, name="Legacy asymmetric box", guid=_LEGACY_GUID, units=None) - - -def _legacy_roundtrip(source: Brep, archive: Path) -> Brep: - source.to_json(archive) - envelope = json.loads(archive.read_text(encoding="utf-8")) - assert envelope["dtype"] == "compas.geometry/Brep" - assert envelope["data"]["schema"] == "compas.brep" - assert envelope["data"]["version"] == 1 - assert envelope["data"]["units"] == source.units - assert envelope["data"]["native"]["backend"] == "occ" - return Brep.from_json(archive) - - -def test_candidate_brep_legacy_fallback_remains_readable(tmp_path: Path) -> None: +def test_candidate_brep_requires_units(tmp_path: Path) -> None: box = _box_brep() box.units = None - restored_box = _legacy_roundtrip(box, tmp_path / "unitless-box.json") - _assert_box(restored_box, name=box.name, guid=box.guid, units=None) + with pytest.raises(ValueError, match="unit"): + box.to_json(tmp_path / "unitless-box.json") + +def test_candidate_brep_analytic_json_roundtrip(tmp_path: Path) -> None: sphere = Brep.from_sphere(Sphere(2.0)) sphere.name = "Candidate analytic sphere" sphere.units = "mm" - restored_sphere = _legacy_roundtrip(sphere, tmp_path / "sphere.json") + archive = tmp_path / "sphere.json" + + sphere.to_json(archive) + data = json.loads(archive.read_text(encoding="utf-8"))["data"] + (face,) = data["components"][0]["faces"] + assert face["surface"]["type"] == "sphere" + surface = SphericalSurface.__from_data__(face["surface"]["data"]) + assert surface.radius == pytest.approx(2.0) + component = data["components"][0] + assert len([trim for trim in face["loops"][0]["trims"] if trim["edge"] is None]) == 2 + for trim in face["loops"][0]["trims"]: + if trim["edge"] is None: + vertices = [trim["vertex"]] * 2 + else: + vertices = component["edges"][trim["edge"]]["vertices"] + if trim["reversed"]: + vertices = vertices[::-1] + for uv, index in zip(trim["curve"]["points"], vertices): + assert list(surface.point_at(*uv)) == pytest.approx(component["vertices"][index]) + with brep_json_context(backend="occ"): + restored_sphere = Brep.from_json(archive) + assert type(restored_sphere) is Brep assert (restored_sphere.name, restored_sphere.guid, restored_sphere.units) == (sphere.name, sphere.guid, "mm") assert restored_sphere.is_valid diff --git a/.github/scripts/run_rhino_brep_candidate.py b/.github/scripts/run_rhino_brep_candidate.py index 247edf3..eb79781 100644 --- a/.github/scripts/run_rhino_brep_candidate.py +++ b/.github/scripts/run_rhino_brep_candidate.py @@ -15,7 +15,6 @@ from candidate_artifacts import sha256_file from candidate_artifacts import verify_offline_bundle -RHINO_BUNDLE_SHA256 = "7fde860d021bf1b1066c417310211f23a71943647304e60670a24551011b73a6" DEFAULT_RHINOCODE = Path("/Applications/Rhino 8.app/Contents/Resources/bin/rhinocode") HARNESS = Path(__file__).resolve().parents[1] / "brep-interchange" @@ -68,14 +67,14 @@ def _run_host(rhinocode: Path, host: str, directory: Path, script: str, report_n raise ValueError(f"Rhino {name} failed.\n{phase['error']}") -def run(wheels: tuple[Path, Path], bundle: Path, output: Path, rhinocode: Path, host: str | None) -> None: +def run(wheels: tuple[Path, Path], bundle: Path, bundle_sha256: str, output: Path, rhinocode: Path, host: str | None) -> None: """Install exact wheels and execute both native round trips for each fixture.""" if sys.version_info[:2] != (3, 12): raise ValueError("Run the OCC candidate side with Python 3.12.") bundle = bundle.resolve(strict=True) bundle_digest = sha256_file(bundle) - if bundle_digest != RHINO_BUNDLE_SHA256: - raise ValueError(f"Unexpected Rhino 8 bundle SHA-256 {bundle_digest}.") + if bundle_digest != bundle_sha256: + raise ValueError(f"Rhino 8 bundle has SHA-256 {bundle_digest}, expected {bundle_sha256}.") core, occ = wheels wheels = core.resolve(strict=True), occ.resolve(strict=True) @@ -122,6 +121,7 @@ def main() -> None: selection.add_argument("--candidate-bundle", type=Path, help="Credential-free bundle from candidate artifact retrieval.") selection.add_argument("--wheels", nargs=2, type=Path, metavar=("CORE", "OCC"), help="Two explicit local candidate wheels.") parser.add_argument("--bundle", type=Path, required=True, help="Exact Rhino 8 codec ZIP.") + parser.add_argument("--bundle-sha256", required=True, help="SHA-256 from the reviewed Rhino codec build.") parser.add_argument("--output", type=Path, required=True, help="New directory under temporary storage.") parser.add_argument("--rhinocode", type=Path, default=DEFAULT_RHINOCODE) parser.add_argument("--rhino-id") @@ -131,7 +131,7 @@ def main() -> None: else: core, occ = options.wheels wheels = core, occ - run(wheels, options.bundle, options.output, options.rhinocode, options.rhino_id) + run(wheels, options.bundle, options.bundle_sha256, options.output, options.rhinocode, options.rhino_id) if __name__ == "__main__": diff --git a/.github/workflows/native-candidate-integration.yml b/.github/workflows/native-candidate-integration.yml index d75a658..97cd480 100644 --- a/.github/workflows/native-candidate-integration.yml +++ b/.github/workflows/native-candidate-integration.yml @@ -116,7 +116,6 @@ jobs: cp .github/candidates/candidate_integration.py "${RUNNER_TEMP}/framework-integration/harness/" cp .github/candidates/candidate_typing_consumer.py "${RUNNER_TEMP}/framework-integration/harness/" cp .github/candidates/candidate_brep_json.py "${RUNNER_TEMP}/framework-integration/harness/" - cp .github/candidates/brep_legacy_occ_v1.json "${RUNNER_TEMP}/framework-integration/harness/" cp .github/candidates/environment-native-linux-py312.yml "${RUNNER_TEMP}/framework-integration/harness/" cp .github/candidates/runtime-linux-py312.txt "${RUNNER_TEMP}/framework-integration/harness/" - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -187,11 +186,10 @@ jobs: run: | cd "${RUNNER_TEMP}/candidate-execution" cp "${RUNNER_TEMP}/framework-integration/harness/candidate_brep_json.py" . - cp "${RUNNER_TEMP}/framework-integration/harness/brep_legacy_occ_v1.json" . python -m pytest candidate_brep_json.py --junitxml candidate-brep-json-junit.xml python "${RUNNER_TEMP}/framework-integration/harness/candidate_artifacts.py" verify-junit candidate-brep-json-junit.xml \ --required test_candidate_brep_standalone_json_roundtrip \ --required test_candidate_brep_nested_json_roundtrip \ - --required test_candidate_brep_reads_historical_occ_json \ - --required test_candidate_brep_legacy_fallback_remains_readable + --required test_candidate_brep_requires_units \ + --required test_candidate_brep_analytic_json_roundtrip diff --git a/.github/workflows/rhino-brep-integration.yml b/.github/workflows/rhino-brep-integration.yml index 3ac16ec..a18a855 100644 --- a/.github/workflows/rhino-brep-integration.yml +++ b/.github/workflows/rhino-brep-integration.yml @@ -63,10 +63,11 @@ jobs: with: name: rhino-brep-harness path: ${{ runner.temp }}/rhino-input-${{ github.run_id }}-${{ github.run_attempt }}/harness - - name: Run all nine fixtures through both complete native round trips + - name: Run all fixtures through both complete native round trips env: RHINO8_OCC_PYTHON: ${{ vars.RHINO8_OCC_PYTHON }} RHINO8_BREP_CODEC_ZIP: ${{ vars.RHINO8_BREP_CODEC_ZIP }} + RHINO8_BREP_CODEC_SHA256: ${{ vars.RHINO8_BREP_CODEC_SHA256 }} PYTHONPATH: "" PYTHONDONTWRITEBYTECODE: "1" run: | @@ -75,6 +76,7 @@ jobs: "${inputs}/harness/scripts/run_rhino_brep_candidate.py" \ --candidate-bundle "${inputs}/candidates" \ --bundle "${RHINO8_BREP_CODEC_ZIP:?Set the path to the verified Rhino 8 codec ZIP}" \ + --bundle-sha256 "${RHINO8_BREP_CODEC_SHA256:?Set the reviewed Rhino 8 codec ZIP SHA-256}" \ --output "${RUNNER_TEMP}/rhino-brep-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: diff --git a/docs/testing.md b/docs/testing.md index ae008cd..cc560fc 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -100,13 +100,14 @@ per-backend baselines. The native candidate workflow can require four installed-wheel BRep checks with `brep_json: true`. These cover standalone and nested COMPAS -JSON, a frozen OCC legacy archive, and legacy fallback. Select a reviewed +JSON, a missing unit declaration, and an analytic sphere. Select a reviewed manifest containing Core and OCC wheels with the BRep interchange API. -The separate `rhino-brep-integration.yml` workflow runs nine fixtures +The separate `rhino-brep-integration.yml` workflow runs thirteen fixtures through OCC → Rhino 8 → OCC and Rhino 8 → OCC → Rhino 8. It verifies each JSON handoff and the exact Rhino codec bundle on a dedicated protected -macOS runner. The initiative's first local run passed both layers. -Hosted qualification requires the reviewed BRep-enabled manifest and -the protected Rhino runner. +macOS runner. The fixtures include native sphere, cylinder, cone and +torus solids with checks for retained analytic geometry, seams and poles. +Hosted qualification requires the reviewed BRep-enabled manifest, the +Rhino codec bundle SHA-256 and the protected Rhino runner. [Candidate and Rhino runner instructions](https://github.com/compas-dev/compas_framework/blob/c3-upgrade/.github/candidates/README.md) From d21d6233c34ac879ad3ef8dd9cdea70cf54a0ae4 Mon Sep 17 00:00:00 2001 From: tomvanmele Date: Tue, 1 Dec 2026 10:10:18 +0100 Subject: [PATCH 5/8] Admit exact Core and OCC wheels for BRep qualification --- .github/candidates/README.md | 18 +++- .github/candidates/brep-linux-py312.json | 61 +++++++++++ .github/scripts/candidate_artifacts.py | 63 +++++++---- .github/scripts/run_rhino_brep_candidate.py | 2 +- .github/tests/test_candidate_artifacts.py | 100 +++++++++++++----- .../native-candidate-integration.yml | 22 ++-- docs/testing.md | 10 +- tests/test_package.py | 2 +- 8 files changed, 212 insertions(+), 66 deletions(-) create mode 100644 .github/candidates/brep-linux-py312.json diff --git a/.github/candidates/README.md b/.github/candidates/README.md index e93a470..c2f53bb 100644 --- a/.github/candidates/README.md +++ b/.github/candidates/README.md @@ -80,9 +80,21 @@ repository-settings check remains an explicit human trust boundary. ## BRep JSON qualification -Use a reviewed manifest that includes the BRep interchange revisions of -Core and `compas_occ`. Set `brep_json: true` when calling or dispatching -the native candidate workflow. The Linux job runs four required checks +Use `brep-linux-py312.json` for the protected BRep qualification. It +contains exactly the reviewed Core and `compas_occ` wheels used by the +Rhino matrix. The BRep path uses the same repository, workflow, PR, +archive, wheel hash, and metadata checks as the four-package native +integration path. + +Validate the BRep manifest with the repository verifier. + +```sh +python .github/scripts/candidate_artifacts.py validate-manifest \ + .github/candidates/brep-linux-py312.json --brep +``` + +Set `brep_json: true` when calling or dispatching the native candidate +workflow with this manifest. The Linux job runs four required checks outside the checkouts with the installed candidate wheels. - Standalone Core BRep JSON uses the shared schema and preserves the native solid, units, name, and GUID. diff --git a/.github/candidates/brep-linux-py312.json b/.github/candidates/brep-linux-py312.json new file mode 100644 index 0000000..bfd23e3 --- /dev/null +++ b/.github/candidates/brep-linux-py312.json @@ -0,0 +1,61 @@ +{ + "schema_version": 1, + "target": { + "runner": "ubuntu-24.04", + "os": "linux", + "architecture": "x86_64", + "python": "3.12" + }, + "packages": [ + { + "distribution": "compas", + "version": "3.0.0", + "repository": "compas-dev/compas", + "commit": "47a9a2eddd4848f8ea20576817d75de63aa717bd", + "workflow": { + "run_id": 46514942813, + "run_attempt": 1, + "path": ".github/workflows/build.yml", + "event": "pull_request", + "pull_request": 1543, + "base_ref": "remove-future" + }, + "artifact": { + "id": 15425936355, + "name": "candidate-linux-py312", + "archive_sha256": "a2e3e1c70cd948308a3da1c204e109eb9c341f0bbb18a7dc1e763346de81a237" + }, + "wheel": { + "filename": "compas-3.0.0-py3-none-any.whl", + "sha256": "d55192abd7ba36102f48a744eaa97afed6830aea3672ff266d2a9927cf51c659" + }, + "depends_on": [] + }, + { + "distribution": "compas-occ", + "version": "1.5.0", + "repository": "compas-dev/compas_occ", + "commit": "be78eac33ad8fa91b067bb079f8b1d38858043dd", + "workflow": { + "run_id": 46514996117, + "run_attempt": 1, + "path": ".github/workflows/build.yml", + "event": "pull_request", + "pull_request": 33, + "base_ref": "c3-upgrade" + }, + "artifact": { + "id": 15424042262, + "name": "candidate-linux-py312", + "archive_sha256": "aa7a43674b3203df3277271a5f069f9b2cd338adc49e1d7aecae5b1ec47a4add" + }, + "wheel": { + "filename": "compas_occ-1.5.0-py3-none-any.whl", + "sha256": "eec2f0359b563817640677f81f6f4e9d0511f3ec96ea4f18159d36d6c6016d90" + }, + "depends_on": [ + "compas" + ] + } + ] +} diff --git a/.github/scripts/candidate_artifacts.py b/.github/scripts/candidate_artifacts.py index 4a328aa..2c60058 100644 --- a/.github/scripts/candidate_artifacts.py +++ b/.github/scripts/candidate_artifacts.py @@ -40,6 +40,7 @@ PLACEHOLDER = re.compile(r"(?:change[-_ ]?me|placeholder|todo|example|0{12,})", re.IGNORECASE) SUPPORTED_TARGET = ("ubuntu-24.04", "linux", "x86_64", "3.12") LIVE_DISTRIBUTIONS = frozenset({"compas", "compas-occ", "compas-cgal", "compas-libigl"}) +BREP_DISTRIBUTIONS = frozenset({"compas", "compas-occ"}) LIVE_REPOSITORIES = { "compas": "compas-dev/compas", "compas-occ": "compas-dev/compas_occ", @@ -155,8 +156,24 @@ def _digest(value: str, context: str) -> str: return digest -def parse_manifest(data: object, *, require_live_set: bool = False) -> Manifest: - """Parse and validate a candidate manifest.""" +def parse_manifest(data: object, *, require_live_set: bool = False, brep: bool = False) -> Manifest: + """Parse and validate a candidate manifest. + + Parameters + ---------- + data + The decoded manifest. + require_live_set + Require the complete native candidate set and approved producers. + brep + Require the BRep candidate set and approved producers. + + Returns + ------- + Manifest + The validated candidate metadata. + + """ root = _mapping(data, "manifest") _exact_keys(root, {"schema_version", "target", "packages"}, "manifest") @@ -296,11 +313,13 @@ def parse_manifest(data: object, *, require_live_set: bool = False) -> Manifest: manifest = Manifest(schema_version=1, target=target, packages=tuple(candidates)) _topological_candidates(manifest) - if require_live_set and set(manifest.by_name) != LIVE_DISTRIBUTIONS: - raise CandidateError(f"live manifest must contain exactly {sorted(LIVE_DISTRIBUTIONS)!r}") - if require_live_set: - for distribution, repository in LIVE_REPOSITORIES.items(): - candidate = manifest.by_name[distribution] + if require_live_set or brep: + expected = BREP_DISTRIBUTIONS if brep else LIVE_DISTRIBUTIONS + if manifest.by_name.keys() != expected: + raise CandidateError(f"live manifest must contain exactly {sorted(expected)!r}") + for candidate in manifest.packages: + distribution = candidate.distribution + repository = LIVE_REPOSITORIES[distribution] if candidate.repository != repository: raise CandidateError(f"live manifest repository for {distribution!r} must be {repository!r}") if candidate.artifact.name != LIVE_ARTIFACT_NAMES[distribution]: @@ -310,12 +329,13 @@ def parse_manifest(data: object, *, require_live_set: bool = False) -> Manifest: return manifest -def load_manifest(path: Path, *, require_live_set: bool = False) -> Manifest: +def load_manifest(path: Path, *, require_live_set: bool = False, brep: bool = False) -> Manifest: + """Read a manifest and validate its selected candidate set.""" try: data = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as error: raise CandidateError(f"cannot read candidate manifest {path}: {error}") from error - return parse_manifest(data, require_live_set=require_live_set) + return parse_manifest(data, require_live_set=require_live_set, brep=brep) def _topological_candidates(manifest: Manifest) -> tuple[Candidate, ...]: @@ -604,10 +624,10 @@ def verify_artifact_provenance(candidate: Candidate, artifact: dict[str, Any], r return download_url -def retrieve_candidates(manifest_path: Path, output: Path, client: GitHubClient) -> None: +def retrieve_candidates(manifest_path: Path, output: Path, client: GitHubClient, *, brep: bool = False) -> None: """Retrieve and verify all candidate artifacts into an offline bundle.""" - manifest = load_manifest(manifest_path, require_live_set=True) + manifest = load_manifest(manifest_path, require_live_set=True, brep=brep) if output.exists(): if not output.is_dir() or any(output.iterdir()): raise CandidateError(f"output directory must be empty: {output}") @@ -635,13 +655,13 @@ def retrieve_candidates(manifest_path: Path, output: Path, client: GitHubClient) "wheels": {candidate.wheel.filename: candidate.wheel.sha256 for candidate in sorted(manifest.packages, key=lambda item: item.distribution)}, } (output / "bundle.json").write_text(json.dumps(bundle, indent=2, sort_keys=True) + "\n", encoding="utf-8") - verify_offline_bundle(output, manifest) + verify_offline_bundle(output, manifest, brep=brep) -def verify_offline_bundle(bundle: Path, manifest: Manifest | None = None) -> Manifest: +def verify_offline_bundle(bundle: Path, manifest: Manifest | None = None, *, brep: bool = False) -> Manifest: """Revalidate a credential-free candidate bundle before installation.""" - bundled_manifest = load_manifest(bundle / "manifest.json", require_live_set=True) + bundled_manifest = load_manifest(bundle / "manifest.json", require_live_set=True, brep=brep) if manifest is not None and bundled_manifest != manifest: raise CandidateError("bundled manifest differs from the selected manifest") actual_root = {path.name for path in bundle.iterdir()} @@ -685,10 +705,10 @@ def _framework_wheel(framework_bundle: Path) -> Path: return wheels[0] -def install_candidates(bundle: Path, framework_bundle: Path, python: Path) -> None: +def install_candidates(bundle: Path, framework_bundle: Path, python: Path, *, brep: bool = False) -> None: """Install the verified candidates and framework wheel without resolution.""" - manifest = verify_offline_bundle(bundle) + manifest = verify_offline_bundle(bundle, brep=brep) framework_wheel = _framework_wheel(framework_bundle) environment = os.environ.copy() environment["PIP_NO_INDEX"] = "1" @@ -822,6 +842,9 @@ def _parser() -> argparse.ArgumentParser: install.add_argument("framework_bundle", type=Path) install.add_argument("--python", required=True, type=Path) + for command in (validate, retrieve, verify_bundle, install): + command.add_argument("--brep", action="store_true", help="Require exactly the Core and OCC candidates from approved producers.") + junit = subparsers.add_parser("verify-junit") junit.add_argument("report", type=Path) junit.add_argument("--required", action="append", default=[]) @@ -837,14 +860,14 @@ def main() -> None: args = _parser().parse_args() try: if args.command == "validate-manifest": - load_manifest(args.manifest, require_live_set=args.live) + load_manifest(args.manifest, require_live_set=args.live, brep=args.brep) elif args.command == "retrieve": token = os.environ.get("CANDIDATE_ARTIFACT_TOKEN", "") - retrieve_candidates(args.manifest, args.output, GitHubClient(token)) + retrieve_candidates(args.manifest, args.output, GitHubClient(token), brep=args.brep) elif args.command == "verify-bundle": - verify_offline_bundle(args.bundle) + verify_offline_bundle(args.bundle, brep=args.brep) elif args.command == "install": - install_candidates(args.bundle, args.framework_bundle, args.python) + install_candidates(args.bundle, args.framework_bundle, args.python, brep=args.brep) elif args.command == "verify-junit": verify_junit(args.report, args.required) elif args.command == "verify-public": diff --git a/.github/scripts/run_rhino_brep_candidate.py b/.github/scripts/run_rhino_brep_candidate.py index eb79781..3ab30fc 100644 --- a/.github/scripts/run_rhino_brep_candidate.py +++ b/.github/scripts/run_rhino_brep_candidate.py @@ -35,7 +35,7 @@ def _candidate_wheels(bundle: Path) -> tuple[Path, Path]: - manifest = verify_offline_bundle(bundle) + manifest = verify_offline_bundle(bundle, brep=True) wheels = {item.distribution: bundle / "wheels" / item.wheel.filename for item in manifest.packages} return wheels["compas"], wheels["compas-occ"] diff --git a/.github/tests/test_candidate_artifacts.py b/.github/tests/test_candidate_artifacts.py index 2971535..4558a2a 100644 --- a/.github/tests/test_candidate_artifacts.py +++ b/.github/tests/test_candidate_artifacts.py @@ -75,10 +75,15 @@ def manifest_data(*packages: dict[str, object]) -> dict[str, object]: } -def live_manifest_data() -> dict[str, object]: - return manifest_data( +def live_manifest_data(*, brep: bool = False) -> dict[str, object]: + core_and_occ = ( package("compas", "compas-dev/compas", artifact_id=1), package("compas_occ", "compas-dev/compas_occ", artifact_id=2, depends_on=["compas"]), + ) + if brep: + return manifest_data(*core_and_occ) + return manifest_data( + *core_and_occ, package("compas_cgal", "compas-dev/compas_cgal", artifact_id=3, depends_on=["compas"], platform="manylinux_2_28_x86_64"), package("compas_libigl", "compas-dev/compas_libigl", artifact_id=4, depends_on=["compas"], platform="manylinux_2_28_x86_64"), ) @@ -141,8 +146,8 @@ def write_manifest(path: Path, data: dict[str, object]) -> candidate_artifacts.M return candidate_artifacts.load_manifest(path) -def write_bundle(tmp_path: Path) -> tuple[Path, candidate_artifacts.Manifest]: - data = live_manifest_data() +def write_bundle(tmp_path: Path, *, brep: bool = False) -> tuple[Path, candidate_artifacts.Manifest]: + data = live_manifest_data(brep=brep) bundle = tmp_path / "bundle" wheels = bundle / "wheels" wheels.mkdir(parents=True) @@ -205,17 +210,56 @@ def test_manifest_rejects_missing_candidate_from_live_set(): candidate_artifacts.parse_manifest(data, require_live_set=True) -def test_live_manifest_rejects_unapproved_repository_or_artifact_name(): - data = live_manifest_data() +def test_brep_manifest_accepts_exact_core_and_occ_set(): + manifest = candidate_artifacts.parse_manifest(live_manifest_data(brep=True), brep=True) + + assert [item.distribution for item in candidate_artifacts._topological_candidates(manifest)] == ["compas", "compas-occ"] + + +def test_candidate_profiles_reject_missing_and_extra_distributions(): + brep_data = live_manifest_data(brep=True) + packages = brep_data["packages"] + assert isinstance(packages, list) + + with pytest.raises(CandidateError, match="exactly"): + candidate_artifacts.parse_manifest(brep_data, require_live_set=True) + with pytest.raises(CandidateError, match="exactly"): + candidate_artifacts.parse_manifest(live_manifest_data(), brep=True) + + packages.pop() + with pytest.raises(CandidateError, match="exactly"): + candidate_artifacts.parse_manifest(brep_data, brep=True) + + +def test_brep_manifest_cli_applies_live_producer_checks(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]): + data = live_manifest_data(brep=True) + path = tmp_path / "manifest.json" + write_manifest(path, data) + monkeypatch.setattr(sys, "argv", [str(SCRIPT), "validate-manifest", str(path), "--brep"]) + + candidate_artifacts.main() + + packages = data["packages"] + assert isinstance(packages, list) + packages[0]["repository"] = "other/compas" + write_manifest(path, data) + with pytest.raises(SystemExit, match="1"): + candidate_artifacts.main() + assert "repository" in capsys.readouterr().err + + +@pytest.mark.parametrize("brep", [False, True], ids=["native", "brep"]) +def test_live_manifest_rejects_unapproved_repository_or_artifact_name(brep: bool): + data = live_manifest_data(brep=brep) packages = data["packages"] assert isinstance(packages, list) first = packages[0] assert isinstance(first, dict) first["repository"] = "other/compas" with pytest.raises(CandidateError, match="repository"): - candidate_artifacts.parse_manifest(data, require_live_set=True) + candidate_artifacts.parse_manifest(data, require_live_set=True, brep=brep) - data = live_manifest_data() + data = live_manifest_data(brep=brep) packages = data["packages"] assert isinstance(packages, list) first = packages[0] @@ -224,7 +268,7 @@ def test_live_manifest_rejects_unapproved_repository_or_artifact_name(): assert isinstance(artifact, dict) artifact["name"] = "other" with pytest.raises(CandidateError, match="artifact name"): - candidate_artifacts.parse_manifest(data, require_live_set=True) + candidate_artifacts.parse_manifest(data, require_live_set=True, brep=brep) def test_wheel_verification_accepts_compressed_platform_tags_and_dependencies(tmp_path: Path): @@ -491,8 +535,9 @@ def test_artifact_provenance_accepts_output_retained_by_a_successful_rerun(): assert url.startswith("https://api.github.com/") -def test_retrieval_verifies_provenance_and_downloaded_archive_digest(tmp_path: Path): - data = live_manifest_data() +@pytest.mark.parametrize("brep", [False, True], ids=["native", "brep"]) +def test_retrieval_verifies_provenance_and_downloaded_archive_digest(tmp_path: Path, brep: bool): + data = live_manifest_data(brep=brep) source = tmp_path / "source" source.mkdir() archives: dict[str, Path] = {} @@ -526,15 +571,16 @@ def download(self, url: str, destination: Path) -> None: client = Client() output = tmp_path / "verified" - candidate_artifacts.retrieve_candidates(manifest_path, output, client) + candidate_artifacts.retrieve_candidates(manifest_path, output, client, brep=brep) - assert candidate_artifacts.verify_offline_bundle(output).by_name.keys() == candidate_artifacts.LIVE_DISTRIBUTIONS + expected = {"compas", "compas-occ"} if brep else {"compas", "compas-occ", "compas-cgal", "compas-libigl"} + assert candidate_artifacts.verify_offline_bundle(output, brep=brep).by_name.keys() == expected corrupt = tmp_path / "corrupt.zip" corrupt.write_bytes(b"changed archive") archives[next(iter(archives))] = corrupt with pytest.raises(CandidateError, match="downloaded archive digest mismatch"): - candidate_artifacts.retrieve_candidates(manifest_path, tmp_path / "rejected", client) + candidate_artifacts.retrieve_candidates(manifest_path, tmp_path / "rejected", client, brep=brep) def test_safe_extraction_rejects_traversal_symlinks_and_extra_files(tmp_path: Path): @@ -560,25 +606,28 @@ def _write_symlink(archive: zipfile.ZipFile, name: str) -> None: archive.writestr(info, "target") -def test_offline_bundle_revalidates_exact_inventory_and_hashes(tmp_path: Path): - bundle, manifest = write_bundle(tmp_path / "hash") +@pytest.mark.parametrize("brep", [False, True], ids=["native", "brep"]) +def test_offline_bundle_revalidates_exact_inventory_and_hashes(tmp_path: Path, brep: bool): + bundle, manifest = write_bundle(tmp_path / "hash", brep=brep) - assert candidate_artifacts.verify_offline_bundle(bundle) == manifest + assert candidate_artifacts.verify_offline_bundle(bundle, brep=brep) == manifest + with pytest.raises(CandidateError, match="exactly"): + candidate_artifacts.verify_offline_bundle(bundle, brep=not brep) selected = bundle / "wheels" / manifest.packages[0].wheel.filename selected.write_bytes(selected.read_bytes() + b"tampered") with pytest.raises(CandidateError, match="digest mismatch"): - candidate_artifacts.verify_offline_bundle(bundle) + candidate_artifacts.verify_offline_bundle(bundle, brep=brep) - missing_bundle, missing_manifest = write_bundle(tmp_path / "missing") + missing_bundle, missing_manifest = write_bundle(tmp_path / "missing", brep=brep) (missing_bundle / "wheels" / missing_manifest.packages[0].wheel.filename).unlink() with pytest.raises(CandidateError, match="missing or unexpected"): - candidate_artifacts.verify_offline_bundle(missing_bundle) + candidate_artifacts.verify_offline_bundle(missing_bundle, brep=brep) - extra_bundle, _ = write_bundle(tmp_path / "extra") + extra_bundle, _ = write_bundle(tmp_path / "extra", brep=brep) (extra_bundle / "wheels" / "unexpected.whl").write_bytes(b"unexpected") with pytest.raises(CandidateError, match="missing or unexpected"): - candidate_artifacts.verify_offline_bundle(extra_bundle) + candidate_artifacts.verify_offline_bundle(extra_bundle, brep=brep) def junit(tmp_path: Path, body: str) -> Path: @@ -687,8 +736,9 @@ def changed(candidate, base_url): candidate_artifacts.verify_public_artifacts(manifest, before=dependent) -def test_install_uses_topological_no_index_no_deps_commands(tmp_path: Path, monkeypatch): - bundle, manifest = write_bundle(tmp_path) +@pytest.mark.parametrize("brep", [False, True], ids=["native", "brep"]) +def test_install_uses_topological_no_index_no_deps_commands(tmp_path: Path, monkeypatch, brep: bool): + bundle, manifest = write_bundle(tmp_path, brep=brep) framework = tmp_path / "framework-bundle" / "framework" framework.mkdir(parents=True) framework_wheel = framework / "compas_framework-0.1.3-py3-none-any.whl" @@ -703,7 +753,7 @@ def run(command, *, check, env): monkeypatch.setattr(candidate_artifacts.subprocess, "run", run) - candidate_artifacts.install_candidates(bundle, framework.parent, Path("/candidate/python")) + candidate_artifacts.install_candidates(bundle, framework.parent, Path("/candidate/python"), brep=brep) assert len(calls) == len(manifest.packages) + 2 install_calls = calls[:-1] diff --git a/.github/workflows/native-candidate-integration.yml b/.github/workflows/native-candidate-integration.yml index 97cd480..ff1ca35 100644 --- a/.github/workflows/native-candidate-integration.yml +++ b/.github/workflows/native-candidate-integration.yml @@ -7,24 +7,22 @@ on: workflow_call: inputs: manifest_path: - description: Reviewed candidate manifest in this repository + description: Reviewed candidate manifest path. Defaults to the manifest for the selected package set. required: false - default: .github/candidates/native-linux-py312.json type: string brep_json: - description: Require BRep JSON contracts with interchange-capable Core and OCC candidates + description: Qualify the Core and OCC wheels with the BRep JSON contracts required: false default: false type: boolean workflow_dispatch: inputs: manifest_path: - description: Reviewed candidate manifest in this repository + description: Reviewed candidate manifest path. Defaults to the manifest for the selected package set. required: false - default: .github/candidates/native-linux-py312.json type: string brep_json: - description: Require BRep JSON contracts with interchange-capable Core and OCC candidates + description: Qualify the Core and OCC wheels with the BRep JSON contracts required: false default: false type: boolean @@ -42,7 +40,7 @@ jobs: runs-on: ubuntu-24.04 environment: candidate-artifact-retrieval env: - CANDIDATE_MANIFEST: ${{ inputs.manifest_path || '.github/candidates/native-linux-py312.json' }} + CANDIDATE_MANIFEST: ${{ inputs.manifest_path || (inputs.brep_json && '.github/candidates/brep-linux-py312.json' || '.github/candidates/native-linux-py312.json') }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -69,11 +67,7 @@ jobs: app-id: ${{ secrets.CANDIDATE_ARTIFACT_APP_ID }} private-key: ${{ secrets.CANDIDATE_ARTIFACT_PRIVATE_KEY }} owner: compas-dev - repositories: | - compas - compas_occ - compas_cgal - compas_libigl + repositories: ${{ inputs.brep_json && 'compas,compas_occ' || 'compas,compas_occ,compas_cgal,compas_libigl' }} - name: Retrieve and verify admitted candidate artifacts env: CANDIDATE_ARTIFACT_TOKEN: ${{ steps.app-token.outputs.token }} @@ -81,6 +75,7 @@ jobs: uv run --no-sync python .github/scripts/candidate_artifacts.py retrieve "${CANDIDATE_MANIFEST}" "${RUNNER_TEMP}/verified-native-candidates" + ${{ inputs.brep_json && '--brep' || '' }} - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: verified-native-candidates @@ -160,7 +155,9 @@ jobs: "${RUNNER_TEMP}/verified-native-candidates" "${RUNNER_TEMP}/framework-integration" --python "$(command -v python)" + ${{ inputs.brep_json && '--brep' || '' }} - name: Run installed runtime and typing contracts outside all checkouts + if: ${{ !inputs.brep_json }} shell: bash -el {0} env: PIP_NO_INDEX: "1" @@ -184,6 +181,7 @@ jobs: PIP_NO_INDEX: "1" PYTHONPATH: "" run: | + mkdir -p "${RUNNER_TEMP}/candidate-execution" cd "${RUNNER_TEMP}/candidate-execution" cp "${RUNNER_TEMP}/framework-integration/harness/candidate_brep_json.py" . python -m pytest candidate_brep_json.py --junitxml candidate-brep-json-junit.xml diff --git a/docs/testing.md b/docs/testing.md index cc560fc..7b7d0a7 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -98,10 +98,12 @@ per-backend baselines. ## BRep JSON qualification -The native candidate workflow can require four installed-wheel BRep -checks with `brep_json: true`. These cover standalone and nested COMPAS -JSON, a missing unit declaration, and an analytic sphere. Select a reviewed -manifest containing Core and OCC wheels with the BRep interchange API. +With `brep_json: true`, the native candidate workflow verifies a reviewed +manifest containing exactly the Core and OCC wheels for the BRep +interchange API. It applies the same artifact provenance and hash checks +used for the four-package native qualification. Its installed-wheel +tests cover standalone and nested COMPAS JSON, a missing unit +declaration, and an analytic sphere. The separate `rhino-brep-integration.yml` workflow runs thirteen fixtures through OCC → Rhino 8 → OCC and Rhino 8 → OCC → Rhino 8. It verifies each diff --git a/tests/test_package.py b/tests/test_package.py index 1f38fe1..2f805a0 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -65,7 +65,7 @@ def test_native_candidate_integration_runs_from_the_protected_initiative_branch( workflow = (Path(__file__).parents[1] / ".github" / "workflows" / "native-candidate-integration.yml").read_text() assert "push:\n branches:\n - initiative/candidate-artifact-integration" in workflow - assert "inputs.manifest_path || '.github/candidates/native-linux-py312.json'" in workflow + assert "inputs.manifest_path || (inputs.brep_json && '.github/candidates/brep-linux-py312.json' || '.github/candidates/native-linux-py312.json')" in workflow def test_framework_examples_page_is_link_oriented(): From de90722b5b5d34c2b1a5d729b028b0a958e71c50 Mon Sep 17 00:00:00 2001 From: tomvanmele Date: Tue, 1 Dec 2026 16:02:24 +0100 Subject: [PATCH 6/8] Check BRep attribute identity in both native kernels --- .../brep-interchange-v1.schema.json | 24 ++++ .github/brep-interchange/element_fixture.py | 120 ++++++++++++++++++ .../interchange_validation.py | 71 ++++++++++- .github/brep-interchange/run_in_rhino.py | 1 + .github/brep-interchange/run_interchange.py | 9 ++ .github/brep-interchange/test_interchange.py | 9 +- .github/candidates/README.md | 10 +- docs/testing.md | 7 +- 8 files changed, 241 insertions(+), 10 deletions(-) create mode 100644 .github/brep-interchange/element_fixture.py diff --git a/.github/brep-interchange/brep-interchange-v1.schema.json b/.github/brep-interchange/brep-interchange-v1.schema.json index 142705b..cfb612d 100644 --- a/.github/brep-interchange/brep-interchange-v1.schema.json +++ b/.github/brep-interchange/brep-interchange-v1.schema.json @@ -97,6 +97,29 @@ "uv": { "$ref": "#/$defs/positiveNumber" } } }, + "elementRecord": { + "type": "object", + "additionalProperties": false, + "required": ["index", "id"], + "properties": { + "index": { "$ref": "#/$defs/index" }, + "id": { "type": "string", "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" }, + "attributes_json": { "type": "string", "contentMediaType": "application/json" } + } + }, + "elementRecords": { + "type": "array", + "items": { "$ref": "#/$defs/elementRecord" } + }, + "elementData": { + "type": "object", + "additionalProperties": false, + "properties": { + "vertices": { "$ref": "#/$defs/elementRecords" }, + "edges": { "$ref": "#/$defs/elementRecords" }, + "faces": { "$ref": "#/$defs/elementRecords" } + } + }, "component": { "type": "object", "additionalProperties": false, @@ -117,6 +140,7 @@ "minItems": 1, "items": { "$ref": "#/$defs/face" } }, + "element_data": { "$ref": "#/$defs/elementData" }, "shells": { "type": "array", "minItems": 1, diff --git a/.github/brep-interchange/element_fixture.py b/.github/brep-interchange/element_fixture.py new file mode 100644 index 0000000..18571d3 --- /dev/null +++ b/.github/brep-interchange/element_fixture.py @@ -0,0 +1,120 @@ +"""Locate BRep element metadata fixtures by their geometry.""" + +from __future__ import annotations + +import json +from collections import Counter +from collections.abc import Iterable +from math import dist +from typing import TYPE_CHECKING +from typing import Literal +from uuid import NAMESPACE_URL +from uuid import uuid5 + +from nurbs_seam import fixture_data as seam_fixture_data + +if TYPE_CHECKING: + from compas.geometry.brep.interchange import BrepInterchangeData + from compas.geometry.brep.interchange import _ComponentData + from compas.geometry.brep.interchange import _ElementData + from compas.geometry.brep.interchange import _ElementTables + +_ElementKind = Literal["vertices", "edges", "faces"] + +ELEMENT_FIXTURES: dict[str, dict[str, tuple[_ElementKind, dict[str, object]]]] = { + "box": { + "origin": ("vertices", {}), + "x_endpoint": ("vertices", {"label": "edge endpoint", "flags": {"fixed": True, "value": 0}}), + "bottom_x_edge": ( + "edges", + {"marks": ["start", {"nested": [True, None, 1.25, "μ"]}]}, + ), + "x_min_face": ( + "faces", + {"label": "inlet", "marker": {"dtype": "compas.geometry/Point", "data": [1, 2, 3]}}, + ), + "x_max_face": ("faces", {"label": "outlet", "selected": False}), + }, + "nurbs_seam": { + "periodic_seam": ("edges", {"label": "shared seam", "uv_uses": [0, 1]}), + }, +} + + +def _one_index(indices: Iterable[int], label: str) -> int: + matches = list(indices) + if len(matches) != 1: + raise ValueError(f"Fixture geometry does not uniquely identify {label}.") + return matches[0] + + +def _vertex_index(component: _ComponentData, point: Iterable[float]) -> int: + xyz = tuple(point) + return _one_index((index for index, vertex in enumerate(component["vertices"]) if dist(vertex, xyz) < 1e-7), f"vertex {xyz}") + + +def _box_indices(component: _ComponentData) -> dict[str, int]: + origin = _vertex_index(component, (0, 0, 0)) + end = _vertex_index(component, (1, 0, 0)) + edges = component["edges"] + edge = _one_index((index for index, item in enumerate(edges) if set(item["vertices"]) == {origin, end}), "bottom X edge") + + planes: dict[float, list[int]] = {0: [], 1: []} + for index, face in enumerate(component["faces"]): + vertices = {vertex for loop in face["loops"] for trim in loop["trims"] if trim["edge"] is not None for vertex in edges[trim["edge"]]["vertices"]} + for x in planes: + if vertices and all(abs(component["vertices"][vertex][0] - x) < 1e-7 for vertex in vertices): + planes[x].append(index) + return { + "origin": origin, + "x_endpoint": end, + "bottom_x_edge": edge, + "x_min_face": _one_index(planes[0], "face at X=0"), + "x_max_face": _one_index(planes[1], "face at X=1"), + } + + +def _target_indices(name: str, component: _ComponentData) -> dict[str, int]: + if name == "box": + return _box_indices(component) + + reference_vertices = seam_fixture_data()["vertices"] + ends = {_vertex_index(component, point) for point in reference_vertices} + (face,) = component["faces"] + uses = Counter(trim["edge"] for loop in face["loops"] for trim in loop["trims"] if trim["edge"] is not None) + seam = _one_index((index for index, edge in enumerate(component["edges"]) if set(edge["vertices"]) == ends and uses[index] == 2), "periodic seam edge") + return {"periodic_seam": seam} + + +def _identifier(origin: str, name: str, label: str) -> str: + return str(uuid5(NAMESPACE_URL, f"https://compas.dev/brep-fixtures/{origin}/{name}/{label}")) + + +def seed_element_data(name: str, data: BrepInterchangeData, origin: str) -> None: + """Attach fixture UUIDs and JSON attributes to a native export before reconstruction.""" + (component,) = data["components"] + indices = _target_indices(name, component) + tables: _ElementTables = {} + for label, (kind, attributes) in ELEMENT_FIXTURES[name].items(): + entry: _ElementData = {"index": indices[label], "id": _identifier(origin, name, label)} + if attributes: + entry["attributes_json"] = json.dumps(attributes, ensure_ascii=False, allow_nan=False) + tables.setdefault(kind, []).append(entry) + component["element_data"] = tables + + +def check_element_data(name: str, data: BrepInterchangeData, origin: str) -> dict[str, dict[str, object]]: + """Verify full attributes and UUIDs at the expected geometric targets.""" + (component,) = data["components"] + indices = _target_indices(name, component) + tables = component.get("element_data", {}) + actual = {(kind, entry["index"]): (entry["id"], json.loads(entry.get("attributes_json", "{}"))) for kind, table in tables.items() for entry in table} + report = {} + for label, (kind, attributes) in ELEMENT_FIXTURES[name].items(): + identifier = _identifier(origin, name, label) + if actual.pop((kind, indices[label]), None) != (identifier, attributes): + raise ValueError(f"{name} lost or moved the metadata for {label}.") + report[label] = {"id": identifier, "attributes": attributes} + if actual: + raise ValueError(f"{name} contains unexpected element metadata.") + return report diff --git a/.github/brep-interchange/interchange_validation.py b/.github/brep-interchange/interchange_validation.py index 82c3726..fac9e24 100644 --- a/.github/brep-interchange/interchange_validation.py +++ b/.github/brep-interchange/interchange_validation.py @@ -2,10 +2,12 @@ from __future__ import annotations +import json from collections import defaultdict from math import isclose from math import tau from sys import float_info +from uuid import UUID SCHEMA = "compas.brep.interchange" VERSION = 1 @@ -16,11 +18,12 @@ def _require(condition: object, path: str, message: str) -> None: raise ValueError(f"{path}: {message}") -def _record(value: object, path: str, fields: str | None = None) -> dict[str, object]: +def _record(value: object, path: str, fields: str | None = None, *, optional: str = "") -> dict[str, object]: if not isinstance(value, dict): raise ValueError(f"{path}: expected a JSON object") if fields is not None: - _require(value.keys() == set(fields.split()), path, f"expected fields {fields}") + required = set(fields.split()) + _require(required <= value.keys() <= required | set(optional.split()), path, f"expected fields {fields}") return value @@ -357,9 +360,64 @@ def _shells(shells: object, face_count: int, uses: dict[int, list[tuple[int, boo _require(visited == faces, f"{path}[{index}]", "shell faces must be connected") -def _component(data: object, kind: object, path: str) -> None: +def _attribute_value(value: object, path: str) -> None: + if isinstance(value, dict): + for key, item in value.items(): + _require(isinstance(key, str), path, "attribute keys must be strings") + _attribute_value(item, f"{path}.{key}") + elif isinstance(value, list): + for index, item in enumerate(value): + _attribute_value(item, f"{path}[{index}]") + elif value is not None and not isinstance(value, (bool, str)): + _number(value, path) + + +def _encode_element_attributes(attributes: object) -> str: + record = _record(attributes, "BRep element attributes") + try: + _attribute_value(record, "BRep element attributes") + return json.dumps(record, allow_nan=False, separators=(",", ":")) + except RecursionError as error: + raise ValueError("BRep element attributes must be finite, nested JSON values.") from error + + +def _element_metadata(data: object, counts: dict[str, int], identifiers: set[str], path: str) -> None: + domains = _record(data, path) + _require(domains.keys() <= counts.keys(), path, "expected vertex, edge, or face metadata") + for domain, records in domains.items(): + domain_path = f"{path}.{domain}" + indices: set[int] = set() + for position, item in enumerate(_array(records, domain_path)): + record_path = f"{domain_path}[{position}]" + record = _record(item, record_path, "index id", optional="attributes_json") + index = _reference(record["index"], counts[domain], f"{record_path}.index") + _require(index not in indices, record_path, "duplicate element index") + indices.add(index) + identifier = record["id"] + if not isinstance(identifier, str): + raise ValueError(f"{record_path}.id: expected a canonical UUID") + try: + canonical = str(UUID(identifier)) + except ValueError as error: + raise ValueError(f"{record_path}.id: expected a canonical UUID") from error + _require(identifier == canonical, f"{record_path}.id", "expected a canonical UUID") + _require(identifier not in identifiers, f"{record_path}.id", "duplicate element UUID") + identifiers.add(identifier) + if "attributes_json" in record: + attrs_path = f"{record_path}.attributes_json" + raw = record["attributes_json"] + if not isinstance(raw, str): + raise ValueError(f"{attrs_path}: expected JSON text") + try: + attributes = _record(json.loads(raw), attrs_path) + _attribute_value(attributes, attrs_path) + except (json.JSONDecodeError, RecursionError) as error: + raise ValueError(f"{attrs_path}: expected JSON object text") from error + + +def _component(data: object, kind: object, identifiers: set[str], path: str) -> None: fields = "kind vertices edges faces shells" if kind == "solid" else "kind vertices edges faces" - component = _record(data, path, fields) + component = _record(data, path, fields, optional="element_data") _require(component["kind"] == kind, path, f"expected a {kind} component") vertices = _array(component["vertices"], f"{path}.vertices") _require(vertices, path, "a component requires at least one vertex") @@ -367,6 +425,8 @@ def _component(data: object, kind: object, path: str) -> None: _coordinates(vertex, 3, f"{path}.vertices[{index}]") edges = [_edge(edge, len(vertices), f"{path}.edges[{index}]") for index, edge in enumerate(_array(component["edges"], f"{path}.edges"))] faces = _array(component["faces"], f"{path}.faces") + if "element_data" in component: + _element_metadata(component["element_data"], {"vertices": len(vertices), "edges": len(edges), "faces": len(faces)}, identifiers, f"{path}.element_data") if kind == "face": _require(len(faces) == 1, path, "a face component contains exactly one face") uses: dict[int, list[tuple[int, bool]]] = defaultdict(list) @@ -416,5 +476,6 @@ def validate(value: object) -> None: kind = "solid" else: _require(len(components) == 1, "$.components", "expected exactly one component") + identifiers: set[str] = set() for index, component in enumerate(components): - _component(component, kind, f"$.components[{index}]") + _component(component, kind, identifiers, f"$.components[{index}]") diff --git a/.github/brep-interchange/run_in_rhino.py b/.github/brep-interchange/run_in_rhino.py index 3ff0b78..1b96c80 100644 --- a/.github/brep-interchange/run_in_rhino.py +++ b/.github/brep-interchange/run_in_rhino.py @@ -32,6 +32,7 @@ def _staged_modules(directory): "run_probe", "run_interchange", "analytic_fixture", + "element_fixture", "interchange", "interchange_validation", "rhino_adapter", diff --git a/.github/brep-interchange/run_interchange.py b/.github/brep-interchange/run_interchange.py index 5c78c75..577e04c 100644 --- a/.github/brep-interchange/run_interchange.py +++ b/.github/brep-interchange/run_interchange.py @@ -15,6 +15,9 @@ from analytic_fixture import ANALYTIC_FIXTURES from analytic_fixture import measure as measure_analytic from analytic_fixture import signature as analytic_signature +from element_fixture import ELEMENT_FIXTURES +from element_fixture import check_element_data +from element_fixture import seed_element_data from interchange import from_prototype_data from interchange import to_prototype_data from interchange_validation import validate @@ -178,6 +181,10 @@ def run(backend: Backend, phase: Phase, directory: Path, source: Backend | None else: native = adapter.make_fixture(name) data = write_brep(native, units="mm") + if name in ELEMENT_FIXTURES: + seed_element_data(name, data, origin) + native = read_brep(data) + data = write_brep(native, units=data["units"]) _fixture_signature(name, data) else: input_path = directory / f"{input_prefix}-{name}.json" @@ -194,6 +201,8 @@ def run(backend: Backend, phase: Phase, directory: Path, source: Backend | None raise ValueError(f"{backend} re-export changed topology for {name}.") properties = _measure_fixture(backend, adapter, name, native, data) + if name in ELEMENT_FIXTURES: + properties["element_metadata"] = check_element_data(name, data, origin) if input_prefix is not None: properties["input_file"] = input_path.name properties["input_sha256"] = sha256(contents).hexdigest() diff --git a/.github/brep-interchange/test_interchange.py b/.github/brep-interchange/test_interchange.py index db49b21..827f736 100644 --- a/.github/brep-interchange/test_interchange.py +++ b/.github/brep-interchange/test_interchange.py @@ -7,6 +7,8 @@ from pathlib import Path from zipfile import ZipFile +from element_fixture import ELEMENT_FIXTURES +from element_fixture import check_element_data from interchange_validation import SCHEMA from interchange_validation import VERSION from interchange_validation import validate @@ -53,12 +55,14 @@ def _verify_host(path: Path, bundle_evidence: dict) -> dict: return host -def _validate_payload(path: Path, validator: Draft202012Validator) -> str: +def _validate_payload(path: Path, validator: Draft202012Validator, fixture: str, origin: str, metrics: dict) -> str: contents = path.read_bytes() data = json.loads(contents) try: validator.validate(data) validate(data) + if fixture in ELEMENT_FIXTURES and check_element_data(fixture, data, origin) != metrics.get("element_metadata"): + raise ValueError("The report differs from the geometry-matched element metadata.") except (ValidationError, ValueError) as error: raise ValueError(f"Invalid fixture {path}: {error}") from error return sha256(contents).hexdigest() @@ -86,6 +90,7 @@ def verify_exchange(directory: Path, *, bundle: Path) -> None: ) digests: dict[str, str] = {} for stage, source, host_results in stages: + origin = stage.split("-", maxsplit=1)[0] suffix = "-source" if source is None else "" report = _read_json(directory / f"{stage}{suffix}-report.json") if host_results is not None and host_results != report: @@ -101,7 +106,7 @@ def verify_exchange(directory: Path, *, bundle: Path) -> None: if (metrics.get("input_file"), metrics.get("input_sha256")) != (input_name, digests[input_name]): raise ValueError(f"{stage} did not consume the preceding native export for {fixture}.") payload = f"{stage}-{fixture}.json" - digest = _validate_payload(directory / payload, validator) + digest = _validate_payload(directory / payload, validator, fixture, origin, metrics) if metrics.get("output_sha256") != digest: raise ValueError(f"{stage} report does not identify its output file {payload}.") digests[payload] = digest diff --git a/.github/candidates/README.md b/.github/candidates/README.md index c2f53bb..acce2f2 100644 --- a/.github/candidates/README.md +++ b/.github/candidates/README.md @@ -132,6 +132,14 @@ analytic solids it checks native surface types, shared seam edges, singular trims, area, volume, and point containment. It also checks both orders of the native Rhino compound tuple. +The box and periodic NURBS seam fixtures verify element UUIDs and attributes +with metadata-capable Core and OCC wheels and the Rhino codec. Checks locate +the two equal-area box faces by their X coordinates and identify the +vertices, edge, and shared seam by geometry. Each direction has distinct UUIDs. +The checks compare complete attribute dictionaries, including nested JSON +with a literal `dtype` key. Hosted metadata qualification requires a +reviewed manifest and bundle with this schema. + For a local run from the framework checkout, use the OCC environment and provide the exact wheels and Rhino ZIP. @@ -139,7 +147,7 @@ provide the exact wheels and Rhino ZIP. work=$(mktemp -d) python .github/scripts/run_rhino_brep_candidate.py \ --wheels /absolute/path/to/compas.whl /absolute/path/to/compas_occ.whl \ - --bundle /absolute/path/to/compas-rhino8-brep-codec-1.1.0.zip \ + --bundle /absolute/path/to/compas-rhino8-brep-codec-1.2.0.zip \ --bundle-sha256 '' \ --output "$work/results" ``` diff --git a/docs/testing.md b/docs/testing.md index 7b7d0a7..c9f3efd 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -110,6 +110,9 @@ through OCC → Rhino 8 → OCC and Rhino 8 → OCC → Rhino 8. It verifies eac JSON handoff and the exact Rhino codec bundle on a dedicated protected macOS runner. The fixtures include native sphere, cylinder, cone and torus solids with checks for retained analytic geometry, seams and poles. -Hosted qualification requires the reviewed BRep-enabled manifest, the -Rhino codec bundle SHA-256 and the protected Rhino runner. +The box and periodic seam fixtures also verify topology element UUIDs and +attribute dictionaries at geometrically identified faces, vertices, and +edges. Hosted qualification for these checks requires reviewed Core and +OCC wheels and the Rhino bundle with element metadata support, the bundle +SHA-256, and the protected Rhino runner. [Candidate and Rhino runner instructions](https://github.com/compas-dev/compas_framework/blob/c3-upgrade/.github/candidates/README.md) From 2b0fa185ca5bda1292489b37767262f49bcc3368 Mon Sep 17 00:00:00 2001 From: tomvanmele Date: Tue, 1 Dec 2026 17:34:56 +0100 Subject: [PATCH 7/8] Submit exact BRep topology producer wheels --- .github/candidates/brep-linux-py312.json | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/.github/candidates/brep-linux-py312.json b/.github/candidates/brep-linux-py312.json index bfd23e3..2c9e2be 100644 --- a/.github/candidates/brep-linux-py312.json +++ b/.github/candidates/brep-linux-py312.json @@ -11,9 +11,9 @@ "distribution": "compas", "version": "3.0.0", "repository": "compas-dev/compas", - "commit": "47a9a2eddd4848f8ea20576817d75de63aa717bd", + "commit": "097cabc6ac86141ce3b588e7489c594449c2e358", "workflow": { - "run_id": 46514942813, + "run_id": 46674098344, "run_attempt": 1, "path": ".github/workflows/build.yml", "event": "pull_request", @@ -21,13 +21,13 @@ "base_ref": "remove-future" }, "artifact": { - "id": 15425936355, + "id": 15501479098, "name": "candidate-linux-py312", - "archive_sha256": "a2e3e1c70cd948308a3da1c204e109eb9c341f0bbb18a7dc1e763346de81a237" + "archive_sha256": "90c5eb8be65782f6a5488018a51f2b3540b271303cc491c814217c6737f31ed8" }, "wheel": { "filename": "compas-3.0.0-py3-none-any.whl", - "sha256": "d55192abd7ba36102f48a744eaa97afed6830aea3672ff266d2a9927cf51c659" + "sha256": "6840465e19392cca9c009e2f995a018b2d020c385403cc196940d986c9a1b0dc" }, "depends_on": [] }, @@ -35,9 +35,9 @@ "distribution": "compas-occ", "version": "1.5.0", "repository": "compas-dev/compas_occ", - "commit": "be78eac33ad8fa91b067bb079f8b1d38858043dd", + "commit": "9b1b5728885425584ffa1ce9520d680a5693528d", "workflow": { - "run_id": 46514996117, + "run_id": 46674238087, "run_attempt": 1, "path": ".github/workflows/build.yml", "event": "pull_request", @@ -45,13 +45,13 @@ "base_ref": "c3-upgrade" }, "artifact": { - "id": 15424042262, + "id": 15502032374, "name": "candidate-linux-py312", - "archive_sha256": "aa7a43674b3203df3277271a5f069f9b2cd338adc49e1d7aecae5b1ec47a4add" + "archive_sha256": "f34290fdfbb48cc75ab487143f76b02987f41dbd0c6fb5c62f17a6d58b26c156" }, "wheel": { "filename": "compas_occ-1.5.0-py3-none-any.whl", - "sha256": "eec2f0359b563817640677f81f6f4e9d0511f3ec96ea4f18159d36d6c6016d90" + "sha256": "5eb0acd068fc0d9e08d151e450330d750101f640b9bfe17dbb2ac633009d4895" }, "depends_on": [ "compas" From b43cf3890a48dbbf0eb160d6c2c08ad74c527ee5 Mon Sep 17 00:00:00 2001 From: tomvanmele Date: Tue, 1 Dec 2026 18:46:32 +0100 Subject: [PATCH 8/8] Pass protected candidate App credentials to reusable workflow --- .github/tests/test_candidate_artifacts.py | 16 ++++++++++++++++ .../workflows/native-candidate-integration.yml | 5 +++++ .github/workflows/rhino-brep-integration.yml | 3 +++ 3 files changed, 24 insertions(+) diff --git a/.github/tests/test_candidate_artifacts.py b/.github/tests/test_candidate_artifacts.py index 4558a2a..c56bd1e 100644 --- a/.github/tests/test_candidate_artifacts.py +++ b/.github/tests/test_candidate_artifacts.py @@ -849,6 +849,22 @@ def test_trusted_workflow_isolated_from_pull_requests_and_secrets(): assert "actions/checkout" not in execute +def test_rhino_qualification_passes_only_the_required_retrieval_secrets(): + workflows = ROOT / ".github" / "workflows" + native = (workflows / "native-candidate-integration.yml").read_text(encoding="utf-8") + rhino = (workflows / "rhino-brep-integration.yml").read_text(encoding="utf-8") + workflow_call = native.split(" workflow_call:", 1)[1].split(" workflow_dispatch:", 1)[0] + qualify = rhino.split(" qualify-linux-candidates:", 1)[1].split(" assemble-rhino-harness:", 1)[0] + assert "uses: ./.github/workflows/native-candidate-integration.yml" in qualify + assert qualify.split(" secrets:\n", 1)[1].rstrip().splitlines() == [ + " CANDIDATE_ARTIFACT_APP_ID: ${{ secrets.CANDIDATE_ARTIFACT_APP_ID }}", + " CANDIDATE_ARTIFACT_PRIVATE_KEY: ${{ secrets.CANDIDATE_ARTIFACT_PRIVATE_KEY }}", + ] + assert " CANDIDATE_ARTIFACT_APP_ID:\n required: true" in workflow_call + assert " CANDIDATE_ARTIFACT_PRIVATE_KEY:\n required: true" in workflow_call + assert "secrets." not in rhino.split(" assemble-rhino-harness:", 1)[1] + + def test_pull_request_contract_workflow_has_no_credentials(): workflow = (ROOT / ".github" / "workflows" / "candidate-contracts.yml").read_text(encoding="utf-8") diff --git a/.github/workflows/native-candidate-integration.yml b/.github/workflows/native-candidate-integration.yml index ff1ca35..fdc7ef6 100644 --- a/.github/workflows/native-candidate-integration.yml +++ b/.github/workflows/native-candidate-integration.yml @@ -15,6 +15,11 @@ on: required: false default: false type: boolean + secrets: + CANDIDATE_ARTIFACT_APP_ID: + required: true + CANDIDATE_ARTIFACT_PRIVATE_KEY: + required: true workflow_dispatch: inputs: manifest_path: diff --git a/.github/workflows/rhino-brep-integration.yml b/.github/workflows/rhino-brep-integration.yml index a18a855..65ba0ca 100644 --- a/.github/workflows/rhino-brep-integration.yml +++ b/.github/workflows/rhino-brep-integration.yml @@ -27,6 +27,9 @@ jobs: with: manifest_path: ${{ inputs.manifest_path || '.github/candidates/brep-linux-py312.json' }} brep_json: true + secrets: + CANDIDATE_ARTIFACT_APP_ID: ${{ secrets.CANDIDATE_ARTIFACT_APP_ID }} + CANDIDATE_ARTIFACT_PRIVATE_KEY: ${{ secrets.CANDIDATE_ARTIFACT_PRIVATE_KEY }} assemble-rhino-harness: if: github.repository == 'compas-dev/compas_framework' && github.ref_protected