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
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
# Changelog

## Unreleased

- New: **host collection in the pull.** In a model with linked models, the
host's own elements arrive in `FromRevit/HostModel - <file name>`, next to
the `LinkModel` collections. Elements already pulled move there only from
the `FromRevit` root; a model without links keeps everything in
`FromRevit`.
- Fixed: Blender sends nothing until Revit answers the handshake. A second
Blender waits on *waiting for Revit* instead of freezing on Sync, and a
protocol mismatch disconnects.
- Fixed: a dropped connection redraws the panel and marks a bake or proxy
still waiting as lost.
- Fixed: Bake together keeps the previous geometry of a member that fails,
and the Revit Status note now shows in the Blender panel.
- Fixed: a `BL_` parameter with a formula of its own is no longer removed.
- Fixed: a Blender that stops reading can no longer freeze Revit on a send.

## 0.3.0 - 2026-10-29

- New: **linked models in the pull.** Select a Revit link and press Send
Expand Down
12 changes: 11 additions & 1 deletion DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ object in Blender deletes nothing in Revit.
| type | header | payload |
|---|---|---|
| `hello_ack` | `{type, protocol_version, revit_version, doc_title}` | - |
| `revit_batch_begin` | `{type, count}` | - |
| `revit_batch_begin` | `{type, count, [host_name]}` | - |
| `revit_geometry` | `{type, element_id, name, category, type_name, vert_count, tri_count, origin, color, [link_id, link_name]}` | positions (vert_count*3 f32) + normals (vert_count*3 f32) + indices (tri_count*3 u32) |
| `revit_mesh` | `{type, mesh_key, vert_count, tri_count}` | positions + normals + indices, same as `revit_geometry` |
| `revit_instance` | `{type, element_id, name, category, type_name, mesh_key, matrix, color, [link_id, link_name]}` | - |
Expand Down Expand Up @@ -747,6 +747,16 @@ model). Edits to those objects are lost on the next pull of the same link.
`revit_mesh` and `revit_instance` arriving without a `revit_batch_begin`
open an implicit batch, like `revit_geometry`.

`revit_batch_begin` carries `host_name`, the host document's title, when
that document contains at least one `RevitLinkInstance`, whatever is
selected: the same file always lands in the same place. The host's own
elements then go into `FromRevit/HostModel - <host_name>`, next to the
`LinkModel` ones. New objects are created there; an existing one moves there
only from the `FromRevit` root, so a collection the user chose is kept.
Without `host_name` (no links, or an older add-in) they stay in `FromRevit`.
Unlike a link, the host sub-collection is never emptied: its elements keep
the in-place update.

#### `bake_result`

The response to `bake_end` (`action` = `"bake"`) and to `bake_remove`
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ endorsed by Autodesk or the Blender Foundation.
with openings in the right place. Sending again updates them in place.
Select a Revit link and the whole linked model comes along, in
`FromRevit/LinkModel - <link name>`, replaced on every send (heavy on big
models). Every mesh arrives with a `UVMap` in real meters, ready for
models). In a model with links, the host's own elements go to
`FromRevit/HostModel - <file name>`. Every mesh arrives with a `UVMap` in real meters, ready for
textures and for Unreal's lightmap UVs (**Metric UVs** in the panel, on by
default).

Expand Down
10 changes: 9 additions & 1 deletion src/Bilocus.Revit/Net/MessageRouter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -555,7 +555,11 @@ public static string BuildError(string message)
// backslashes, non-ASCII characters: Utf8JsonWriter writes them
// correctly, a hand-rolled string.Format does not.

public static string BuildBatchBegin(int count)
// hostName non-null: the document has linked models, and the Blender
// side puts the host's own elements in FromRevit/HostModel - <name>,
// next to the LinkModel ones. Absent when there are no links: then
// everything stays in FromRevit, as before.
public static string BuildBatchBegin(int count, string hostName = null)
{
using (MemoryStream buffer = new MemoryStream())
{
Expand All @@ -564,6 +568,10 @@ public static string BuildBatchBegin(int count)
writer.WriteStartObject();
writer.WriteString("type", "revit_batch_begin");
writer.WriteNumber("count", count);
if (!string.IsNullOrEmpty(hostName))
{
writer.WriteString("host_name", hostName);
}
writer.WriteEndObject();
}
return Encoding.UTF8.GetString(buffer.ToArray());
Expand Down
18 changes: 15 additions & 3 deletions src/Bilocus.Revit/Pull/SendSelectionCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public Result Execute(ExternalCommandData commandData, ref string message, Eleme
}

long sendStart = Stopwatch.GetTimestamp();
SendBatch(server, ready, sharedMeshes, result);
SendBatch(server, ready, sharedMeshes, result, HostNameIfLinked(doc));
result.SendMs = ElapsedMs(sendStart);

TaskDialog.Show("Bilocus", result.BuildSummaryText());
Expand Down Expand Up @@ -217,11 +217,23 @@ private static void AddElement(
}
}

// The document's name when it has at least one linked model, else
// null. Decided on the model and not on the selection: the same file
// always lands in the same Blender collection, whatever is selected.
private static string HostNameIfLinked(Document doc)
{
bool hasLinks = new FilteredElementCollector(doc)
.OfClass(typeof(RevitLinkInstance))
.FirstElementId() != ElementId.InvalidElementId;
return hasLinks ? doc.Title : null;
}

private static void SendBatch(
BridgeServer server, List<PendingElement> ready,
Dictionary<string, TessellatedMesh> sharedMeshes, SendSelectionResult result)
Dictionary<string, TessellatedMesh> sharedMeshes, SendSelectionResult result,
string hostName)
{
string beginHeader = MessageRouter.BuildBatchBegin(ready.Count);
string beginHeader = MessageRouter.BuildBatchBegin(ready.Count, hostName);
if (!server.Send(new Frame(beginHeader, null)))
{
result.Aborted = true;
Expand Down
47 changes: 37 additions & 10 deletions src/blender_addon/bridge_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@
# Sub-collection of FromRevit holding the objects of one linked model.
LINK_COLLECTION_PREFIX = "LinkModel - "

# Sub-collection of FromRevit holding the host model's own elements. Used
# only when the host has linked models, so the two sit side by side.
HOST_COLLECTION_PREFIX = "HostModel - "

# Custom properties linking the Blender object to the Revit element. The
# first one is also the key used to find the object again on the next pull:
# it is a string, for the reason written in receive.element_id_key.
Expand Down Expand Up @@ -355,7 +359,7 @@ def import_geometry(fields, positions, indices, scene=None):
overwritten = False
if created:
obj = bpy.data.objects.new(fields["name"], mesh_data)
ensure_collection(scene).objects.link(obj)
_place_host_object(obj, scene)
# The object's origin ends up ON THE ELEMENT, not at (0,0,0): that
# is the whole point of the fix. A wall thirty meters from the
# scene origin, with the object's origin at zero, rotated fifteen
Expand Down Expand Up @@ -406,6 +410,7 @@ def import_geometry(fields, positions, indices, scene=None):
del obj[MESH_KEY_PROPERTY]

obj.name = fields["name"]
_place_host_object(obj, scene)

_write_properties(obj, fields)
return created, overwritten
Expand All @@ -430,7 +435,6 @@ def import_instance(fields, scene=None):
try:
if not exists:
obj = bpy.data.objects.new(fields["name"], mesh)
ensure_collection(scene).objects.link(obj)
elif replace_mesh and obj.data != mesh:
old_mesh = obj.data
# A fresh mesh inherits the material slots of the one it replaces:
Expand All @@ -448,6 +452,7 @@ def import_instance(fields, scene=None):

if exists:
obj.name = fields["name"]
_place_host_object(obj, scene)
_write_properties(obj, fields)
obj[MESH_KEY_PROPERTY] = fields["mesh_key"]
except Exception:
Expand All @@ -471,22 +476,43 @@ def _link_collection(link, now, scene):
pull of the same link, by design."""
name = LINK_COLLECTION_PREFIX + link
meshes, first = LAST_PULL.link_meshes(name, now)
collection = _sub_collection(name, scene)

if first:
for obj in list(collection.objects):
data = obj.data
bpy.data.objects.remove(obj)
if isinstance(data, bpy.types.Mesh):
_remove_if_orphan(data)
return collection, meshes


def _sub_collection(name, scene):
"""A collection under FromRevit, created when missing."""
collection = bpy.data.collections.get(name)
if collection is None:
collection = bpy.data.collections.new(name)
# Same check as ensure_collection: the user may have moved it elsewhere
# in the scene, and linking it twice raises RuntimeError.
if collection not in scene.collection.children_recursive:
ensure_collection(scene).children.link(collection)
return collection

if first:
for obj in list(collection.objects):
data = obj.data
bpy.data.objects.remove(obj)
if isinstance(data, bpy.types.Mesh):
_remove_if_orphan(data)
return collection, meshes

def _place_host_object(obj, scene):
"""Puts a host element where the pull wants it: FromRevit, or its
HostModel sub-collection when the host has links. A new object is
linked there; an existing one moves only if it sits in the FromRevit
root, where the pull left it: a collection the user chose is kept."""
root = ensure_collection(scene)
target = root
if LAST_PULL.host is not None:
target = _sub_collection(HOST_COLLECTION_PREFIX + LAST_PULL.host, scene)
if not obj.users_collection:
target.objects.link(obj)
elif target is not root and root in obj.users_collection:
target.objects.link(obj)
root.objects.unlink(obj)


def import_link(fields, positions, indices, now, scene=None):
Expand Down Expand Up @@ -592,7 +618,8 @@ def handle_instance(header, payload, now, scene=None):

def handle_batch_begin(header, now):
"""A revit_batch_begin message. Returns a note to print, or None."""
note = LAST_PULL.begin(receive.read_batch_count(header), now)
note = LAST_PULL.begin(receive.read_batch_count(header), now,
receive.read_batch_host(header))
if note is None:
return None
return "batch opened without closing the previous one ({})".format(note)
Expand Down
16 changes: 15 additions & 1 deletion src/blender_addon/bridge_receive.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,16 @@ def read_batch_count(header):
return value


def read_batch_host(header):
"""The host_name of revit_batch_begin, or None when absent: Revit
writes it only for a model with linked models. Anything that is not a
non-empty string counts as absent, the objects then go to FromRevit."""
value = header.get("host_name")
if not isinstance(value, str) or not value:
return None
return value


# --- draining the incoming queue -----------------------------------------
#
# The drain runs on Blender's main thread: while it works, nothing redraws
Expand Down Expand Up @@ -490,9 +500,12 @@ def _clear(self):
# Link sub-collections already emptied in this batch, by name, each
# with the meshes built for it: {mesh_key: mesh name} (bridge_import).
self.links = {}
# Name of the host model when it has links (revit_batch_begin
# host_name), else None: its elements go to FromRevit itself.
self.host = None
self.last_activity = 0.0

def begin(self, count, now):
def begin(self, count, now, host=None):
"""Opens a batch. If one was left open, returns the reason for its
closure, otherwise None."""
note = None
Expand All @@ -501,6 +514,7 @@ def begin(self, count, now):
self._clear()
self.open = True
self.expected = count
self.host = host
self.last_activity = now
self.message = self._progress()
return note
Expand Down
10 changes: 10 additions & 0 deletions tests/Bilocus.Revit.Net.Tests/SendSelectionMessagesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,16 @@ public void BuildBatchBegin_HasTypeAndCount()
Assert.Equal(7, root.GetProperty("count").GetInt32());
}

[Fact]
public void BuildBatchBegin_HostNameOnlyWhenGiven()
{
JsonElement without = JsonDocument.Parse(MessageRouter.BuildBatchBegin(3)).RootElement;
Assert.False(without.TryGetProperty("host_name", out _));

JsonElement with = JsonDocument.Parse(MessageRouter.BuildBatchBegin(3, "Progetto_ARC")).RootElement;
Assert.Equal("Progetto_ARC", with.GetProperty("host_name").GetString());
}

[Fact]
public void BuildBatchEnd_HasOnlyType()
{
Expand Down
34 changes: 32 additions & 2 deletions tests/blender/smoke_pull.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,11 @@ def pulled(element_id):
return imp.find_object(str(element_id))


def batch(count, now=0.0):
imp.handle_batch_begin({"type": "revit_batch_begin", "count": count}, now)
def batch(count, now=0.0, host=None):
header = {"type": "revit_batch_begin", "count": count}
if host is not None:
header["host_name"] = host
imp.handle_batch_begin(header, now)


def end(now=0.0):
Expand Down Expand Up @@ -235,6 +238,33 @@ def main():
"checkbox off: flat and instance meshes arrive without UVs")
setattr(scene, imp.UVS_PROPERTY, True)

# 11. a host with links: its elements go to HostModel - <name>; one
# still in the FromRevit root moves there, one the user moved stays
root = imp.ensure_collection(scene)
elsewhere = bpy.data.collections.new("UserPlaced")
scene.collection.children.link(elsewhere)
root.objects.unlink(pulled(93))
elsewhere.objects.link(pulled(93))
batch(4, host="Progetto_ARC")
send_flat(90, (0.0, 0.0, 0.0))
send_flat(93, (0.0, 90.0, 0.0))
send_flat(95, (0.0, 120.0, 0.0))
send_mesh("K9", scale=2.0)
send_instance(91, "K9", matrix(tx=30.0))
end()
host = bpy.data.collections.get(imp.HOST_COLLECTION_PREFIX + "Progetto_ARC")
check(host is not None and host.name in root.children, "HostModel collection created under FromRevit")
check(pulled(95).users_collection[:] == (host,), "new host element in HostModel")
check(pulled(90).users_collection[:] == (host,) and pulled(91).users_collection[:] == (host,),
"flat and instance moved from the FromRevit root to HostModel")
check(pulled(93).users_collection[:] == (elsewhere,), "element placed by the user left where it is")

# 12. no links: new host elements stay in the FromRevit root
batch(1)
send_flat(96, (0.0, 150.0, 0.0))
end()
check(pulled(96).users_collection[:] == (root,), "no host_name: new element in FromRevit")

imp.unregister_properties()


Expand Down
21 changes: 21 additions & 0 deletions tests/python/test_bridge_receive.py
Original file line number Diff line number Diff line change
Expand Up @@ -972,3 +972,24 @@ def test_drain_handles_at_least_one_message_even_with_no_budget():
seen = []
assert not bridge_receive.drain(q, lambda h, p: seen.append(p), FakeClock(1.0), 0.0)
assert seen == [0]


# --- read_batch_host ------------------------------------------------------------

def test_read_batch_host():
begin = {"type": "revit_batch_begin", "count": 3}
assert bridge_receive.read_batch_host(dict(begin, host_name="Progetto_ARC")) == "Progetto_ARC"
# absent, empty or not a string: no host collection, FromRevit as before
assert bridge_receive.read_batch_host(begin) is None
assert bridge_receive.read_batch_host(dict(begin, host_name="")) is None
assert bridge_receive.read_batch_host(dict(begin, host_name=7)) is None


def test_batch_state_keeps_host_until_next_begin():
state = bridge_receive.BatchState()
state.begin(2, 0.0, "Progetto_ARC")
assert state.host == "Progetto_ARC"
state.end(1.0)
assert state.host == "Progetto_ARC"
state.begin(2, 2.0)
assert state.host is None
Loading