Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@
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.
drive the geometry and are rewritten at every bake. A value set by hand
is flagged in the panel, and in the bake message, once the object's
dimensions change: it is still sent until you set it again or clear it.
A `BL_` parameter you use in a formula in the family editor is kept even
when it is no longer sent, and one you give a formula is not overwritten.

## 0.2.0 - 2026-10-10

Expand Down
25 changes: 25 additions & 0 deletions src/Bilocus.Revit/Bake/BakeParameter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,30 @@ public static BakeParameter Create(string name, string kind, double value)
}
return new BakeParameter(name, kind, value);
}

// Whether a family parameter formula refers to the parameter named
// name. Whole names only: BL_ names are letters after the prefix, so
// a letter, digit or underscore next to a match means a longer name.
public static bool IsUsedIn(string name, string formula)
{
if (string.IsNullOrEmpty(formula)) { return false; }
int at = formula.IndexOf(name, StringComparison.Ordinal);
while (at >= 0)
{
int end = at + name.Length;
if ((at == 0 || !IsNameChar(formula[at - 1]))
&& (end == formula.Length || !IsNameChar(formula[end])))
{
return true;
}
at = formula.IndexOf(name, at + 1, StringComparison.Ordinal);
}
return false;
}

private static bool IsNameChar(char c)
{
return char.IsLetterOrDigit(c) || c == '_';
}
}
}
13 changes: 9 additions & 4 deletions src/Bilocus.Revit/Bake/FamilyBaker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -715,7 +715,8 @@ private ObjectWrite CreateFamily(

// 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);
// A fresh family has no formulas: nothing is left out.
FamilyParameters.Apply(familyDoc, host.Parameters, familyName, out _);
return null;
});
if (refusal != null) { return ObjectWrite.Refused(refusal); }
Expand Down Expand Up @@ -826,6 +827,8 @@ private ObjectWrite UpdateFamily(BakeMeshRequest host, List<MemberSolid> built,

Family loaded;
int removedMembers = 0;
List<BakeParameter> written = new List<BakeParameter>();
string paramsNote = null;
try
{
string refusal = InTransaction(familyDoc, FamilyTransactionName, () =>
Expand Down Expand Up @@ -855,7 +858,7 @@ private ObjectWrite UpdateFamily(BakeMeshRequest host, List<MemberSolid> built,
removedMembers = RemoveOtherMembers(familyDoc, requested);

// Added, updated, and the stale BL_ ones removed.
FamilyParameters.Apply(familyDoc, host.Parameters, familyName);
written = FamilyParameters.Apply(familyDoc, host.Parameters, familyName, out paramsNote);

// For a family the category is changed in place: it
// is always replaced, never recreated (contract).
Expand Down Expand Up @@ -890,7 +893,7 @@ private ObjectWrite UpdateFamily(BakeMeshRequest host, List<MemberSolid> built,
{
// 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);
FamilyParameters.WriteToTypes(_project, target, written);

List<ElementId> instances = MarkedInstancesOf(target.Id, host.ObjectId);

Expand Down Expand Up @@ -930,7 +933,9 @@ private ObjectWrite UpdateFamily(BakeMeshRequest host, List<MemberSolid> built,
+ " reloaded, but instance not updated: " + instanceRefusal);
}

return ObjectWrite.Done(false, switched, notMoved, renameNote, target.Name, removedMembers);
string note = paramsNote == null ? renameNote
: (renameNote == null ? "" : renameNote + "; ") + "family " + target.Name + ": " + paramsNote;
return ObjectWrite.Done(false, switched, notMoved, note, target.Name, removedMembers);
}

// The bridge's FreeFormElements marked with an obj_id that is not
Expand Down
51 changes: 48 additions & 3 deletions src/Bilocus.Revit/Bake/FamilyParameters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,17 @@ namespace Bilocus.Revit.Bake
// 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<BakeParameter> parameters, string typeName)
// Inside an open transaction on the family document. Returns the
// parameters actually written; note says which BL_ ones were left
// alone, or is null.
//
// The user may build on a BL_ parameter in the family editor. One
// used in another parameter's formula is never removed or re-typed:
// RemoveParameter does not throw, it silently empties that formula
// (Revit 2025, checked live). One with a formula of its own is the
// user's choice and is not overwritten.
public static List<BakeParameter> Apply(Document familyDoc, IList<BakeParameter> parameters,
string typeName, out string note)
{
FamilyManager manager = familyDoc.FamilyManager;
EnsureCurrentType(manager, typeName);
Expand All @@ -27,6 +36,8 @@ public static void Apply(Document familyDoc, IList<BakeParameter> parameters, st
List<FamilyParameter> existing = new List<FamilyParameter>();
foreach (FamilyParameter fp in manager.Parameters) { existing.Add(fp); }

List<string> left = new List<string>();
HashSet<string> keptAsIs = new HashSet<string>();
foreach (FamilyParameter fp in existing)
{
string name = fp.Definition.Name;
Expand All @@ -38,26 +49,60 @@ public static void Apply(Document familyDoc, IList<BakeParameter> parameters, st
if (!wanted.TryGetValue(name, out p) || fp.IsInstance
|| fp.Definition.GetDataType() != SpecOf(p.Kind))
{
string user = FormulaUsing(existing, fp);
if (user != null)
{
keptAsIs.Add(name);
left.Add(name + " kept, used in the formula of " + user);
continue;
}
manager.RemoveParameter(fp);
}
}

List<BakeParameter> written = new List<BakeParameter>();
foreach (BakeParameter p in parameters)
{
if (keptAsIs.Contains(p.Name)) { continue; }
FamilyParameter fp = manager.get_Parameter(p.Name);
if (fp == null)
{
fp = manager.AddParameter(p.Name, GroupTypeId.Geometry, SpecOf(p.Kind), false);
}
else if (!string.IsNullOrEmpty(fp.Formula))
{
// IsDeterminedByFormula reads false here (Revit 2025,
// checked live), and Set would be accepted and ignored:
// the formula text is what tells.
left.Add(p.Name + " not written, it has a formula");
continue;
}
manager.Set(fp, ToInternal(p));
written.Add(p);
}

note = left.Count == 0 ? null : string.Join(", ", left);
return written;
}

// The name of another parameter whose formula uses fp, or null.
private static string FormulaUsing(IList<FamilyParameter> all, FamilyParameter fp)
{
string name = fp.Definition.Name;
foreach (FamilyParameter other in all)
{
if (other.Id == fp.Id) { continue; }
if (BakeParameter.IsUsedIn(name, other.Formula)) { return other.Definition.Name; }
}
return null;
}

// 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).
// which is the same for all of them). Pass what Apply wrote: a BL_
// left alone in the family must be left alone here too.
public static void WriteToTypes(Document project, Family family, IList<BakeParameter> parameters)
{
foreach (ElementId id in family.GetFamilySymbolIds())
Expand Down
56 changes: 55 additions & 1 deletion src/blender_addon/bridge_bake_send.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,11 @@ def bake_selected(context=None, target="directshape", together=False):
notes.append("NOT sent: {}".format("; ".join(failed[:3])))
if warned:
notes.append("heavy: {}".format("; ".join(warned[:3])))
if family:
changed = [obj.name for obj, _obj_id in announced if changed_overrides(obj)]
if changed:
notes.append("BL_ values set by hand before the object changed: {}".format(
"; ".join(changed[:3])))

if sent == 0:
# bake_end went out anyway: Revit will reply with ok false and all
Expand All @@ -475,8 +480,57 @@ def bake_selected(context=None, target="directshape", together=False):

# 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.
# the mesh changes. Next to each, bilocus_param_length_dims holds the
# object's dimensions when it was set, so a value left behind by a reshape
# can be flagged. Shift+D copies both: the copy starts with the same shape,
# so its values are right until it is edited, like the original's.
OVERRIDE_PREFIX = "bilocus_param_"
DIMS_SUFFIX = "_dims"


def set_override(obj, key, value, depsgraph):
obj[OVERRIDE_PREFIX + key] = value
obj[OVERRIDE_PREFIX + key + DIMS_SUFFIX] = list(evaluated_dimensions(obj, depsgraph))


def evaluated_dimensions(obj, depsgraph):
"""What obj.dimensions reads in Object Mode, computed from the evaluated
mesh. Values are set by hand in Edit Mode, where Blender 4.2 and 4.5
do not update obj.dimensions after a reshape (5.x does): recording it
there flagged the value as soon as the user left Edit Mode."""
evaluated = obj.evaluated_get(depsgraph)
mesh_data = evaluated.to_mesh()
try:
count = len(mesh_data.vertices)
if count == 0:
return tuple(obj.dimensions)
co = [0.0] * (3 * count)
mesh_data.vertices.foreach_get("co", co)
finally:
evaluated.to_mesh_clear()
scale = obj.matrix_world.to_scale()
return tuple((max(co[axis::3]) - min(co[axis::3])) * abs(scale[axis]) for axis in range(3))


def clear_override(obj, key):
for name in (OVERRIDE_PREFIX + key, OVERRIDE_PREFIX + key + DIMS_SUFFIX):
if name in obj:
del obj[name]


def changed_overrides(obj):
"""The keys of the values set by hand while the object had other
dimensions than now. None in Edit Mode: obj.dimensions is not kept up
to date there on Blender 4.x, the flag shows on leaving it."""
if obj.mode == 'EDIT':
return []
result = []
for key in overrides_of(obj):
recorded = obj.get(OVERRIDE_PREFIX + key + DIMS_SUFFIX)
recorded = None if recorded is None else tuple(recorded)
if params_logic.changed_since(tuple(obj.dimensions), recorded):
result.append(key)
return result


def measure(obj, depsgraph):
Expand Down
12 changes: 12 additions & 0 deletions src/blender_addon/bridge_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,15 @@ def build_params(dimensions, area, volume, overrides):
raise BridgeFramingError("{}: {} is not a valid measure".format(name, value))
result.append({"name": name, "kind": kind, "value": round(value, 6)})
return result


def changed_since(dimensions, recorded):
"""True if the object's dimensions are no longer those recorded when a
value was set by hand: the value may describe a shape that is gone.
recorded None, or malformed, means a value set before the dimensions
were recorded: unknown, so not flagged. The tolerance absorbs the
float32 noise of obj.dimensions, about 0.1 mm per meter."""
if recorded is None or len(recorded) != 3:
return False
return any(not math.isclose(float(now), float(then), rel_tol=1e-4, abs_tol=1e-6)
for now, then in zip(dimensions, recorded))
14 changes: 10 additions & 4 deletions src/blender_addon/panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def execute(self, context):
if problem is not None:
self.report({'ERROR'}, problem)
return {'CANCELLED'}
obj[bake.OVERRIDE_PREFIX + self.key] = value
bake.set_override(obj, self.key, value, context.evaluated_depsgraph_get())
self.report({'INFO'}, "{}: {:.4f}".format(self.key, value))
return {'FINISHED'}

Expand All @@ -138,8 +138,8 @@ class BILOCUS_OT_clear_bake_param(bpy.types.Operator):

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]
if obj is not None:
bake.clear_override(obj, self.key)
return {'FINISHED'}


Expand Down Expand Up @@ -496,10 +496,12 @@ def _draw_family_params(layout, target):
box = layout.box()
box.label(text="Family parameters (informative)")
overrides = bake.overrides_of(target)
changed = bake.changed_overrides(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)
icon = 'NONE'
if source == "none" and key in ("area", "volume"):
text = "{}: computed at bake".format(name)
if key == "volume":
Expand All @@ -509,7 +511,11 @@ def _draw_family_params(layout, target):
else:
unit = "m2" if key == "area" else "m"
text = "{}: {:.3f} {} ({})".format(name, value, unit, source)
row.label(text=text)
if key in changed:
# still sent: the user decides, with the picker or the X
text = "{}: {:.3f} {} (set, object changed)".format(name, value, unit)
icon = 'ERROR'
row.label(text=text, icon=icon)
if key in params_logic.OVERRIDABLE:
op = row.operator("bilocus.set_bake_param", text="", icon='EYEDROPPER')
op.key = key
Expand Down
16 changes: 16 additions & 0 deletions tests/Bilocus.Revit.Net.Tests/BakeParameterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,21 @@ public void Create_AcceptsZero()
{
Assert.Equal(0.0, BakeParameter.Create("BL_Thickness", "length", 0.0).Value);
}

[Theory]
[InlineData("BL_Length * 2", true)]
[InlineData("if(BL_Length > 1 m, 1, 0)", true)]
[InlineData("BL_Width+BL_Length", true)]
[InlineData("(BL_Length)", true)]
[InlineData("BL_LengthTotal / 2", false)]
[InlineData("MyBL_Length * 2", false)]
[InlineData("BL_Length2 * 2", false)]
[InlineData("bl_length * 2", false)]
[InlineData("", false)]
[InlineData(null, false)]
public void IsUsedIn_MatchesWholeNamesOnly(string formula, bool expected)
{
Assert.Equal(expected, BakeParameter.IsUsedIn("BL_Length", formula));
}
}
}
Loading
Loading