From 943cbd9510b180709836084423c708b6d6e1e0eb Mon Sep 17 00:00:00 2001 From: Roberto Dolfini Date: Mon, 12 Oct 2026 19:25:31 +0200 Subject: [PATCH 1/8] Spec: family dimension parameters --- ...0-12-family-dimension-parameters-design.md | 96 +++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 docs/superpowers/specs/2026-10-12-family-dimension-parameters-design.md diff --git a/docs/superpowers/specs/2026-10-12-family-dimension-parameters-design.md b/docs/superpowers/specs/2026-10-12-family-dimension-parameters-design.md new file mode 100644 index 0000000..6004cb7 --- /dev/null +++ b/docs/superpowers/specs/2026-10-12-family-dimension-parameters-design.md @@ -0,0 +1,96 @@ +# Family dimension parameters - Design + +Date: 2026-10-12 +Status: approved in brainstorming, not yet implemented. + +## 1. Goal + +A shape modeled in Blender and baked as a family reaches Revit as a mute +solid. After this change the family carries a few rough dimensions as +family parameters with the `BL_` prefix, readable on the type in Revit: +length, width, height, thickness, area, volume. + +The values are **informative**: they do not drive the geometry (a +`FreeFormElement` cannot flex), and they are rewritten at every bake from +Blender, which stays the source of truth. Whoever reshapes the object must +reassign the overridden values. Scheduling them is up to the user, who can +map them to shared parameters: Bilocus creates plain family parameters. + +Out of scope: DirectShape (it has no family parameters), shared +parameters, instance parameters, parameters that drive geometry. + +## 2. The parameters + +All type parameters, group *Dimensions*, sent in SI units (m, m2, m3) and +converted by Revit to internal units; the project shows them in its own +units. + +| Parameter | Automatic value | Override | +|---|---|---| +| `BL_Length` | larger of `obj.dimensions` X, Y | sum of the selected edges | +| `BL_Width` | smaller of `obj.dimensions` X, Y | sum of the selected edges | +| `BL_Height` | `obj.dimensions` Z | sum of the selected edges | +| `BL_Thickness` | none: exists only when overridden | sum of the selected edges | +| `BL_Area` | total surface of the evaluated mesh | sum of the selected faces | +| `BL_Volume` | volume of the evaluated mesh, only if closed (every edge manifold); otherwise not sent | not overridable | + +`obj.dimensions` is Blender's own bounding box of the evaluated geometry +(modifiers included) in local axes times the object scale: the same X, Y, Z +the user reads in the N panel. Length and width are ordered by size so that +"length" stays the long side whichever local axis it lies on. Area and +volume are measured on the evaluated mesh with the object's rotation and +scale applied (no translation). Overridden edge and face measures are taken +in world scale too. + +With **Bake together** the parameters are the active object's: it already +names, places and identifies the family, and the typical members are LODs +of the same shape, whose volumes must not be summed. + +## 3. Blender side + +- Overrides are frozen values in meters, m2: object custom properties + `bilocus_param_` (e.g. `bilocus_param_length`). Not recomputed when + the mesh changes. +- Panel, Bake section, box *Family parameters* for the active object: one + row per parameter with the value that will be sent, "auto" or "set", + a button that sets it from the Edit Mode selection (edges for lengths, + faces for area) and an X that clears the override. Volume shows its value + or "open mesh". +- Pure logic (no bpy) in `bridge_bake.py`: the parameter list from + dimensions, area, volume and overrides; the `params` header field. + +## 4. Protocol + +`bake_mesh` gets an optional `params` field: an array of +`{name, kind, value}`, `kind` one of `length`, `area`, `volume`, `value` a +finite number >= 0 in SI units, `name` starting with `BL_`. Absent means +no parameters. The DirectShape bake ignores it; an older Revit add-in +ignores it too. A malformed `params` is a content error for that object. + +## 5. Revit side + +- `BakeMeshRequest` parses and validates `params` (pure, tested). +- In the family document, inside the family transaction of both creation + and re-bake: ensure a current family type, add the missing `BL_` + parameters (`FamilyManager.AddParameter`, type parameter, group + Dimensions, spec Length/Area/Volume), set their values in internal units + (`UnitUtils.ConvertToInternalUnits`), and **delete the `BL_` parameters + that did not arrive** (an override cleared, a mesh that opened): stale + data is worse than missing data. Parameters without the `BL_` prefix are + never touched. +- Re-bake reloads with `overwriteParameterValues = false` on purpose (the + user's own values on project types stay): so after the load the `BL_` + values are also written on the family's type in the project, and only + those. + +## 6. Testing + +- pytest: ordering of length and width, sums, volume only when closed, + override vs automatic, Thickness only when set, `params` in the header + and its validation. +- xUnit: `params` parsing and validation in `BakeMeshRequest`. +- Live via MCP: bake a family, read the `BL_` values on the type; override + thickness from an edge, re-bake, read it; clear it, re-bake, check it is + gone; open mesh -> no `BL_Volume`. +- Docs: DESIGN.md (`bake_mesh` row and paragraph), README (informative + values, family only), CHANGELOG. From d224d793018cc826d207b214e52bbf7542f64270 Mon Sep 17 00:00:00 2001 From: Roberto Dolfini Date: Mon, 12 Oct 2026 19:30:13 +0200 Subject: [PATCH 2/8] Plan: family dimension parameters --- .../2026-10-12-family-dimension-parameters.md | 648 ++++++++++++++++++ 1 file changed, 648 insertions(+) create mode 100644 docs/superpowers/plans/2026-10-12-family-dimension-parameters.md diff --git a/docs/superpowers/plans/2026-10-12-family-dimension-parameters.md b/docs/superpowers/plans/2026-10-12-family-dimension-parameters.md new file mode 100644 index 0000000..05b3061 --- /dev/null +++ b/docs/superpowers/plans/2026-10-12-family-dimension-parameters.md @@ -0,0 +1,648 @@ +# Family Dimension Parameters Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** A family baked from Blender carries informative `BL_` type parameters (length, width, height, thickness, area, volume), automatic from the object's extent and overridable from an edge or face selection, except the computed volume. + +**Architecture:** Blender computes the values (pure logic in a new `bridge_params.py`, bpy measuring in `bridge_bake_send.py`) and sends them in an optional `params` field of `bake_mesh`. Revit validates them in a pure `BakeParameter` class, then a thin `FamilyParameters` helper writes them in the family document (add, set, delete stale `BL_`) and on the project type after the load. + +**Tech Stack:** Python (bpy, bmesh; pytest without bpy), C# (Revit API 2024-2027, xUnit on net8/net48 with linked sources). + +**Spec:** `docs/superpowers/specs/2026-10-12-family-dimension-parameters-design.md` + +## Global Constraints + +- Parameter names: `BL_Length`, `BL_Width`, `BL_Height`, `BL_Thickness`, `BL_Area`, `BL_Volume`. +- Type parameters, group Dimensions (`GroupTypeId.Geometry`), specs `SpecTypeId.Length` / `Area` / `Volume`. +- Wire values in SI units (m, m2, m3); Revit converts with `UnitUtils.ConvertToInternalUnits` and `UnitTypeId.Meters` / `SquareMeters` / `CubicMeters`. +- Family bake only; DirectShape ignores `params`. Absent `params` = no parameters. +- Parameters without the `BL_` prefix are never touched. +- Volume is never overridable and is sent only for a closed mesh (every edge manifold). +- Code rules of the repo: ASCII only in source, no f-strings in Python. + +## Review Focus + +- Mesh with no faces or a single open face: area 0, no volume, the bake must not fail. -> Task 1 test `test_open_mesh_has_no_volume`. +- Override of 0 (user selected a degenerate edge): a 0 value is valid and sent, not dropped. -> Task 1 test `test_zero_override_is_kept`. +- Re-bake after clearing an override: the `BL_` parameter must disappear from the family. -> Task 4, live check in Task 5. +- Bake together: only the active object's values reach the family, members' values are ignored. -> Task 4 uses `host.Parameters`; live check in Task 5. +- Malformed `params` from a hand-made client (wrong kind, negative, NaN-like 1e39, name without prefix): error frame for that object, batch goes on. -> Task 3 tests. + +--- + +### Task 1: Pure parameter logic and header field (Blender, no bpy) + +**Files:** +- Create: `src/blender_addon/bridge_params.py` +- Modify: `src/blender_addon/bridge_bake.py` (`build_bake_mesh_header`, add `params=None`) +- Test: `tests/python/test_bridge_params.py`, `tests/python/test_bridge_bake.py` + +**Interfaces:** +- Produces: `bridge_params.OVERRIDABLE = ("length", "width", "height", "thickness", "area")`; `bridge_params.rows(dimensions, area, volume, overrides) -> list of (key, name, kind, value_or_None, source)` with source `"auto"`, `"set"` or `"none"`; `bridge_params.build_params(dimensions, area, volume, overrides) -> list of {"name", "kind", "value"}`; `bridge_bake.build_bake_mesh_header(..., params=None)` writes `"params"` only when not None. + +- [ ] **Step 1: Write the failing tests** (`tests/python/test_bridge_params.py`) + +```python +import os, sys +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "src", "blender_addon")) +import pytest +import bridge_params +from bridge_protocol import BridgeFramingError + +def by_name(params): + return {p["name"]: p for p in params} + +def test_length_and_width_are_ordered_by_size(): + params = by_name(bridge_params.build_params((0.6, 2.4, 0.9), 5.0, 1.2, {})) + assert params["BL_Length"]["value"] == 2.4 + assert params["BL_Width"]["value"] == 0.6 + assert params["BL_Height"]["value"] == 0.9 + +def test_kinds_and_automatic_set(): + params = by_name(bridge_params.build_params((1.0, 2.0, 3.0), 22.0, 6.0, {})) + assert set(params) == {"BL_Length", "BL_Width", "BL_Height", "BL_Area", "BL_Volume"} + assert params["BL_Area"]["kind"] == "area" + assert params["BL_Volume"]["kind"] == "volume" + assert params["BL_Length"]["kind"] == "length" + +def test_thickness_only_when_overridden(): + assert "BL_Thickness" not in by_name(bridge_params.build_params((1, 2, 3), 1.0, None, {})) + params = by_name(bridge_params.build_params((1, 2, 3), 1.0, None, {"thickness": 0.05})) + assert params["BL_Thickness"]["value"] == 0.05 + +def test_override_wins_over_automatic(): + params = by_name(bridge_params.build_params((1, 2, 3), 9.0, 6.0, {"length": 7.5, "area": 4.0})) + assert params["BL_Length"]["value"] == 7.5 + assert params["BL_Area"]["value"] == 4.0 + +def test_open_mesh_has_no_volume(): + assert "BL_Volume" not in by_name(bridge_params.build_params((1, 1, 0), 0.0, None, {})) + +def test_volume_override_is_ignored(): + params = by_name(bridge_params.build_params((1, 1, 1), 6.0, 1.0, {"volume": 99.0})) + assert params["BL_Volume"]["value"] == 1.0 + +def test_zero_override_is_kept(): + params = by_name(bridge_params.build_params((1, 2, 3), 1.0, None, {"thickness": 0.0})) + assert params["BL_Thickness"]["value"] == 0.0 + +def test_rows_say_where_each_value_comes_from(): + rows = {r[0]: r for r in bridge_params.rows((1, 2, 3), 1.0, None, {"height": 2.5})} + assert rows["height"][3:] == (2.5, "set") + assert rows["length"][3:] == (2.0, "auto") + assert rows["thickness"][3:] == (None, "none") + assert rows["volume"][3:] == (None, "none") + +@pytest.mark.parametrize("bad", [-0.1, float("nan"), float("inf")]) +def test_invalid_values_are_rejected(bad): + with pytest.raises(BridgeFramingError): + bridge_params.build_params((1, 2, 3), 1.0, None, {"length": bad}) +``` + +In `tests/python/test_bridge_bake.py`, after `test_mesh_header_has_the_fields_of_the_contract`: + +```python +def test_mesh_header_carries_params_only_when_given(): + assert "params" not in mesh_header() + params = [{"name": "BL_Length", "kind": "length", "value": 2.0}] + assert mesh_header(params=params)["params"] == params +``` + +- [ ] **Step 2: Run to verify they fail** + +Run: `python -m pytest tests/python/test_bridge_params.py tests/python/test_bridge_bake.py -q` +Expected: FAIL, `ModuleNotFoundError: bridge_params` and unexpected keyword `params`. + +- [ ] **Step 3: Implement** `src/blender_addon/bridge_params.py` + +```python +# SPDX-License-Identifier: GPL-3.0-or-later +# Copyright (c) 2026 Roberto Dolfini + +# The BL_ family parameters of a bake: rough dimensions of the object, sent +# with bake_mesh and written by Revit as type parameters of the family. +# Informative values: they do not drive the geometry. +# +# This module must NOT import bpy: it is shared with the tests. + +import math + +from bridge_protocol import BridgeFramingError + +# key, Revit name, kind. The order is the panel's. +PARAMS = ( + ("length", "BL_Length", "length"), + ("width", "BL_Width", "length"), + ("height", "BL_Height", "length"), + ("thickness", "BL_Thickness", "length"), + ("area", "BL_Area", "area"), + ("volume", "BL_Volume", "volume"), +) + +# Everything but the volume, which is computed: a hand-written volume would +# be a number about a shape that does not have it. +OVERRIDABLE = ("length", "width", "height", "thickness", "area") + + +def _automatic(dimensions, area, volume): + x, y, z = (float(c) for c in dimensions) + return { + "length": max(x, y), + "width": min(x, y), + "height": z, + "thickness": None, + "area": None if area is None else float(area), + "volume": None if volume is None else float(volume), + } + + +def rows(dimensions, area, volume, overrides): + """(key, name, kind, value, source) per parameter, source "set", "auto" + or "none" (value None: the parameter is not sent). + + dimensions is obj.dimensions (local extent times scale), area and volume + are measured on the evaluated mesh, volume None for an open mesh.""" + automatic = _automatic(dimensions, area, volume) + result = [] + for key, name, kind in PARAMS: + if key in OVERRIDABLE and key in overrides: + result.append((key, name, kind, float(overrides[key]), "set")) + elif automatic[key] is not None: + result.append((key, name, kind, automatic[key], "auto")) + else: + result.append((key, name, kind, None, "none")) + return result + + +def build_params(dimensions, area, volume, overrides): + """The params field of bake_mesh: [{name, kind, value}], SI units.""" + result = [] + for _key, name, kind, value, _source in rows(dimensions, area, volume, overrides): + if value is None: + continue + if math.isnan(value) or math.isinf(value) or value < 0.0: + raise BridgeFramingError("{}: {} is not a valid measure".format(name, value)) + result.append({"name": name, "kind": kind, "value": round(value, 6)}) + return result +``` + +In `bridge_bake.build_bake_mesh_header`: add `params=None` as last parameter, document it ("the BL_ family parameters, bridge_params.build_params; only the family bake uses them, absent when None"), and before `return` build the dict into a variable, then `if params is not None: header["params"] = list(params)`. + +- [ ] **Step 4: Run to verify they pass** + +Run: `python -m pytest tests/python -q` +Expected: all pass. + +- [ ] **Step 5: Commit** + +```bash +git add src/blender_addon/bridge_params.py src/blender_addon/bridge_bake.py tests/python/test_bridge_params.py tests/python/test_bridge_bake.py +git commit -m "Compute BL_ family parameters and carry them in bake_mesh" +``` + +### Task 2: Measuring, overrides, operators, panel and sending (Blender, bpy) + +**Files:** +- Modify: `src/blender_addon/bridge_bake_send.py` (measure, overrides, `_prepare_mesh` sends params for family) +- Modify: `src/blender_addon/panel.py` (operators `bilocus.set_bake_param`, `bilocus.clear_bake_param`, box in the bake section, `CLASSES`) + +**Interfaces:** +- Consumes: `bridge_params.rows`, `bridge_params.build_params`, `bridge_params.OVERRIDABLE`, `build_bake_mesh_header(..., params=...)`. +- Produces: `bridge_bake_send.OVERRIDE_PREFIX = "bilocus_param_"`; `measure(obj, depsgraph) -> (dimensions, area, volume_or_None)`; `overrides_of(obj) -> dict`; `selection_measure(obj, key) -> (value, problem)`. + +- [ ] **Step 1: Implement measuring and overrides** in `bridge_bake_send.py` (add `import bmesh` and `import bridge_params as params_logic`): + +```python +OVERRIDE_PREFIX = "bilocus_param_" + + +def measure(obj, depsgraph): + """(dimensions, area, volume) of the evaluated object. Area and volume + with the object's rotation and scale, no translation; volume None when + the mesh is not closed.""" + evaluated = obj.evaluated_get(depsgraph) + mesh = evaluated.to_mesh() + bm = bmesh.new() + try: + bm.from_mesh(mesh) + bm.transform(obj.matrix_world.to_3x3().to_4x4()) + area = sum(face.calc_area() for face in bm.faces) + closed = len(bm.edges) > 0 and all(edge.is_manifold for edge in bm.edges) + volume = abs(bm.calc_volume()) if closed else None + finally: + bm.free() + evaluated.to_mesh_clear() + return tuple(obj.dimensions), area, volume + + +def overrides_of(obj): + result = {} + for key in params_logic.OVERRIDABLE: + value = obj.get(OVERRIDE_PREFIX + key) + if isinstance(value, (int, float)) and not isinstance(value, bool): + result[key] = float(value) + return result + + +def selection_measure(obj, key): + """(value, problem) from the Edit Mode selection: summed edge lengths + for the lengths, summed face areas for the area, in world scale.""" + if obj is None or obj.type != 'MESH' or obj.mode != 'EDIT': + return None, "enter Edit Mode on the object and select what to measure" + bm = bmesh.from_edit_mesh(obj.data).copy() + try: + bm.transform(obj.matrix_world.to_3x3().to_4x4()) + if key == "area": + faces = [f for f in bm.faces if f.select] + if not faces: + return None, "select one or more faces" + return sum(f.calc_area() for f in faces), None + edges = [e for e in bm.edges if e.select] + if not edges: + return None, "select one or more edges" + return sum(e.calc_length() for e in edges), None + finally: + bm.free() +``` + +In `_prepare_mesh(obj, obj_id, depsgraph, reject_limit)` add a `family` argument (pass `family` from `bake_selected`), and pass to the header: + +```python + params = None + if family: + dimensions, area, volume = measure(obj, depsgraph) + params = params_logic.build_params(dimensions, area, volume, overrides_of(obj)) +``` +then `build_bake_mesh_header(..., accept_open_of(obj), smooth_mesh_of(obj), params)`. + +- [ ] **Step 2: Operators and panel** in `panel.py`: + +```python +class BILOCUS_OT_set_bake_param(bpy.types.Operator): + bl_idname = "bilocus.set_bake_param" + bl_label = "Set from selection" + bl_description = ("Sets this family parameter from the Edit Mode selection: " + "edges for lengths, faces for the area. Frozen value: " + "set it again if you reshape the object") + key: bpy.props.StringProperty() + + def execute(self, context): + obj = context.active_object + value, problem = bake_send.selection_measure(obj, self.key) + if problem is not None: + self.report({'ERROR'}, problem) + return {'CANCELLED'} + obj[bake_send.OVERRIDE_PREFIX + self.key] = value + self.report({'INFO'}, "{}: {:.4f}".format(self.key, value)) + return {'FINISHED'} + + +class BILOCUS_OT_clear_bake_param(bpy.types.Operator): + bl_idname = "bilocus.clear_bake_param" + bl_label = "Back to automatic" + bl_description = "Removes the value set by hand: the parameter goes back to automatic" + key: bpy.props.StringProperty() + + def execute(self, context): + obj = context.active_object + if obj is not None and (bake_send.OVERRIDE_PREFIX + self.key) in obj: + del obj[bake_send.OVERRIDE_PREFIX + self.key] + return {'FINISHED'} +``` + +Add both to `CLASSES`. In the bake box, after the category row, when `target` is a mesh: a sub-box "Family parameters (informative)" that calls `bake_send.measure(target, context.evaluated_depsgraph_get())` only in Object Mode (in Edit Mode show the stored overrides and "values update in Object Mode"), then for each row of `params_logic.rows(...)`: label `name`, value formatted (m with 3 decimals, m2 / m3 with 3), source; for keys in `OVERRIDABLE` an icon button `bilocus.set_bake_param` (icon `EYEDROPPER`) and, when source is "set", `bilocus.clear_bake_param` (icon `X`). Volume row shows "open mesh" when None. + +- [ ] **Step 3: Verify** + +Run: `python -m pytest tests/python -q` (no regressions) and `python -c "import ast,sys; [ast.parse(open(p,encoding='utf-8').read()) for p in sys.argv[1:]]" src/blender_addon/panel.py src/blender_addon/bridge_bake_send.py` +Expected: pass. The bpy part is verified live in Task 5. + +- [ ] **Step 4: Commit** + +```bash +git add src/blender_addon/bridge_bake_send.py src/blender_addon/panel.py +git commit -m "Measure, override and send the BL_ family parameters from Blender" +``` + +### Task 3: Parse and validate params (Revit, pure) + +**Files:** +- Create: `src/Bilocus.Revit/Bake/BakeParameter.cs` +- Modify: `src/Bilocus.Revit/Bake/BakeMeshRequest.cs` (`Parameters` property, `Parse` optional argument) +- Modify: `src/Bilocus.Revit/Net/MessageRouter.cs` (`HandleBakeMesh` reads `params`) +- Modify: `tests/Bilocus.Revit.Net.Tests/Bilocus.Revit.Net.Tests.csproj` (link `BakeParameter.cs`) +- Test: `tests/Bilocus.Revit.Net.Tests/BakeParameterTests.cs`, `MessageRouterTests.cs` + +**Interfaces:** +- Produces: `BakeParameter` with `Name`, `Kind` (`"length"|"area"|"volume"`), `Value` (double, SI), `static BakeParameter Create(string name, string kind, double value)` throwing `ArgumentException`; `const string Prefix = "BL_"`; `BakeMeshRequest.Parameters` (`IList`, never null). + +- [ ] **Step 1: Failing tests** `BakeParameterTests.cs`: + +```csharp +using System; +using Bilocus.Revit.Bake; +using Xunit; + +namespace Bilocus.Revit.Net.Tests +{ + public class BakeParameterTests + { + [Fact] + public void Create_KeepsTheValues() + { + BakeParameter p = BakeParameter.Create("BL_Length", "length", 2.4); + Assert.Equal("BL_Length", p.Name); + Assert.Equal("length", p.Kind); + Assert.Equal(2.4, p.Value); + } + + [Theory] + [InlineData("Length", "length", 1.0)] + [InlineData("BL_", "length", 1.0)] + [InlineData("BL_Len gth", "length", 1.0)] + [InlineData("BL_Length", "weight", 1.0)] + [InlineData("BL_Length", "length", -0.1)] + [InlineData("BL_Length", "length", double.PositiveInfinity)] + [InlineData("BL_Length", "length", double.NaN)] + public void Create_RejectsInvalid(string name, string kind, double value) + { + Assert.Throws(() => BakeParameter.Create(name, kind, value)); + } + + [Fact] + public void Create_AcceptsZero() + { + Assert.Equal(0.0, BakeParameter.Create("BL_Thickness", "length", 0.0).Value); + } + } +} +``` + +In `MessageRouterTests.cs`, next to the other `BakeMesh_*` tests: + +```csharp + [Fact] + public void BakeMesh_WithValidParams_IsAccepted() + { + MessageRouter router = new MessageRouter(new GeometryStore()); + Sink sink = new Sink(); + BakeBegin(router, sink, "obj-1"); + Send(router, sink, BakeGolden.MeshHeaderWith("obj-1", + "\"params\": [{\"name\": \"BL_Length\", \"kind\": \"length\", \"value\": 2.4}]"), + BakeGolden.Payload()); + Assert.Empty(sink.Sent); + } + + [Theory] + [InlineData("\"params\": {}")] + [InlineData("\"params\": [{\"name\": \"Length\", \"kind\": \"length\", \"value\": 1}]")] + [InlineData("\"params\": [{\"name\": \"BL_Length\", \"kind\": \"weight\", \"value\": 1}]")] + [InlineData("\"params\": [{\"name\": \"BL_Length\", \"kind\": \"length\", \"value\": -1}]")] + [InlineData("\"params\": [{\"name\": \"BL_Length\", \"kind\": \"length\"}]")] + [InlineData("\"params\": [{\"name\": \"BL_Length\", \"kind\": \"length\", \"value\": 1e400}]")] + public void BakeMesh_WithMalformedParams_RepliesError(string field) + { + MessageRouter router = new MessageRouter(new GeometryStore()); + Sink sink = new Sink(); + BakeBegin(router, sink, "obj-1"); + Send(router, sink, BakeGolden.MeshHeaderWith("obj-1", field), BakeGolden.Payload()); + Assert.Single(sink.Sent); + Assert.StartsWith("bake_mesh:", ErrorMessageOf(sink, 0)); + } +``` + +Link the new source in the test csproj next to `BakeMeshRequest.cs`: +`` + +- [ ] **Step 2: Run to verify they fail** + +Run: `dotnet test tests/Bilocus.Revit.Net.Tests -c Release` +Expected: build error, `BakeParameter` not found. + +- [ ] **Step 3: Implement** `BakeParameter.cs`: + +```csharp +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Roberto Dolfini + +using System; + +namespace Bilocus.Revit.Bake +{ + // One BL_ family parameter of a bake_mesh: a rough dimension of the + // Blender object, informative, written as a type parameter of the + // family. Pure, no Revit API: FamilyParameters does the writing. + public sealed class BakeParameter + { + public const string Prefix = "BL_"; + + public string Name { get; private set; } + public string Kind { get; private set; } + + // SI units: m, m2 or m3 by Kind. + public double Value { get; private set; } + + private BakeParameter(string name, string kind, double value) + { + Name = name; + Kind = kind; + Value = value; + } + + public static BakeParameter Create(string name, string kind, double value) + { + if (name == null || name.Length <= Prefix.Length || !name.StartsWith(Prefix, StringComparison.Ordinal)) + { + throw new ArgumentException("parameter name '" + name + "' must start with " + Prefix); + } + for (int i = Prefix.Length; i < name.Length; i++) + { + if (!char.IsLetter(name[i])) + { + throw new ArgumentException("parameter name '" + name + "' may only contain letters after " + Prefix); + } + } + if (kind != "length" && kind != "area" && kind != "volume") + { + throw new ArgumentException("parameter " + name + ": kind '" + kind + "' is not length, area or volume"); + } + if (double.IsNaN(value) || double.IsInfinity(value) || value < 0.0) + { + throw new ArgumentException("parameter " + name + ": value must be a finite number >= 0"); + } + return new BakeParameter(name, kind, value); + } + } +} +``` + +`BakeMeshRequest`: add `public IList Parameters { get; private set; }`, a constructor argument, and `IList parameters = null` as last optional argument of the full `Parse`; store `new List(parameters ?? new BakeParameter[0])` (add `using System.Collections.Generic;`). + +`MessageRouter.HandleBakeMesh`: after `smoothMesh`, `List parameters = OptionalBakeParameters(root);` and pass it to `Parse`. New helper: + +```csharp + // bake_mesh's params: absent = none. Present it must be an array of + // {name, kind, value}; each one is validated by BakeParameter. + private static List OptionalBakeParameters(JsonElement root) + { + List result = new List(); + JsonElement field; + if (!root.TryGetProperty("params", out field)) { return result; } + if (field.ValueKind != JsonValueKind.Array) + { + throw new ContentException("field params is not an array"); + } + foreach (JsonElement item in field.EnumerateArray()) + { + if (item.ValueKind != JsonValueKind.Object) + { + throw new ContentException("field params: every entry must be an object"); + } + string name = RequireString(item, "name"); + string kind = RequireString(item, "kind"); + JsonElement value; + double number; + if (!item.TryGetProperty("value", out value) || value.ValueKind != JsonValueKind.Number + || !value.TryGetDouble(out number)) + { + throw new ContentException("field params: " + name + " has no numeric value"); + } + result.Add(BakeParameter.Create(name, kind, number)); + } + return result; + } +``` + +Add `using Bilocus.Revit.Bake;` only if not already present. + +- [ ] **Step 4: Run to verify they pass** + +Run: `dotnet test Bilocus.sln -c Release` +Expected: all pass on net8 and net48. Note `1e400` parses to infinity in `TryGetDouble` or fails: both must end in an error frame; adjust nothing if the test passes. + +- [ ] **Step 5: Commit** + +```bash +git add src/Bilocus.Revit/Bake/BakeParameter.cs src/Bilocus.Revit/Bake/BakeMeshRequest.cs src/Bilocus.Revit/Net/MessageRouter.cs tests/Bilocus.Revit.Net.Tests +git commit -m "Parse and validate the BL_ params of bake_mesh" +``` + +### Task 4: Write the parameters in the family and on the project type (Revit API) + +**Files:** +- Create: `src/Bilocus.Revit/Bake/FamilyParameters.cs` +- Modify: `src/Bilocus.Revit/Bake/FamilyBaker.cs` (`CreateFamily` and `UpdateFamily`) + +**Interfaces:** +- Consumes: `BakeMeshRequest.Parameters`, `BakeParameter`. +- Produces: `FamilyParameters.Apply(Document familyDoc, IList parameters, string typeName)` (inside an open family transaction); `FamilyParameters.WriteToType(FamilySymbol symbol, IList parameters)` (inside an open project transaction). + +- [ ] **Step 1: Implement** `FamilyParameters.cs`: + +```csharp +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Roberto Dolfini + +using System.Collections.Generic; +using Autodesk.Revit.DB; + +namespace Bilocus.Revit.Bake +{ + // Writes the BL_ parameters of a bake: type parameters of the family, + // group Dimensions, informative values. Parameters without the BL_ + // prefix are never touched; BL_ parameters that did not arrive are + // deleted, because stale data is worse than missing data. + public static class FamilyParameters + { + public static void Apply(Document familyDoc, IList parameters, string typeName) + { + FamilyManager manager = familyDoc.FamilyManager; + if (manager.CurrentType == null) { manager.NewType(typeName); } + + Dictionary wanted = new Dictionary(); + foreach (BakeParameter p in parameters) { wanted[p.Name] = p; } + + List existing = new List(); + foreach (FamilyParameter fp in manager.Parameters) { existing.Add(fp); } + + foreach (FamilyParameter fp in existing) + { + string name = fp.Definition.Name; + if (!name.StartsWith(BakeParameter.Prefix)) { continue; } + BakeParameter p; + if (!wanted.TryGetValue(name, out p) || fp.Definition.GetDataType() != SpecOf(p.Kind) || fp.IsInstance) + { + manager.RemoveParameter(fp); + } + } + + foreach (BakeParameter p in parameters) + { + FamilyParameter fp = manager.get_Parameter(p.Name); + if (fp == null) + { + fp = manager.AddParameter(p.Name, GroupTypeId.Geometry, SpecOf(p.Kind), false); + } + manager.Set(fp, ToInternal(p)); + } + } + + public static void WriteToType(FamilySymbol symbol, IList parameters) + { + if (symbol == null) { return; } + foreach (BakeParameter p in parameters) + { + Parameter parameter = symbol.LookupParameter(p.Name); + if (parameter != null && !parameter.IsReadOnly) { parameter.Set(ToInternal(p)); } + } + } + + private static ForgeTypeId SpecOf(string kind) + { + if (kind == "area") { return SpecTypeId.Area; } + if (kind == "volume") { return SpecTypeId.Volume; } + return SpecTypeId.Length; + } + + private static double ToInternal(BakeParameter p) + { + ForgeTypeId unit = p.Kind == "area" ? UnitTypeId.SquareMeters + : p.Kind == "volume" ? UnitTypeId.CubicMeters : UnitTypeId.Meters; + return UnitUtils.ConvertToInternalUnits(p.Value, unit); + } + } +} +``` + +- [ ] **Step 2: Hook into FamilyBaker** + - `CreateFamily`, inside the family transaction lambda, after the marking loop and before `return null;`: `FamilyParameters.Apply(familyDoc, host.Parameters, familyName);` + - `UpdateFamily`, inside the family transaction lambda, after `removedMembers = RemoveOtherMembers(...)`: `FamilyParameters.Apply(familyDoc, host.Parameters, familyName);` + - `UpdateFamily`, in the project transaction that follows the load (the one that computes `switched` / `notMoved` on `target`): `FamilyParameters.WriteToType(FirstSymbol(target), host.Parameters);` as its first statement. + - Read the exact surrounding code before editing and keep the existing comment style: one short comment at each call stating why (re-bake loads with `overwriteParameterValues = false`, hence the write on the type). + +- [ ] **Step 3: Verify build** for all Revit versions: + +Run: `for v in 2024 2025 2026 2027; do dotnet build src/Bilocus.Revit/Bilocus.Revit.csproj -c Release -p:RevitVersion=$v; done` and `dotnet test Bilocus.sln -c Release` +Expected: 0 errors, 0 warnings, tests pass. + +- [ ] **Step 4: Commit** + +```bash +git add src/Bilocus.Revit/Bake/FamilyParameters.cs src/Bilocus.Revit/Bake/FamilyBaker.cs +git commit -m "Write the BL_ parameters in the baked family and on its project type" +``` + +### Task 5: Docs, deploy and live verification + +**Files:** +- Modify: `DESIGN.md` (`bake_mesh` row: add `params?`; paragraph on params), `README.md` (Bake bullet: informative BL_ parameters, family only), `CHANGELOG.md` (Unreleased entry) + +- [ ] **Step 1: Docs.** DESIGN: `bake_mesh` row gets `params?`; a paragraph after the bake_mesh description stating the shape `[{name, kind, value}]`, SI units, family only, BL_ prefix, stale BL_ deleted, written on the project type after the load. README Bake bullet: one sentence "A family also carries `BL_` type parameters (length, width, height, area, volume, optional thickness): informative values from the object's extent, overridable in the panel, not linked to the geometry." CHANGELOG `## Unreleased` with a "New: **family dimension parameters.**" entry. +- [ ] **Step 2: Deploy** Revit 2024-2027 and Blender 4.2/5.1/5.2 with the tools scripts (Revit and Blender closed), combining the open branches as done for the previous features. +- [ ] **Step 3: Live via MCP** (Revit 2025 + Blender 5.2): + 1. Blender: box 2.4 x 0.6 x 0.9 m in ToRevit, Bake Family. Revit: the type has BL_Length 2.4, BL_Width 0.6, BL_Height 0.9, BL_Area 8.28 (2*(2.4*0.6+2.4*0.9+0.6*0.9)), BL_Volume 1.296; no BL_Thickness. + 2. Edit Mode, select one 0.6 edge, set Thickness; re-bake; the type has BL_Thickness 0.6. + 3. Clear Thickness, re-bake; BL_Thickness is gone from the family and the type. + 4. Delete one face (open mesh) with Accept open on, re-bake; BL_Volume is gone. + 5. Bake together with a second object active-first: values are the active object's. +- [ ] **Step 4: Commit docs**, push, open the PR. From dc6f9280d2897528b33c2a72e519a03868478e97 Mon Sep 17 00:00:00 2001 From: Roberto Dolfini Date: Mon, 12 Oct 2026 19:31:17 +0200 Subject: [PATCH 3/8] Compute BL_ family parameters and carry them in bake_mesh Co-Authored-By: Claude Opus 5.5 --- src/blender_addon/bridge_bake.py | 12 +++-- src/blender_addon/bridge_params.py | 71 +++++++++++++++++++++++++++++ tests/python/test_bridge_bake.py | 6 +++ tests/python/test_bridge_params.py | 73 ++++++++++++++++++++++++++++++ 4 files changed, 159 insertions(+), 3 deletions(-) create mode 100644 src/blender_addon/bridge_params.py create mode 100644 tests/python/test_bridge_params.py diff --git a/src/blender_addon/bridge_bake.py b/src/blender_addon/bridge_bake.py index e04fe44..96a2871 100644 --- a/src/blender_addon/bridge_bake.py +++ b/src/blender_addon/bridge_bake.py @@ -371,7 +371,7 @@ def build_bake_begin_header(obj_ids, target="directshape", host=None): def build_bake_mesh_header(obj_id, name, category, matrix, vert_count, face_count, loop_count, tri_count, - accept_open=False, smooth_mesh=False): + accept_open=False, smooth_mesh=False, params=None): """The bake_mesh header. The counts must be those of the sequences passed to pack_bake_payload (see its docstring). @@ -385,7 +385,10 @@ def build_bake_mesh_header(obj_id, name, category, matrix, smooth_mesh asks the DirectShape bake for a Revit mesh instead of a solid: drawn without edges, no volume. The family bake ignores it, a - family needs a solid. Always written, like accept_open.""" + family needs a solid. Always written, like accept_open. + + params are the BL_ family parameters (bridge_params.build_params): only + the family bake uses them, and the field is absent when None.""" normalized = _normalize_object_id(obj_id) # Only a real bool. A 1 or a "true" on the wire is a content error for @@ -432,7 +435,7 @@ def build_bake_mesh_header(obj_id, name, category, matrix, "the triangles must be {}".format( tri_count, loop_count, face_count, loop_count - 2 * face_count)) - return { + header = { "type": "bake_mesh", "obj_id": normalized, "name": label, @@ -445,6 +448,9 @@ def build_bake_mesh_header(obj_id, name, category, matrix, "accept_open": accept_open, "smooth_mesh": smooth_mesh, } + if params is not None: + header["params"] = list(params) + return header def build_bake_end_header(): diff --git a/src/blender_addon/bridge_params.py b/src/blender_addon/bridge_params.py new file mode 100644 index 0000000..6dbf711 --- /dev/null +++ b/src/blender_addon/bridge_params.py @@ -0,0 +1,71 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# Copyright (c) 2026 Roberto Dolfini + +# The BL_ family parameters of a bake: rough dimensions of the object, sent +# with bake_mesh and written by Revit as type parameters of the family. +# Informative values: they do not drive the geometry, and they are rewritten +# at every bake. +# +# This module must NOT import bpy: it is shared with the tests. + +import math + +from bridge_protocol import BridgeFramingError + +# key, Revit name, kind. The order is the panel's. +PARAMS = ( + ("length", "BL_Length", "length"), + ("width", "BL_Width", "length"), + ("height", "BL_Height", "length"), + ("thickness", "BL_Thickness", "length"), + ("area", "BL_Area", "area"), + ("volume", "BL_Volume", "volume"), +) + +# Everything but the volume, which is computed: a hand-written volume would +# be a number about a shape that does not have it. +OVERRIDABLE = ("length", "width", "height", "thickness", "area") + + +def _automatic(dimensions, area, volume): + # Length and width ordered by size: "length" stays the long side + # whichever local axis the object was modeled along. + x, y, z = (float(c) for c in dimensions) + return { + "length": max(x, y), + "width": min(x, y), + "height": z, + "thickness": None, + "area": None if area is None else float(area), + "volume": None if volume is None else float(volume), + } + + +def rows(dimensions, area, volume, overrides): + """(key, name, kind, value, source) per parameter, source "set", "auto" + or "none" (value None: the parameter is not sent). + + dimensions is obj.dimensions (local extent times scale), area and volume + are measured on the evaluated mesh, volume None for an open mesh.""" + automatic = _automatic(dimensions, area, volume) + result = [] + for key, name, kind in PARAMS: + if key in OVERRIDABLE and key in overrides: + result.append((key, name, kind, float(overrides[key]), "set")) + elif automatic[key] is not None: + result.append((key, name, kind, automatic[key], "auto")) + else: + result.append((key, name, kind, None, "none")) + return result + + +def build_params(dimensions, area, volume, overrides): + """The params field of bake_mesh: [{name, kind, value}], SI units.""" + result = [] + for _key, name, kind, value, _source in rows(dimensions, area, volume, overrides): + if value is None: + continue + if math.isnan(value) or math.isinf(value) or value < 0.0: + raise BridgeFramingError("{}: {} is not a valid measure".format(name, value)) + result.append({"name": name, "kind": kind, "value": round(value, 6)}) + return result diff --git a/tests/python/test_bridge_bake.py b/tests/python/test_bridge_bake.py index 41580de..d49993a 100644 --- a/tests/python/test_bridge_bake.py +++ b/tests/python/test_bridge_bake.py @@ -599,6 +599,12 @@ def test_mesh_header_has_the_fields_of_the_contract(): } +def test_mesh_header_carries_params_only_when_given(): + assert "params" not in mesh_header() + params = [{"name": "BL_Length", "kind": "length", "value": 2.0}] + assert mesh_header(params=params)["params"] == params + + def test_mesh_header_writes_accept_open_when_true(): assert mesh_header(accept_open=True)["accept_open"] is True diff --git a/tests/python/test_bridge_params.py b/tests/python/test_bridge_params.py new file mode 100644 index 0000000..db122b3 --- /dev/null +++ b/tests/python/test_bridge_params.py @@ -0,0 +1,73 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# Copyright (c) 2026 Roberto Dolfini + +# Tests for bridge_params.py, the BL_ family parameters of a bake. +# Does NOT import bpy: runs under pytest with the system Python. + +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "src", "blender_addon")) + +import pytest +import bridge_params +from bridge_protocol import BridgeFramingError + + +def by_name(params): + return {p["name"]: p for p in params} + + +def test_length_and_width_are_ordered_by_size(): + params = by_name(bridge_params.build_params((0.6, 2.4, 0.9), 5.0, 1.2, {})) + assert params["BL_Length"]["value"] == 2.4 + assert params["BL_Width"]["value"] == 0.6 + assert params["BL_Height"]["value"] == 0.9 + + +def test_kinds_and_automatic_set(): + params = by_name(bridge_params.build_params((1.0, 2.0, 3.0), 22.0, 6.0, {})) + assert set(params) == {"BL_Length", "BL_Width", "BL_Height", "BL_Area", "BL_Volume"} + assert params["BL_Area"]["kind"] == "area" + assert params["BL_Volume"]["kind"] == "volume" + assert params["BL_Length"]["kind"] == "length" + + +def test_thickness_only_when_overridden(): + assert "BL_Thickness" not in by_name(bridge_params.build_params((1, 2, 3), 1.0, None, {})) + params = by_name(bridge_params.build_params((1, 2, 3), 1.0, None, {"thickness": 0.05})) + assert params["BL_Thickness"]["value"] == 0.05 + + +def test_override_wins_over_automatic(): + params = by_name(bridge_params.build_params((1, 2, 3), 9.0, 6.0, {"length": 7.5, "area": 4.0})) + assert params["BL_Length"]["value"] == 7.5 + assert params["BL_Area"]["value"] == 4.0 + + +def test_open_mesh_has_no_volume(): + assert "BL_Volume" not in by_name(bridge_params.build_params((1, 1, 0), 0.0, None, {})) + + +def test_volume_override_is_ignored(): + params = by_name(bridge_params.build_params((1, 1, 1), 6.0, 1.0, {"volume": 99.0})) + assert params["BL_Volume"]["value"] == 1.0 + + +def test_zero_override_is_kept(): + params = by_name(bridge_params.build_params((1, 2, 3), 1.0, None, {"thickness": 0.0})) + assert params["BL_Thickness"]["value"] == 0.0 + + +def test_rows_say_where_each_value_comes_from(): + rows = {r[0]: r for r in bridge_params.rows((1, 2, 3), 1.0, None, {"height": 2.5})} + assert rows["height"][3:] == (2.5, "set") + assert rows["length"][3:] == (2.0, "auto") + assert rows["thickness"][3:] == (None, "none") + assert rows["volume"][3:] == (None, "none") + + +@pytest.mark.parametrize("bad", [-0.1, float("nan"), float("inf")]) +def test_invalid_values_are_rejected(bad): + with pytest.raises(BridgeFramingError): + bridge_params.build_params((1, 2, 3), 1.0, None, {"length": bad}) From a2e940ba4ff2b1442b27620abd205b045d495b2b Mon Sep 17 00:00:00 2001 From: Roberto Dolfini Date: Mon, 12 Oct 2026 19:32:15 +0200 Subject: [PATCH 4/8] Measure, override and send the BL_ family parameters from Blender Co-Authored-By: Claude Opus 5.5 --- src/blender_addon/bridge_bake_send.py | 72 +++++++++++++++++++++++++-- src/blender_addon/panel.py | 70 ++++++++++++++++++++++++++ 2 files changed, 139 insertions(+), 3 deletions(-) diff --git a/src/blender_addon/bridge_bake_send.py b/src/blender_addon/bridge_bake_send.py index 2985223..dcd8b33 100644 --- a/src/blender_addon/bridge_bake_send.py +++ b/src/blender_addon/bridge_bake_send.py @@ -16,9 +16,11 @@ # guarantees that what ends up in Revit is what was seen in the preview, # with the same id. +import bmesh import bpy import bridge_bake as bake +import bridge_params as params_logic import bridge_client as client import bridge_collection as coll import bridge_extract as extract @@ -412,7 +414,7 @@ def bake_selected(context=None, target="directshape", together=False): lost = False try: for obj, obj_id in announced: - problem, header, payload = _prepare_mesh(obj, obj_id, depsgraph, reject_limit) + problem, header, payload = _prepare_mesh(obj, obj_id, depsgraph, reject_limit, family) if problem is not None: # Rejected before producing any bytes: the connection is # intact. The object is already announced, so Revit will @@ -471,7 +473,65 @@ def bake_selected(context=None, target="directshape", together=False): return _record(level, message) -def _prepare_mesh(obj, obj_id, depsgraph, reject_limit): +# Object custom properties holding the BL_ values set by hand, in meters +# and square meters: bilocus_param_length, ... Frozen: not recomputed when +# the mesh changes. +OVERRIDE_PREFIX = "bilocus_param_" + + +def measure(obj, depsgraph): + """(dimensions, area, volume) of the evaluated object, for the BL_ + family parameters. dimensions is obj.dimensions (local extent times + scale, modifiers included); area and volume carry the object's rotation + and scale, no translation; volume is None when the mesh is not closed.""" + evaluated = obj.evaluated_get(depsgraph) + mesh_data = evaluated.to_mesh() + bm = bmesh.new() + try: + bm.from_mesh(mesh_data) + bm.transform(obj.matrix_world.to_3x3().to_4x4()) + area = sum(face.calc_area() for face in bm.faces) + closed = len(bm.edges) > 0 and all(edge.is_manifold for edge in bm.edges) + volume = abs(bm.calc_volume()) if closed else None + finally: + bm.free() + evaluated.to_mesh_clear() + return tuple(obj.dimensions), area, volume + + +def overrides_of(obj): + """The BL_ values set by hand on the object, {key: value}.""" + result = {} + for key in params_logic.OVERRIDABLE: + value = obj.get(OVERRIDE_PREFIX + key) + if isinstance(value, (int, float)) and not isinstance(value, bool): + result[key] = float(value) + return result + + +def selection_measure(obj, key): + """(value, problem) from the Edit Mode selection: summed edge lengths + for the lengths, summed face areas for the area, in world scale.""" + if obj is None or obj.type != 'MESH' or obj.mode != 'EDIT': + return None, "enter Edit Mode on the object and select what to measure" + # a copy: transforming the edit bmesh itself would move the vertices + bm = bmesh.from_edit_mesh(obj.data).copy() + try: + bm.transform(obj.matrix_world.to_3x3().to_4x4()) + if key == "area": + faces = [face for face in bm.faces if face.select] + if not faces: + return None, "select one or more faces" + return sum(face.calc_area() for face in faces), None + edges = [edge for edge in bm.edges if edge.select] + if not edges: + return None, "select one or more edges" + return sum(edge.calc_length() for edge in edges), None + finally: + bm.free() + + +def _prepare_mesh(obj, obj_id, depsgraph, reject_limit, family=False): """(problem, header, payload): problem is None if the object is ready. Except Exception and not just BridgeFramingError: even a bpy @@ -494,13 +554,19 @@ def _prepare_mesh(obj, obj_id, depsgraph, reject_limit): payload = bake.pack_bake_payload( positions, face_sizes, face_vertices, tri_vertices, tri_faces) + # The BL_ parameters only mean something for a family: a + # DirectShape has no family parameters. + params = None + if family: + dimensions, area, volume = measure(obj, depsgraph) + params = params_logic.build_params(dimensions, area, volume, overrides_of(obj)) # counts from the same sequences passed to pack_bake_payload: this # is the condition for the header and the payload to agree on the # Revit side header = bake.build_bake_mesh_header( obj_id, obj.name, category_of(obj), obj.matrix_world, len(positions) // 3, len(face_sizes), len(face_vertices), len(tri_faces), - accept_open_of(obj), smooth_mesh_of(obj)) + accept_open_of(obj), smooth_mesh_of(obj), params) except Exception as error: return str(error), None, None return None, header, payload diff --git a/src/blender_addon/panel.py b/src/blender_addon/panel.py index 64e5605..b26f6f2 100644 --- a/src/blender_addon/panel.py +++ b/src/blender_addon/panel.py @@ -7,6 +7,7 @@ import bridge_client as client import bridge_collection as coll import bridge_fit as fit +import bridge_params as params_logic import bridge_import as imp import bridge_protocol as protocol import bridge_proxy as proxy @@ -108,6 +109,40 @@ def execute(self, context): return {'FINISHED'} +class BILOCUS_OT_set_bake_param(bpy.types.Operator): + bl_idname = "bilocus.set_bake_param" + bl_label = "Set from selection" + bl_description = ("Sets this family parameter from the Edit Mode " + "selection: edges for lengths, faces for the area. " + "Frozen value: set it again if you reshape the object") + + key: bpy.props.StringProperty() + + def execute(self, context): + obj = context.active_object + value, problem = bake.selection_measure(obj, self.key) + if problem is not None: + self.report({'ERROR'}, problem) + return {'CANCELLED'} + obj[bake.OVERRIDE_PREFIX + self.key] = value + self.report({'INFO'}, "{}: {:.4f}".format(self.key, value)) + return {'FINISHED'} + + +class BILOCUS_OT_clear_bake_param(bpy.types.Operator): + bl_idname = "bilocus.clear_bake_param" + bl_label = "Back to automatic" + bl_description = "Removes the value set by hand: the parameter goes back to automatic" + + key: bpy.props.StringProperty() + + def execute(self, context): + obj = context.active_object + if obj is not None and (bake.OVERRIDE_PREFIX + self.key) in obj: + del obj[bake.OVERRIDE_PREFIX + self.key] + return {'FINISHED'} + + class BILOCUS_OT_bake_directshape(bpy.types.Operator): bl_idname = "bilocus.bake_directshape" bl_label = "Bake DirectShape" @@ -377,6 +412,7 @@ def draw(self, context): box.prop(target, bake.ACCEPT_OPEN_PROPERTY, text="Accept open solid") if hasattr(target, bake.SMOOTH_MESH_PROPERTY): box.prop(target, bake.SMOOTH_MESH_PROPERTY, text="Smooth mesh (no volume)") + _draw_family_params(box, target) row = box.row() row.enabled = target is not None @@ -449,6 +485,38 @@ def draw(self, context): box.prop(context.scene, "bilocus_max_vertices") +def _draw_family_params(layout, target): + """The BL_ parameters a family bake will send for the active object. + + Area and volume are NOT measured here: draw() runs on every redraw of + the sidebar, and evaluating the mesh at that rate is what this panel + already avoids for the triangle count. obj.dimensions costs nothing; + area and volume are computed at bake time unless set by hand.""" + box = layout.box() + box.label(text="Family parameters (informative)") + overrides = bake.overrides_of(target) + # area None and volume None: shown as computed at bake, not as missing + for key, name, _kind, value, source in params_logic.rows( + tuple(target.dimensions), None, None, overrides): + row = box.row(align=True) + if source == "none" and key in ("area", "volume"): + text = "{}: computed at bake".format(name) + if key == "volume": + text = "{} (closed mesh only)".format(text) + elif source == "none": + text = "{}: -".format(name) + else: + unit = "m2" if key == "area" else "m" + text = "{}: {:.3f} {} ({})".format(name, value, unit, source) + row.label(text=text) + if key in params_logic.OVERRIDABLE: + op = row.operator("bilocus.set_bake_param", text="", icon='EYEDROPPER') + op.key = key + if source == "set": + op = row.operator("bilocus.clear_bake_param", text="", icon='X') + op.key = key + + CLASSES = ( BILOCUS_OT_connect, BILOCUS_OT_disconnect, @@ -461,5 +529,7 @@ def draw(self, context): BILOCUS_OT_bake_family, BILOCUS_OT_remove_bake, BILOCUS_OT_apply_bake_category, + BILOCUS_OT_set_bake_param, + BILOCUS_OT_clear_bake_param, BILOCUS_PT_panel, ) From 459eb0508dc24a082923f242206e535d22bc4234 Mon Sep 17 00:00:00 2001 From: Roberto Dolfini Date: Mon, 12 Oct 2026 19:33:22 +0200 Subject: [PATCH 5/8] Parse and validate the BL_ params of bake_mesh Co-Authored-By: Claude Opus 5.5 --- src/Bilocus.Revit/Bake/BakeMeshRequest.cs | 14 ++++- src/Bilocus.Revit/Bake/BakeParameter.cs | 62 +++++++++++++++++++ src/Bilocus.Revit/Net/MessageRouter.cs | 37 ++++++++++- .../BakeParameterTests.cs | 41 ++++++++++++ .../Bilocus.Revit.Net.Tests.csproj | 1 + .../MessageRouterTests.cs | 32 ++++++++++ 6 files changed, 183 insertions(+), 4 deletions(-) create mode 100644 src/Bilocus.Revit/Bake/BakeParameter.cs create mode 100644 tests/Bilocus.Revit.Net.Tests/BakeParameterTests.cs diff --git a/src/Bilocus.Revit/Bake/BakeMeshRequest.cs b/src/Bilocus.Revit/Bake/BakeMeshRequest.cs index 5abec44..9c87658 100644 --- a/src/Bilocus.Revit/Bake/BakeMeshRequest.cs +++ b/src/Bilocus.Revit/Bake/BakeMeshRequest.cs @@ -2,6 +2,7 @@ // Copyright (c) 2026 Roberto Dolfini using System; +using System.Collections.Generic; using Bilocus.Geometry; using Bilocus.Revit.Proxy; @@ -56,8 +57,13 @@ public sealed class BakeMeshRequest // solid. False if the message does not carry it. public bool SmoothMesh { get; private set; } + // The BL_ family parameters. Only the family bake writes them, and + // with Bake together only the host's: the members are often LODs of + // the same shape. Never null, empty if the message has none. + public IList Parameters { get; private set; } + private BakeMeshRequest(string objectId, string name, string category, float[] matrix, - BakeMeshPayload mesh, bool acceptOpen, bool smoothMesh) + BakeMeshPayload mesh, bool acceptOpen, bool smoothMesh, IList parameters) { ObjectId = objectId; Name = name; @@ -66,6 +72,7 @@ private BakeMeshRequest(string objectId, string name, string category, float[] m Mesh = mesh; AcceptOpen = acceptOpen; SmoothMesh = smoothMesh; + Parameters = parameters; } // The Phase B Parse: AcceptOpen false. @@ -88,7 +95,7 @@ public static BakeMeshRequest Parse(string objectId, string name, string categor // be reported. public static BakeMeshRequest Parse(string objectId, string name, string category, float[] matrix, int vertCount, int faceCount, int loopCount, int triCount, byte[] payload, bool acceptOpen, - bool smoothMesh = false) + bool smoothMesh = false, IList parameters = null) { // Without identity there is neither replacement nor removal: // better to reject the message than to leave a DirectShape in the @@ -133,7 +140,8 @@ public static BakeMeshRequest Parse(string objectId, string name, string categor // The request stays pending until it is drained: a copy, so a // caller that reuses its array does not move the object. return new BakeMeshRequest( - normalizedId, label, category, (float[])matrix.Clone(), mesh, acceptOpen, smoothMesh); + normalizedId, label, category, (float[])matrix.Clone(), mesh, acceptOpen, smoothMesh, + new List(parameters ?? new BakeParameter[0])); } } } diff --git a/src/Bilocus.Revit/Bake/BakeParameter.cs b/src/Bilocus.Revit/Bake/BakeParameter.cs new file mode 100644 index 0000000..1f46d17 --- /dev/null +++ b/src/Bilocus.Revit/Bake/BakeParameter.cs @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Roberto Dolfini + +using System; + +namespace Bilocus.Revit.Bake +{ + // One BL_ family parameter of a bake_mesh: a rough dimension of the + // Blender object, informative, written as a type parameter of the + // family. No Revit API in here, so it is checked by the tests; + // FamilyParameters does the writing. + public sealed class BakeParameter + { + public const string Prefix = "BL_"; + + public string Name { get; private set; } + + // "length", "area" or "volume": it picks the Revit spec and unit. + public string Kind { get; private set; } + + // SI units, m, m2 or m3 by Kind. + public double Value { get; private set; } + + private BakeParameter(string name, string kind, double value) + { + Name = name; + Kind = kind; + Value = value; + } + + // Throws ArgumentException on anything a Blender add-on would never + // send: the router turns it into a "bake_mesh: ..." error for that + // object. Letters only after the prefix, because the name becomes a + // family parameter name and the prefix is how stale ones are found. + public static BakeParameter Create(string name, string kind, double value) + { + if (name == null || name.Length <= Prefix.Length + || !name.StartsWith(Prefix, StringComparison.Ordinal)) + { + throw new ArgumentException("parameter name '" + name + "' must start with " + Prefix); + } + for (int i = Prefix.Length; i < name.Length; i++) + { + if (!char.IsLetter(name[i])) + { + throw new ArgumentException( + "parameter name '" + name + "' may only contain letters after " + Prefix); + } + } + if (kind != "length" && kind != "area" && kind != "volume") + { + throw new ArgumentException( + "parameter " + name + ": kind '" + kind + "' is not length, area or volume"); + } + if (double.IsNaN(value) || double.IsInfinity(value) || value < 0.0) + { + throw new ArgumentException("parameter " + name + ": value must be a finite number >= 0"); + } + return new BakeParameter(name, kind, value); + } + } +} diff --git a/src/Bilocus.Revit/Net/MessageRouter.cs b/src/Bilocus.Revit/Net/MessageRouter.cs index 13ee388..d2c27f0 100644 --- a/src/Bilocus.Revit/Net/MessageRouter.cs +++ b/src/Bilocus.Revit/Net/MessageRouter.cs @@ -412,10 +412,13 @@ private void HandleBakeMesh(JsonElement root, byte[] payload) // Same rules, the other way round: absent = false, read and // validated in a family batch too, where it is ignored. bool smoothMesh = OptionalBool(root, "smooth_mesh", false); + // Absent = none. Read in a DirectShape batch too, where it is + // then ignored, like the flags above. + List parameters = OptionalBakeParameters(root); BakeMeshRequest request = BakeMeshRequest.Parse( objId, name, category, matrix, vertCount, faceCount, loopCount, triCount, payload, - acceptOpen, smoothMesh); + acceptOpen, smoothMesh, parameters); // Rejects an id not announced; a second arrival of the same // id replaces the first. A rejected bake_mesh, here or above, @@ -872,6 +875,38 @@ private static bool OptionalBool(JsonElement root, string name, bool fallback) throw new ContentException("field " + name + " is not a boolean"); } + // bake_mesh's params: absent = none. Present it must be an array of + // {name, kind, value}; each entry is checked by BakeParameter, whose + // ArgumentException the caller re-encodes as a bake_mesh error. + private static List OptionalBakeParameters(JsonElement root) + { + List result = new List(); + JsonElement field; + if (!root.TryGetProperty("params", out field)) { return result; } + if (field.ValueKind != JsonValueKind.Array) + { + throw new ContentException("field params is not an array"); + } + foreach (JsonElement item in field.EnumerateArray()) + { + if (item.ValueKind != JsonValueKind.Object) + { + throw new ContentException("field params: every entry must be an object"); + } + string name = RequireString(item, "name"); + string kind = RequireString(item, "kind"); + JsonElement value; + double number; + if (!item.TryGetProperty("value", out value) || value.ValueKind != JsonValueKind.Number + || !value.TryGetDouble(out number)) + { + throw new ContentException("field params: " + name + " has no numeric value"); + } + result.Add(BakeParameter.Create(name, kind, number)); + } + return result; + } + // bake_begin's target: absent = BakeTarget.DirectShape. If present it // must be a string accepted by BakeTarget.TryParse; any other value // or type, null included, is a content error. diff --git a/tests/Bilocus.Revit.Net.Tests/BakeParameterTests.cs b/tests/Bilocus.Revit.Net.Tests/BakeParameterTests.cs new file mode 100644 index 0000000..84ae519 --- /dev/null +++ b/tests/Bilocus.Revit.Net.Tests/BakeParameterTests.cs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Roberto Dolfini + +using System; +using Bilocus.Revit.Bake; +using Xunit; + +namespace Bilocus.Revit.Net.Tests +{ + public class BakeParameterTests + { + [Fact] + public void Create_KeepsTheValues() + { + BakeParameter p = BakeParameter.Create("BL_Length", "length", 2.4); + Assert.Equal("BL_Length", p.Name); + Assert.Equal("length", p.Kind); + Assert.Equal(2.4, p.Value); + } + + [Theory] + [InlineData("Length", "length", 1.0)] + [InlineData("BL_", "length", 1.0)] + [InlineData("BL_Len gth", "length", 1.0)] + [InlineData("BL_Length", "weight", 1.0)] + [InlineData("BL_Length", "length", -0.1)] + [InlineData("BL_Length", "length", double.PositiveInfinity)] + [InlineData("BL_Length", "length", double.NaN)] + public void Create_RejectsInvalid(string name, string kind, double value) + { + Assert.Throws(() => BakeParameter.Create(name, kind, value)); + } + + // A degenerate edge measures 0: still a value, not a missing one. + [Fact] + public void Create_AcceptsZero() + { + Assert.Equal(0.0, BakeParameter.Create("BL_Thickness", "length", 0.0).Value); + } + } +} diff --git a/tests/Bilocus.Revit.Net.Tests/Bilocus.Revit.Net.Tests.csproj b/tests/Bilocus.Revit.Net.Tests/Bilocus.Revit.Net.Tests.csproj index 37180d4..4b26b6b 100644 --- a/tests/Bilocus.Revit.Net.Tests/Bilocus.Revit.Net.Tests.csproj +++ b/tests/Bilocus.Revit.Net.Tests/Bilocus.Revit.Net.Tests.csproj @@ -111,6 +111,7 @@ four files, this project stops compiling. --> + diff --git a/tests/Bilocus.Revit.Net.Tests/MessageRouterTests.cs b/tests/Bilocus.Revit.Net.Tests/MessageRouterTests.cs index c5a1044..eba35e8 100644 --- a/tests/Bilocus.Revit.Net.Tests/MessageRouterTests.cs +++ b/tests/Bilocus.Revit.Net.Tests/MessageRouterTests.cs @@ -1097,6 +1097,38 @@ public void BakeBegin_WithoutObjIds_RepliesError() Assert.Contains("obj_ids", message); } + [Fact] + public void BakeMesh_WithValidParams_IsAccepted() + { + MessageRouter router = new MessageRouter(new GeometryStore()); + Sink sink = new Sink(); + BakeBegin(router, sink, "obj-1"); + Send(router, sink, BakeGolden.MeshHeaderWith("obj-1", + "\"params\": [{\"name\": \"BL_Length\", \"kind\": \"length\", \"value\": 2.4}]"), + BakeGolden.Payload()); + Assert.Empty(sink.Sent); + } + + // A hand-made client: the object is refused with a readable error, + // the batch goes on. + [Theory] + [InlineData("\"params\": {}")] + [InlineData("\"params\": [1]")] + [InlineData("\"params\": [{\"name\": \"Length\", \"kind\": \"length\", \"value\": 1}]")] + [InlineData("\"params\": [{\"name\": \"BL_Length\", \"kind\": \"weight\", \"value\": 1}]")] + [InlineData("\"params\": [{\"name\": \"BL_Length\", \"kind\": \"length\", \"value\": -1}]")] + [InlineData("\"params\": [{\"name\": \"BL_Length\", \"kind\": \"length\"}]")] + [InlineData("\"params\": [{\"name\": \"BL_Length\", \"kind\": \"length\", \"value\": 1e400}]")] + public void BakeMesh_WithMalformedParams_RepliesError(string field) + { + MessageRouter router = new MessageRouter(new GeometryStore()); + Sink sink = new Sink(); + BakeBegin(router, sink, "obj-1"); + Send(router, sink, BakeGolden.MeshHeaderWith("obj-1", field), BakeGolden.Payload()); + Assert.Single(sink.Sent); + Assert.StartsWith("bake_mesh:", ErrorMessageOf(sink, 0)); + } + [Fact] public void BakeMesh_WithAMalformedCategory_RepliesError() { From 6c1f19c533cd73ef84b389ff093295242fc0caaf Mon Sep 17 00:00:00 2001 From: Roberto Dolfini Date: Mon, 12 Oct 2026 19:34:15 +0200 Subject: [PATCH 6/8] Write the BL_ parameters in the baked family and on its project types Co-Authored-By: Claude Opus 5.5 --- src/Bilocus.Revit/Bake/FamilyBaker.cs | 11 +++ src/Bilocus.Revit/Bake/FamilyParameters.cs | 104 +++++++++++++++++++++ 2 files changed, 115 insertions(+) create mode 100644 src/Bilocus.Revit/Bake/FamilyParameters.cs diff --git a/src/Bilocus.Revit/Bake/FamilyBaker.cs b/src/Bilocus.Revit/Bake/FamilyBaker.cs index d1c4b6d..7258cfa 100644 --- a/src/Bilocus.Revit/Bake/FamilyBaker.cs +++ b/src/Bilocus.Revit/Bake/FamilyBaker.cs @@ -712,6 +712,10 @@ private ObjectWrite CreateFamily( { ProxySchema.Mark(created[i], built[i].ObjectId); } + + // The host's BL_ parameters: with Bake together the + // members are often LODs, their values do not add up. + FamilyParameters.Apply(familyDoc, host.Parameters, familyName); return null; }); if (refusal != null) { return ObjectWrite.Refused(refusal); } @@ -850,6 +854,9 @@ private ObjectWrite UpdateFamily(BakeMeshRequest host, List built, // what the user added in the editor has no mark. removedMembers = RemoveOtherMembers(familyDoc, requested); + // Added, updated, and the stale BL_ ones removed. + FamilyParameters.Apply(familyDoc, host.Parameters, familyName); + // For a family the category is changed in place: it // is always replaced, never recreated (contract). if (familyDoc.OwnerFamily.FamilyCategoryId != category.Id) @@ -881,6 +888,10 @@ private ObjectWrite UpdateFamily(BakeMeshRequest host, List built, string renameNote = null; string instanceRefusal = TryInTransaction(_project, ObjectTransactionPrefix + host.Name, () => { + // The reload above keeps the project's type values on + // purpose: the BL_ ones are written here, and only them. + FamilyParameters.WriteToTypes(_project, target, host.Parameters); + List instances = MarkedInstancesOf(target.Id, host.ObjectId); if (instances.Count == 1) diff --git a/src/Bilocus.Revit/Bake/FamilyParameters.cs b/src/Bilocus.Revit/Bake/FamilyParameters.cs new file mode 100644 index 0000000..dbc6978 --- /dev/null +++ b/src/Bilocus.Revit/Bake/FamilyParameters.cs @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Roberto Dolfini + +using System.Collections.Generic; +using Autodesk.Revit.DB; + +namespace Bilocus.Revit.Bake +{ + // Writes the BL_ parameters of a bake: type parameters of the family, + // group Dimensions, informative values that do not drive the geometry. + // Parameters without the BL_ prefix are never touched; BL_ parameters + // that did not arrive are deleted, because stale data is worse than + // missing data (an override cleared, a mesh that opened). + public static class FamilyParameters + { + // Inside an open transaction on the family document. + public static void Apply(Document familyDoc, IList parameters, string typeName) + { + FamilyManager manager = familyDoc.FamilyManager; + EnsureCurrentType(manager, typeName); + + Dictionary wanted = new Dictionary(); + foreach (BakeParameter p in parameters) { wanted[p.Name] = p; } + + // A copy: removing while iterating manager.Parameters would + // invalidate the iterator. + List existing = new List(); + foreach (FamilyParameter fp in manager.Parameters) { existing.Add(fp); } + + foreach (FamilyParameter fp in existing) + { + string name = fp.Definition.Name; + if (!name.StartsWith(BakeParameter.Prefix, System.StringComparison.Ordinal)) { continue; } + + // Also removed when it no longer has the shape it is + // written with: added again right below. + BakeParameter p; + if (!wanted.TryGetValue(name, out p) || fp.IsInstance + || fp.Definition.GetDataType() != SpecOf(p.Kind)) + { + manager.RemoveParameter(fp); + } + } + + foreach (BakeParameter p in parameters) + { + FamilyParameter fp = manager.get_Parameter(p.Name); + if (fp == null) + { + fp = manager.AddParameter(p.Name, GroupTypeId.Geometry, SpecOf(p.Kind), false); + } + manager.Set(fp, ToInternal(p)); + } + } + + // Inside an open transaction on the project. The re-bake reloads + // with overwriteParameterValues false, so the user's own values on + // the project types stay: the BL_ values are written here, and only + // those, on every type of the family (they describe the geometry, + // which is the same for all of them). + public static void WriteToTypes(Document project, Family family, IList parameters) + { + foreach (ElementId id in family.GetFamilySymbolIds()) + { + FamilySymbol symbol = project.GetElement(id) as FamilySymbol; + if (symbol == null) { continue; } + foreach (BakeParameter p in parameters) + { + Parameter parameter = symbol.LookupParameter(p.Name); + if (parameter != null && !parameter.IsReadOnly) { parameter.Set(ToInternal(p)); } + } + } + } + + // A type is needed to hold values. A template may come without + // one; a family opened with EditFamily has its types but may not + // have one current. Creating a type when one exists would load a + // second type into the project. + private static void EnsureCurrentType(FamilyManager manager, string typeName) + { + if (manager.CurrentType != null) { return; } + foreach (FamilyType type in manager.Types) + { + manager.CurrentType = type; + return; + } + manager.NewType(typeName); + } + + private static ForgeTypeId SpecOf(string kind) + { + if (kind == "area") { return SpecTypeId.Area; } + if (kind == "volume") { return SpecTypeId.Volume; } + return SpecTypeId.Length; + } + + private static double ToInternal(BakeParameter p) + { + ForgeTypeId unit = p.Kind == "area" ? UnitTypeId.SquareMeters + : p.Kind == "volume" ? UnitTypeId.CubicMeters : UnitTypeId.Meters; + return UnitUtils.ConvertToInternalUnits(p.Value, unit); + } + } +} From f9b8c82b5fefb1de6f4895af1c53dd521eaac0d5 Mon Sep 17 00:00:00 2001 From: Roberto Dolfini Date: Mon, 12 Oct 2026 19:34:40 +0200 Subject: [PATCH 7/8] Docs: family dimension parameters --- CHANGELOG.md | 9 +++++++++ DESIGN.md | 19 ++++++++++++++++++- README.md | 5 +++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 16b2703..c58749a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## Unreleased + +- New: **family dimension parameters.** A family baked from Blender carries + `BL_Length`, `BL_Width`, `BL_Height`, `BL_Area` and `BL_Volume` (closed + meshes only) as type parameters, plus `BL_Thickness` when set. Values come + from the object's extent and can be set by hand from an edge or face + selection in the panel, except the volume. Informative only: they do not + drive the geometry and are rewritten at every bake. + ## 0.2.0 - 2026-10-10 - New: **Revit 2026 and 2027.** One zip per Revit version, 2024 to 2027. diff --git a/DESIGN.md b/DESIGN.md index ef804a6..ac586a5 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -179,7 +179,7 @@ failure would have to be treated as terminal. | `preview_style` | `{type, face, edge}` | - | | `proxy_edges` | `{type, obj_id, name, edge_count, arc_count?}` | `edge_count * 6` float32: two endpoints per edge, x y z each; then `arc_count * 9` float32: start, end, mid-angle point per arc | | `bake_begin` | `{type, obj_ids, target, host?}` | - | -| `bake_mesh` | `{type, obj_id, name, category, matrix, vert_count, face_count, loop_count, tri_count, accept_open, smooth_mesh?}` | positions (vert_count*3 f32) + face_sizes (face_count u32) + face_vertices (loop_count u32) + tri_vertices (tri_count*3 u32) + tri_faces (tri_count u32) | +| `bake_mesh` | `{type, obj_id, name, category, matrix, vert_count, face_count, loop_count, tri_count, accept_open, smooth_mesh?, params?}` | positions (vert_count*3 f32) + face_sizes (face_count u32) + face_vertices (loop_count u32) + tri_vertices (tri_count*3 u32) + tri_faces (tri_count u32) | | `bake_end` | `{type}` | - | | `bake_remove` | `{type, obj_ids}` | - | @@ -433,6 +433,23 @@ a Sheet (an open mesh already stitched), the polygons that are not exactly planar fall back to their triangles and the builder runs again; the retry is kept if it gives a Solid or a Sheet. Same path for the family bake. +**Family dimension parameters.** `params` on `bake_mesh` (absent = none) +is an array of `{name, kind, value}`: `name` is `BL_` followed by letters, +`kind` one of `length`, `area`, `volume`, `value` a finite number >= 0 in +SI units (m, m2, m3). Blender sends `BL_Length` and `BL_Width` (the larger +and smaller of `obj.dimensions` X and Y), `BL_Height` (Z), `BL_Area` (total +surface of the evaluated mesh), `BL_Volume` (only for a closed mesh, never +overridden) and `BL_Thickness` (only when set by hand); every value but the +volume can be set by hand from an edge or face selection, stored frozen on +the object. Only the family bake uses them, and with Bake together only the +host's. Revit writes them as type parameters, group Dimensions, converted +to internal units; it deletes the `BL_` parameters that did not arrive and +never touches parameters without the prefix. The re-bake reloads with +`overwriteParameterValues = false`, so the `BL_` values are also written +on the family's types in the project after the load. The values are +informative: they do not drive the geometry. A malformed `params` is an +`error` for that object. + **Smooth mesh, per object.** `smooth_mesh` on `bake_mesh` (absent = false) asks the DirectShape bake for a mesh from the start: target `Mesh`, fallback `Salvage`, no retry. Revit draws a mesh DirectShape diff --git a/README.md b/README.md index 8bf2974..df9c575 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,11 @@ endorsed by Autodesk or the Blender Foundation. replaces the previous version; **Remove Bake** deletes what Bilocus created. A DirectShape can also arrive as a smooth mesh instead of a solid: see [Smooth meshes or true solids](#smooth-meshes-or-true-solids). + A family also carries `BL_` type parameters (length, width, height, area, + volume, and thickness when set): rough values from the object's extent, + each one but the volume can be set from an edge or face selection in the + panel. They are informative, not linked to the geometry, and rewritten at + every bake. ![A geometry nodes pavilion synced, then baked together into one family](docs/media/geomnodes-sync-blender.gif) From 09188eb9d7293b85140438a789ae1f22e4dd0a97 Mon Sep 17 00:00:00 2001 From: Roberto Dolfini Date: Thu, 22 Oct 2026 15:46:10 +0200 Subject: [PATCH 8/8] Fix smoke_bake panel fakes for the family parameters box FakeLayout.operator() returned None, while the real UILayout returns the operator properties, so op.key = key in the new parameters box crashed. It now returns an object that accepts only the operator's declared properties. Section order checks look at top-level boxes and at the bake section's own level; the nested parameters box gets its own check. Co-Authored-By: Claude Opus 5.5 --- tests/blender/smoke_bake.py | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/tests/blender/smoke_bake.py b/tests/blender/smoke_bake.py index ff7e6de..bf45a84 100644 --- a/tests/blender/smoke_bake.py +++ b/tests/blender/smoke_bake.py @@ -310,6 +310,22 @@ def disable_addon(module, installed): # --- panel drawn on a fake layout ----------------------------------------------- +class FakeOperatorProperties(object): + """What layout.operator() returns: setting a property the operator does + not declare raises in real Blender, so it fails here too.""" + + def __init__(self, idname): + prefix, name = idname.split(".") + rna = getattr(getattr(bpy.ops, prefix), name).get_rna_type() + object.__setattr__(self, "_idname", idname) + object.__setattr__(self, "_names", set(rna.properties.keys())) + + def __setattr__(self, name, value): + if name not in self._names: + raise AssertionError("{} has no property {}".format(self._idname, name)) + object.__setattr__(self, name, value) + + class FakeLayout(object): """Records what draw() asks the layout for, and rejects what would make the whole panel disappear in real Blender: a non-existent icon, an @@ -365,6 +381,7 @@ def operator(self, idname, text=None, icon='NONE', **_kwargs): if icon != 'NONE': shown = "{} [{}]".format(shown, icon) self.lines.append((self.depth, "operator", shown, self._active())) + return FakeOperatorProperties(idname) def prop(self, data, prop, text=None, **_kwargs): if not hasattr(data, prop): @@ -384,7 +401,9 @@ def draw_panel(): def box_titles(lines): - return [lines[i + 1][2] for i in range(len(lines) - 1) if lines[i][1] == "box"] + # top-level sections only: a box nested in a section is part of it + return [lines[i + 1][2] for i in range(len(lines) - 1) + if lines[i][1] == "box" and lines[i][0] == 0] def bake_section(lines): @@ -644,7 +663,14 @@ def test_end_to_end(scene, collection, sample, addon_module): "panel: category of the active object") check(operator_active(lines, "bilocus.bake_family"), "panel: Family Bake active under the same conditions") - order = [line[2] for line in section if line[1] in ("prop", "operator")] + # the family parameters box is nested one level down, checked on its own + depth = section[0][0] + pickers = [line for line in section if line[0] > depth + and line[1] == "operator" and "bilocus.set_bake_param" in line[2]] + check(len(pickers) == len(sys.modules["bridge_params"].OVERRIDABLE), + "panel: one picker per overridable family parameter ({})".format(len(pickers))) + order = [line[2] for line in section + if line[0] == depth and line[1] in ("prop", "operator")] expected_order = ["Category = OST_Walls", "Accept open solid = False", "Smooth mesh (no volume) = False", "[Apply to Selected] bilocus.apply_bake_category",