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
27 changes: 19 additions & 8 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,11 @@ removes it.
the preview restarts empty and a Sync is needed.
- Only one active connection at a time. A second client is not refused:
its connection waits in the listener backlog, with no hello_ack, until
the first one disconnects.
the first one disconnects. The Blender side sends nothing but the
`hello` until the `hello_ack` arrives: the panel says "waiting for
Revit" and Sync, Bake, Proxy and the live transforms stay off.
- When the connection drops, a bake or proxy still waiting for its result
is marked as lost on the panel: its outcome will not arrive.

---

Expand Down Expand Up @@ -186,7 +190,8 @@ failure would have to be treated as terminal.
`hello` is answered with `hello_ack` only when `protocol_version` matches the
add-in's (an absent field is accepted); a different version gets an `error`
frame that names both versions. The Blender side makes the same check on
`hello_ack` and disconnects on a mismatch.
`hello_ack` and disconnects on a mismatch; an `error` that arrives before
any `hello_ack` disconnects as well, with Revit's message as the status.

`sync_begin` lists the ids that are about to arrive: it lets Revit remove,
at the end, the objects no longer present in the collection, atomically and
Expand All @@ -209,7 +214,7 @@ the server takes part in Revit's transparent pass: the faces are drawn
there, with the transparency both in the vertex colors and on the face
effects, and the edges stay opaque in the opaque pass so the outline stays
readable. At 1 the preview is drawn in the opaque pass only, as before.
Blender sends it at Connect, at every Sync and whenever the user changes a
Blender sends it at the handshake, at every Sync and whenever the user changes a
color or the opacity; Revit ignores it when nothing changed, otherwise it
rebuilds the GPU buffers once, because the colors are stored in the vertex
buffers. Out-of-range components or opacity are an `error`.
Expand Down Expand Up @@ -489,7 +494,8 @@ and a rejection fails only that object.
**Two modes, `target` on the batch** (Phase B2): `"directshape"` (default
if absent) or `"family"`. In family mode each object becomes a loadable
family `BL_<name>` with a `FreeFormElement`, created from
`English\Metric Generic Model.rft`, loaded without saving and with an
`English\Metric Generic Model.rft` (falling back to the imperial
templates), saved as `BL_<name>.rfa` in a temp folder, loaded, and with an
instance on the nearest level below the origin. Revit decomposes the
matrix (`FamilyPlacement`): translation and rotation around Z go to the
instance, tilts and scale go into the geometry. Re-bake does `EditFamily`
Expand All @@ -516,11 +522,15 @@ normal family bake is the same thing with a group of one. Re-bake with the
same host aligns the family to the objects of THIS bake: their
`FreeFormElement`s are updated or added, the bridge's ones of objects no
longer in the bake are deleted (the user's own elements have no mark and
stay). A member that fails is reported and keeps its previous
`FreeFormElement`; if the host fails, nothing is written. The DirectShapes
stay). A member that fails, or is announced and never arrives, keeps its
previous `FreeFormElement`; if the host fails, nothing is written. Loose
parts of one object become one solid with several volumes. The DirectShapes
of all members and the families of their own of the non-host members are
removed (`switched`). Remove Bake finds a together family through its host
only.
only, and so does a bake: baking a non-host member on its own creates its
own family or DirectShape while its `FreeFormElement` stays in the host's
family, so the geometry is there twice. Re-bake the group from the host, or
remove the member from it first.

`bake_remove` deletes all `DirectShape` elements, families and instances
marked with those ids, copies included: it is the explicit request to
Expand Down Expand Up @@ -747,7 +757,8 @@ Blender side, a failure also produces the `error` frame.
`ok` says whether the write to the document succeeded. An object that
fails inside an otherwise successful bake does not make it false: it ends
up in `failed` and `message` carries the reason for the last one that
failed. `as_mesh` counts the objects that came out of the builder as a
failed, followed by the Note of the Status (`; ` between them) when there
is one. `as_mesh` counts the objects that came out of the builder as a
mesh rather than a solid (open mesh or non-manifold). `faces_planar` and
`faces_triangulated` say how many polygons arrived whole and how many
fell back to triangles. `target` repeats the batch's mode (`"all"` for
Expand Down
2 changes: 1 addition & 1 deletion src/Bilocus.Revit/Bake/BakeBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,6 @@ private static string ResolveCategory(Document document, string category, out El
return null;
}

// Fills the builder with the object's faces. Returns the rejection
// What BuildShape hands back: the builder, its result and the face
// set it was filled with. The caller owns them: the DirectShape bake
// disposes them after SetShape, the family bake keeps them alive
Expand Down Expand Up @@ -402,6 +401,7 @@ private static string BuildOnce(BakeFaceSet faces, double[] points, bool meshOnl
}
}

// Fills the builder with the object's faces. Returns the rejection
// reason if no face is left, otherwise null.
//
// FamilyBaker reaches it through BuildShape, passing points in FAMILY
Expand Down
11 changes: 11 additions & 0 deletions src/Bilocus.Revit/Bake/BakeResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,17 @@ public string BuildMessage()
return Succeeded ? "" : UnknownReason;
}

// The message of bake_result: BuildMessage plus the Note. Without the
// Note, whoever pressed Bake in Blender would never read what the
// Status says (a BL_ value not written, a name already used, the
// batch run without the undo group).
public string BuildWireMessage()
{
string message = BuildMessage();
if (string.IsNullOrEmpty(Note)) { return message; }
return message.Length == 0 ? Note : message + "; " + Note;
}

private string DescribeLastFailure()
{
string reason = string.IsNullOrEmpty(LastFailureReason) ? UnknownReason : LastFailureReason;
Expand Down
29 changes: 18 additions & 11 deletions src/Bilocus.Revit/Bake/FamilyBaker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,11 @@ namespace Bilocus.Revit.Bake
// Note.
//
// CTRL+Z. A TransactionGroup is tried around the whole batch, as in the
// DirectShape bake. If Revit rejects LoadFamily or EditFamily with the
// group open (nobody could test it outside the add-in), the group rolls
// back, it is remembered for the session and the batch is run again from
// scratch without a group: more undo entries, stated in the Status Note.
// DirectShape bake. Verified in Revit that LoadFamily and EditFamily
// accept the open group. Kept as a safety net: if Revit ever rejects
// them, the group rolls back, it is remembered for the session and the
// batch is run again from scratch without a group: more undo entries,
// stated in the Status Note.
//
// As in BakeBuilder: a failure that concerns an object fails only that
// ONE object, counted and named in BakeResult. No TaskDialog.
Expand Down Expand Up @@ -89,11 +90,6 @@ public static class FamilyBaker
// half the batch every time.
private static bool? _groupAllowsFamilyLoad;

public static bool? GroupAllowsFamilyLoad
{
get { return _groupAllowsFamilyLoad; }
}

// The candidate template paths for this version of Revit, in the
// order they are tried. Public because the error message cites them,
// and whoever reads the Status must be able to compare them with the
Expand Down Expand Up @@ -510,6 +506,16 @@ private string BakeFamily(BakeMeshRequest host, List<BakeMeshRequest> members)
{
List<MemberSolid> built = new List<MemberSolid>();
HashSet<string> requested = new HashSet<string>(StringComparer.Ordinal);
if (_batch.Together)
{
// Announced but never arrived (pack failed in
// Blender, frame rejected) is not "no longer
// selected": its FreeFormElement stays, like a
// member that fails. Only together: in a normal
// bake the other announced ids are families of
// their own and must leave the host's.
foreach (string id in _batch.AnnouncedIds) { requested.Add(id); }
}
List<string> otherCategories = new List<string>();
int facesPlanar = 0;
int facesTriangulated = 0;
Expand Down Expand Up @@ -631,6 +637,9 @@ private string BuildMemberSolid(BakeMeshRequest member, bool isHost, FamilyPlace
return NonManifoldRefusal;
}

// Loose parts (two cubes joined with Ctrl+J) come back as ONE
// solid with several volumes, verified in Revit 2025: the
// first solid is the whole object.
Solid first = FirstSolid(built.GetGeometricalObjects());
if (first == null)
{
Expand All @@ -640,7 +649,6 @@ private string BuildMemberSolid(BakeMeshRequest member, bool isHost, FamilyPlace
solid = new MemberSolid
{
ObjectId = member.ObjectId,
Name = member.Name,
Solid = first,
OpenShell = openShell,
FacesPlanar = faces.PlanarCount,
Expand Down Expand Up @@ -1374,7 +1382,6 @@ public static ObjectWrite Done(bool created, int switched, bool notMoved, string
private sealed class MemberSolid
{
public string ObjectId;
public string Name;
public Solid Solid;
public bool OpenShell;
public int FacesPlanar;
Expand Down
7 changes: 7 additions & 0 deletions src/Bilocus.Revit/Bake/FamilyParameters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ public static List<BakeParameter> Apply(Document familyDoc, IList<BakeParameter>
if (!wanted.TryGetValue(name, out p) || fp.IsInstance
|| fp.Definition.GetDataType() != SpecOf(p.Kind))
{
if (!string.IsNullOrEmpty(fp.Formula))
{
// The user gave it a formula: it is theirs now
keptAsIs.Add(name);
left.Add(name + " kept, it has a formula");
continue;
}
string user = FormulaUsing(existing, fp);
if (user != null)
{
Expand Down
19 changes: 17 additions & 2 deletions src/Bilocus.Revit/Net/BridgeServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ public void Stop()
: "stopped (the listener thread did not respond within 2 seconds)";
}

private const int SendTimeoutMs = 10000;

// Returns true if the frame went out in full.
public bool Send(Frame frame)
{
Expand Down Expand Up @@ -166,8 +168,15 @@ public bool Send(Frame frame)
// promised bytes. The protocol has no delimiters, there is
// no realignment, so this is terminal for the connection:
// the socket is closed and listening resumes.
_status = "write error, connection closed: " + ex.Message;
CloseClient();
// Only if the failed stream is still THE connection:
// Blender may have reconnected while this Send was
// writing to the old one, and closing now would drop
// the new client for nothing.
if (ReferenceEquals(_stream, stream))
{
_status = "write error, connection closed: " + ex.Message;
CloseClient();
}
return false;
}
}
Expand All @@ -190,6 +199,12 @@ private void Loop()
// that shows on screen.
client.NoDelay = true;

// Send runs on Revit's main thread: a Blender that stops
// reading (suspended, hung) would freeze Revit inside a
// write with no way out. The timeout turns that into a
// write error, which Send already treats as terminal.
client.SendTimeout = SendTimeoutMs;

accepted = true;
_client = client;

Expand Down
5 changes: 2 additions & 3 deletions src/Bilocus.Revit/Net/MessageRouter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -350,8 +350,7 @@ private void HandleBakeBegin(JsonElement root)
try
{
// Phase B2: target absent = directshape, so a Phase B Blender
// keeps doing the bake it used to do. The target is read
// before the ids because it decides their cap.
// keeps doing the bake it used to do.
string target = OptionalTarget(root);

// host present = "Bake together" (DESIGN.md 5.3). Present
Expand Down Expand Up @@ -809,7 +808,7 @@ public static string BuildBakeResult(BakeResult result)
writer.WriteString("target", result.Target);
writer.WriteNumber("switched", result.SwitchedCount);
writer.WriteNumber("not_moved", result.NotMovedCount);
writer.WriteString("message", result.BuildMessage());
writer.WriteString("message", result.BuildWireMessage());
writer.WriteEndObject();
}
return Encoding.UTF8.GetString(buffer.ToArray());
Expand Down
7 changes: 6 additions & 1 deletion src/Bilocus.Revit/Preview/GpuChunk.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,12 @@ public sealed class GpuChunk

public bool IsValid()
{
return _litVertices != null && _litVertices.IsValid()
return _litFormat != null && _litFormat.IsValid()
&& _flatFormat != null && _flatFormat.IsValid()
&& _litEffect != null && _litEffect.IsValid()
&& _flatEffect != null && _flatEffect.IsValid()
&& _flatFaceEffect != null && _flatFaceEffect.IsValid()
&& _litVertices != null && _litVertices.IsValid()
&& _flatFaceVertices != null && _flatFaceVertices.IsValid()
&& _triangleIndices != null && _triangleIndices.IsValid()
&& (_lineCount == 0
Expand Down
20 changes: 15 additions & 5 deletions src/Bilocus.Revit/Preview/PreviewServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,14 +96,24 @@ public void RenderScene(View view, DisplayStyle displayStyle)

foreach (StoredObject item in objects)
{
List<GpuChunk> chunks = GetOrBuild(item);
// Per object: a failure on one (a GPU allocation, say)
// must not hide every object after it, nor skip the
// transform reset below.
try
{
List<GpuChunk> chunks = GetOrBuild(item);

DrawContext.SetWorldTransform(ToRevitTransform(item.Matrix));
DrawContext.SetWorldTransform(ToRevitTransform(item.Matrix));

foreach (GpuChunk chunk in chunks)
foreach (GpuChunk chunk in chunks)
{
if (DrawContext.IsInterrupted()) { return; }
chunk.Draw(displayStyle, drawFaces, drawEdges);
}
}
catch (Exception ex)
{
if (DrawContext.IsInterrupted()) { return; }
chunk.Draw(displayStyle, drawFaces, drawEdges);
LastError = string.Format("{0}: {1}: {2}", item.Name, ex.GetType().Name, ex.Message);
}
}
// Precaution: the DrawContext is shared across the registered
Expand Down
61 changes: 59 additions & 2 deletions src/blender_addon/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@

@bpy.app.handlers.persistent
def _on_depsgraph_update(scene, depsgraph):
if not client.CLIENT.running:
if not client.CLIENT.ready:
return

collection = coll.find_collection()
Expand Down Expand Up @@ -116,6 +116,17 @@ def _on_depsgraph_update(scene, depsgraph):


def _flush_transforms():
# Same safety net as _handle_safely, for the whole tick: an exception
# that reaches Blender unregisters the timer, and the addon would stay
# connected but deaf without telling anyone.
try:
_flush_step()
except Exception as error:
_log("transform flush failed: {}: {}".format(type(error).__name__, error))
return TRANSFORM_INTERVAL


def _flush_step():
if _PENDING:
# drain BEFORE sending: send() is synchronous and can take a few
# milliseconds, and whatever arrives meanwhile must end up in the
Expand All @@ -124,7 +135,6 @@ def _flush_transforms():
_PENDING.clear()
for obj_id, matrix in batch:
sync.send_transform(obj_id, matrix)
return TRANSFORM_INTERVAL


def _log(message):
Expand Down Expand Up @@ -162,8 +172,21 @@ def _handle_message(header, payload, now):
client.CLIENT.status = problem
_log(problem)
else:
client.CLIENT.handshake_ok = True
client.CLIENT.status = "handshake ok, Revit {}".format(
header.get("revit_version", "?"))
# Revit starts with the default colors: send the scene's now
sync.send_style(bpy.context.scene)
_tag_redraw()

elif kind == "error" and not client.CLIENT.handshake_ok:
# an error instead of the hello_ack: Revit refused the hello (a
# different protocol version). Staying connected would only get
# every later message rejected.
client.CLIENT.disconnect()
client.CLIENT.status = "Revit refused the connection: {}".format(
header.get("message", "?"))
_log(client.CLIENT.status)
_tag_redraw()

elif kind == "error":
Expand Down Expand Up @@ -240,8 +263,38 @@ def _handle_safely(header, payload):
# perf_counter when the previous tick stopped with messages still queued
_DRAIN_PAUSED_AT = None

# (running, status) seen by the previous tick. The read thread changes
# both when the connection drops, but it cannot touch bpy: the redraw and
# the bookkeeping of the drop happen here.
_LAST_STATE = None


def _check_connection_state():
global _LAST_STATE
state = (client.CLIENT.running, client.CLIENT.status)
if state == _LAST_STATE:
return
dropped = _LAST_STATE is not None and _LAST_STATE[0] and not state[0]
_LAST_STATE = state
if dropped:
# a bake or proxy still waiting will never get its outcome: the
# panel would say "waiting" forever
for last in (bake.LAST_BAKE, proxy.LAST_PROXY):
if client.OUTCOME_PENDING in last["message"]:
last["message"] = "connection lost before Revit replied: check the outcome in Revit"
_tag_redraw()


def _drain_incoming():
# same safety net as _flush_transforms
try:
return _drain_step()
except Exception as error:
_log("drain failed: {}: {}".format(type(error).__name__, error))
return DRAIN_INTERVAL


def _drain_step():
# runs on the main thread: bpy is usable here
global _DRAIN_PAUSED_AT
budget = receive.DRAIN_BUDGET_SECONDS
Expand Down Expand Up @@ -271,6 +324,10 @@ def _drain_incoming():
_log("pull interrupted: {}".format(imp.LAST_PULL.message))
_tag_redraw()

# after the queue: a result already queued when the connection dropped
# is read before the drop is declared
_check_connection_state()

return DRAIN_INTERVAL


Expand Down
Loading
Loading