Skip to content

Open-source Revit MCP server: let Claude and other AI assistants read and edit BIM models, with human approval on every change.

feat: implement PowerBI bridge tool and Rhino add-in integration with updated Revit MCP server components

A. Sam Mohammad949d2e5f4af1
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..cb78818
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,131 @@
+# AEC Omni-Bridge — Project Reference
+
+## Architecture
+
+Four independent "switches" (per-platform add-ins) + one Python MCP hub:
+
+| package | language | port | status |
+|---------|----------|------|--------|
+| `packages/rhino-bridge-addin/` | C# .NET 4.8 | 3004 | built ✓ |
+| `packages/navisworks-bridge-addin/` | C# .NET 4.8 | 3005 | routing infra ✓ |
+| `packages/powerbi-bridge-tool/` | Python | — | stub |
+| `packages/mcp-server-revit/` | Python | — | MCP hub |
+
+MCP providers: `packages/mcp-server-revit/src/revit_mcp_server/providers/`
+Canonical backlog: `docs/agent-task-plan.md`
+Architecture blueprint: `docs/system-blueprint-and-workflows.md`
+
+## Rhino Bridge — Quick Reference
+
+**URL:** `http://127.0.0.1:3004`
+
+**Build (Rhino must be CLOSED):**
+```powershell
+cd packages/rhino-bridge-addin
+dotnet build -c Release
+```
+
+**All bridge commands** (POST `/execute`):
+
+| command | key params |
+|---------|-----------|
+| `get_document_info` | — |
+| `get_lines` | — |
+| `get_scene` | — → all objects with type/layer/bbox |
+| `list_layers` | — |
+| `clear_scene` | `layer?` (omit = delete all) |
+| `set_view` | `view`: perspective\|top\|front\|right\|rendered\|arctic |
+| `create_box` | `min_pt [x,y,z]`, `max_pt [x,y,z]` |
+| `create_sphere` | `center [x,y,z]`, `radius` |
+| `create_cylinder` | `base [x,y,z]`, `height`, `radius` |
+| `boolean_union` | `ids: [guid,...]` |
+| `boolean_difference` | `base_id`, `cutter_ids: [guid,...]` |
+| `set_material` | `ids`\|`layer`, `color [r,g,b]`, `transparency`, `reflectivity` |
+| `transform_objects` | `ids`, `translation`\|`rotation`\|`scale` |
+| `run_python` | `code` — IronPython, stdout captured |
+| `generate_diagrid_tower` | all dims in metres; auto unit-converted |
+| `reflect_get` / `reflect_set` / `invoke_method` | reflection access |
+
+All geometry params in **metres** (C# converts via `RhinoMath.UnitScale`).
+
+## Python Iteration (no recompile)
+
+```python
+import requests
+code = open("scratch/rhino_diagrid_tower.py").read()
+r = requests.post("http://127.0.0.1:3004/execute",
+ json={"command": "run_python", "code": code}, timeout=300)
+print(r.json().get("output", ""))
+```
+
+Edit `scratch/rhino_diagrid_tower.py` → re-run. Rhino updates live.
+
+## RhinoCommon v7 Gotchas
+
+- `mat.ToPhysicallyBased()` → `void` (not `bool`) — never wrap in `if`
+- `PythonScript.ExecuteScript(code)` → 1 arg only (not 2)
+- `TransparencyColor` property does NOT exist — use `mat.Transparency` (double)
+- NuGet: `RhinoCommon 7.16.22067.13001`, target `net48`
+- Use reflection for properties that differ between v7/v8
+
+## MCP Provider Pattern
+
+`providers/rhino.py` maps tool name → bridge command:
+```python
+self._tool_mapping["rhino_foo"] = ("foo_command", lambda args: {"param": args.get("param")})
+# Plus matching ProviderTool entry in _capabilities
+```
+
+## Commit Rules
+
+- No `Co-Authored-By` trailers — ever
+- `docs/ecosystem-strategy-and-monetization.md` is potentially private — check before pushing
+
+## Diagrid Glass Panel Geometry
+
+**Canonical script:** `scratch/glass_diamond.py`
+
+### Critical: loft surface UV axis orientation
+
+`Brep.CreateFromLoft` of horizontal circles produces a surface where:
+- **U (first param) = HEIGHT direction** — 0.0 = tower base, 1.0 = roof
+- **V (second param) = CIRCUMFERENCE direction** — 0.0/1.0 = seam at angle 0°
+
+In the code, `i` = height index (maps to U), `j` = circumference index (maps to V). The circumferential seam wraps at `j % V_DIVS`. Never wrap `i` — wrapping height jumps from near-top to floor and creates 200m-tall spanning panels.
+
+### gpt / cc conventions
+
+```python
+def gpt(i, j): # grid corner — i=height (no wrap), j=circ (wraps)
+ return face.PointAt(float(i) / U_DIVS, float(j % V_DIVS) / V_DIVS)
+
+def cc(i, j): # cell centre on surface
+ return face.PointAt((i + 0.5) / U_DIVS, ((j % V_DIVS) + 0.5) / V_DIVS)
+```
+
+### Panel types
+
+All edges lie along half-segments of actual diagonal mullion members:
+
+| type | vertices | covers | loop range |
+|------|----------|--------|------------|
+| **A** | `cc(i,j)` → `gpt(i+1,j+1)` → `cc(i,j+1)` → `gpt(i,j+1)` | top△(i,j) + bottom△(i,j+1) | i=0..U_DIVS-1, j=0..V_DIVS-1 |
+| **B** | `cc(i,j)` → `gpt(i+1,j)` → `cc(i+1,j)` → `gpt(i+1,j+1)` | right△(i,j) + left△(i+1,j) | i=0..U_DIVS-2, j=0..V_DIVS-1 |
+| **Bot cap** | `gpt(0,j)` → `gpt(0,j+1)` → `cc(0,j)` | left△ of bottom row | j=0..V_DIVS-1 |
+| **Top cap** | `cc(U-1,j)` → `gpt(U,j+1)` → `gpt(U,j)` | right△ of top row | j=0..V_DIVS-1 |
+
+Count at U_DIVS=20, V_DIVS=36: 720 + 684 + 36 + 36 = **1476 panels**, 0 skipped.
+
+## Skill Reference
+
+Use `/rhino-god-mode` for the complete command reference, Python patterns, materials,
+Gram-Schmidt mullion orientation, and buildable glass panel code.
+
+## /compact Policy
+
+When compressing context, preserve:
+- Which files were modified this session
+- Current bridge command set and any new commands added
+- Active error messages / fixes in flight
+- Build status (compiled / Rhino open or closed)
+- Any GUID values still in use
diff --git a/Omni_LiveGeometryStats.csv b/Omni_LiveGeometryStats.csv
new file mode 100644
index 0000000..bc33c73
--- /dev/null
+++ b/Omni_LiveGeometryStats.csv
@@ -0,0 +1,4 @@
+Dome_ID,Volume_m3,Est_Cost_USD,Carbon_Footprint_tons,Radius_m,X,Y
+Geodesic_Dome_1,113097.24,39584034.0,45238.9,30.0,0.0,0.0
+Geodesic_Dome_2,65449.79,22907427.08,26179.92,25.0,60.0,20.0
+Geodesic_Dome_3,268082.35,93828821.33,107232.94,40.0,-50.0,50.0
diff --git a/deploy_pbi.ps1 b/deploy_pbi.ps1
new file mode 100644
index 0000000..56e507e
--- /dev/null
+++ b/deploy_pbi.ps1
@@ -0,0 +1,5 @@
+$pbiExternalToolsDir = 'C:\Program Files (x86)\Common Files\Microsoft Shared\Power BI Desktop\External Tools'
+if (-not (Test-Path $pbiExternalToolsDir)) {
+ New-Item -ItemType Directory -Force -Path $pbiExternalToolsDir | Out-Null
+}
+Copy-Item -Path 'c:\Users\sammo\OneDrive\Documenten\GitHub\Autodesk-Revit-MCP-Server\packages\powerbi-bridge-tool\AECModelBridge.pbitool_filled.json' -Destination (Join-Path $pbiExternalToolsDir 'AECModelBridge.pbitool.json') -Force
diff --git a/docs/Untitled.3dm b/docs/Untitled.3dm
new file mode 100644
index 0000000..d24e131
Binary files /dev/null and b/docs/Untitled.3dm differ
diff --git a/docs/Untitled.3dm.rhl b/docs/Untitled.3dm.rhl
new file mode 100644
index 0000000..1a4b4c4
--- /dev/null
+++ b/docs/Untitled.3dm.rhl
@@ -0,0 +1,3 @@
+sammo
+DESKTOP-PF9RO94
+Sunday, June 14, 2026
\ No newline at end of file
diff --git a/docs/Untitled2.3dm b/docs/Untitled2.3dm
new file mode 100644
index 0000000..9bdf4d8
Binary files /dev/null and b/docs/Untitled2.3dm differ
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/providers/__init__.py b/packages/mcp-server-revit/src/revit_mcp_server/providers/__init__.py
index 54383a6..68ab36d 100644
--- a/packages/mcp-server-revit/src/revit_mcp_server/providers/__init__.py
+++ b/packages/mcp-server-revit/src/revit_mcp_server/providers/__init__.py
@@ -5,6 +5,7 @@ from .ifc import IfcProvider
from .fake import FakeProvider
from .identity_mapper import AECMapperProvider
from .rhino import RhinoProvider
+from .navisworks import NavisworksProvider
from .graph import SemanticGraphProvider
from .cloud import SpeckleProvider, AutodeskDataProvider
from .job_provider import JobProvider
@@ -20,6 +21,7 @@ __all__ = [
"FakeProvider",
"AECMapperProvider",
"RhinoProvider",
+ "NavisworksProvider",
"SemanticGraphProvider",
"SpeckleProvider",
"AutodeskDataProvider",
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/providers/navisworks.py b/packages/mcp-server-revit/src/revit_mcp_server/providers/navisworks.py
new file mode 100644
index 0000000..5b299c5
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/providers/navisworks.py
@@ -0,0 +1,110 @@
+import logging
+from typing import Any, Dict, List
+from ..config import config, BridgeMode
+from ..bridge.client import BridgeClient
+from ..security.workspace import WorkspaceMonitor
+from .base import AECProvider, ProviderTool
+
+logger = logging.getLogger(__name__)
+
+class NavisworksProvider(AECProvider):
+ def __init__(
+ self,
+ workspace: WorkspaceMonitor,
+ mode: BridgeMode = config.mode,
+ bridge_url: str | None = None,
+ bridge_factory=None
+ ) -> None:
+ self.workspace = workspace
+ self.mode = mode
+
+ url = bridge_url or "http://127.0.0.1:3002"
+ factory = bridge_factory or (lambda u, t=None: BridgeClient(u, token=t))
+ self._bridge = factory(url, None)
+ self._init_tool_mapping()
+
+ def get_identity(self) -> str:
+ return "navisworks"
+
+ def get_capabilities(self) -> List[ProviderTool]:
+ return self._capabilities
+
+ async def check_health(self) -> Dict[str, Any]:
+ if self.mode == BridgeMode.bridge:
+ try:
+ if hasattr(self._bridge, '_get'):
+ return self._bridge._get("/health")
+ return {"status": "healthy", "mode": "bridge"}
+ except Exception as e:
+ return {"status": "unhealthy", "error": str(e)}
+ return {"status": "healthy", "mode": "mock"}
+
+ async def execute_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
+ if name not in self._tool_mapping:
+ raise ValueError(f"Unknown Navisworks tool '{name}'")
+
+ bridge_tool, payload_builder = self._tool_mapping[name]
+ payload = payload_builder(arguments)
+
+ if "request_id" in arguments and "request_id" not in payload:
+ payload["request_id"] = arguments["request_id"]
+
+ if self.mode == BridgeMode.bridge:
+ return self._bridge.send_tool(bridge_tool, payload)
+ else:
+ return {"mock": True, "tool": bridge_tool, "payload": payload}
+
+ def _init_tool_mapping(self):
+ self._tool_mapping = {
+ "navisworks_health": ("navisworks.health", lambda args: {}),
+ "navisworks_invoke_method": ("navis.invoke_method", lambda args: {
+ "class_name": args.get("class_name"),
+ "method_name": args.get("method_name"),
+ "arguments": args.get("arguments"),
+ "target_id": args.get("target_id")
+ }),
+ "navisworks_reflect_get": ("navis.reflect_get", lambda args: {
+ "target_id": args.get("target_id"),
+ "property_name": args.get("property_name")
+ }),
+ "navisworks_reflect_set": ("navis.reflect_set", lambda args: {
+ "target_id": args.get("target_id"),
+ "property_name": args.get("property_name"),
+ "value": args.get("value")
+ }),
+ }
+
+ _capabilities = [
+ ProviderTool(
+ name="navisworks_health",
+ description="Check if Navisworks is running and get status information",
+ inputSchema={"type": "object", "properties": {}, "required": []}
+ ),
+ ProviderTool(
+ name="navisworks_invoke_method",
+ description="Invoke a C# method in Navisworks via reflection",
+ inputSchema={"type": "object", "properties": {
+ "class_name": {"type": "string"},
+ "method_name": {"type": "string"},
+ "arguments": {"type": "array"},
+ "target_id": {"type": "string"}
+ }, "required": ["class_name", "method_name", "arguments"]}
+ ),
+ ProviderTool(
+ name="navisworks_reflect_get",
+ description="Get a C# property value from a Navisworks object via reflection",
+ inputSchema={"type": "object", "properties": {
+ "target_id": {"type": "string"},
+ "property_name": {"type": "string"}
+ }, "required": ["target_id", "property_name"]}
+ ),
+ ProviderTool(
+ name="navisworks_reflect_set",
+ description="Set a C# property value on a Navisworks object via reflection",
+ inputSchema={"type": "object", "properties": {
+ "target_id": {"type": "string"},
+ "property_name": {"type": "string"},
+ "value": {}
+ }, "required": ["target_id", "property_name", "value"]}
+ ),
+ ]
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/providers/powerbi.py b/packages/mcp-server-revit/src/revit_mcp_server/providers/powerbi.py
new file mode 100644
index 0000000..ec8ec7c
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/providers/powerbi.py
@@ -0,0 +1,121 @@
+import logging
+from typing import Any, Dict, List
+
+from ..config import config, BridgeMode
+from ..bridge.client import BridgeClient
+from ..security.workspace import WorkspaceMonitor
+from .base import AECProvider, ProviderTool
+
+logger = logging.getLogger(__name__)
+
+class PowerBIProvider(AECProvider):
+ def __init__(
+ self,
+ workspace: WorkspaceMonitor,
+ mode: BridgeMode = config.mode,
+ bridge_url: str | None = None,
+ bridge_factory=None
+ ) -> None:
+ self.workspace = workspace
+ self.mode = mode
+
+ url = bridge_url or "http://127.0.0.1:3006"
+ factory = bridge_factory or (lambda u, t=None: BridgeClient(u, token=t))
+ self._bridge = factory(url, None)
+ self._init_tool_mapping()
+
+ def get_identity(self) -> str:
+ return "powerbi"
+
+ def get_capabilities(self) -> List[ProviderTool]:
+ return self._capabilities
+
+ async def check_health(self) -> Dict[str, Any]:
+ if self.mode == BridgeMode.bridge:
+ try:
+ if hasattr(self._bridge, '_get'):
+ return self._bridge._get("/health")
+ return {"status": "healthy", "mode": "bridge"}
+ except Exception as e:
+ return {"status": "unhealthy", "error": str(e)}
+ return {"status": "healthy", "mode": "mock"}
+
+ async def execute_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
+ if name not in self._tool_mapping:
+ raise ValueError(f"Unknown Power BI tool '{name}'")
+
+ bridge_tool, payload_builder = self._tool_mapping[name]
+ payload = payload_builder(arguments)
+
+ if "request_id" in arguments and "request_id" not in payload:
+ payload["request_id"] = arguments["request_id"]
+
+ if self.mode == BridgeMode.bridge:
+ return self._bridge.send_tool(bridge_tool, payload)
+ else:
+ return {"mock": True, "tool": bridge_tool, "payload": payload}
+
+ def _init_tool_mapping(self):
+ self._tool_mapping = {
+ "powerbi_health": ("health", lambda args: {}),
+ "powerbi_execute_dax": ("execute_dax", lambda args: {
+ "query": args.get("query")
+ }),
+ "powerbi_invoke_method": ("invoke_method", lambda args: {
+ "class_name": args.get("class_name"),
+ "method_name": args.get("method_name"),
+ "arguments": args.get("arguments"),
+ "target_id": args.get("target_id")
+ }),
+ "powerbi_reflect_get": ("reflect_get", lambda args: {
+ "target_id": args.get("target_id"),
+ "property_name": args.get("property_name")
+ }),
+ "powerbi_reflect_set": ("reflect_set", lambda args: {
+ "target_id": args.get("target_id"),
+ "property_name": args.get("property_name"),
+ "value": args.get("value")
+ }),
+ }
+
+ _capabilities = [
+ ProviderTool(
+ name="powerbi_health",
+ description="Check if Power BI External Tool Bridge is running",
+ inputSchema={"type": "object", "properties": {}, "required": []}
+ ),
+ ProviderTool(
+ name="powerbi_execute_dax",
+ description="Execute a DAX query against the active Power BI dataset",
+ inputSchema={"type": "object", "properties": {
+ "query": {"type": "string", "description": "The DAX query to execute"}
+ }, "required": ["query"]}
+ ),
+ ProviderTool(
+ name="powerbi_invoke_method",
+ description="Invoke a C# method in Power BI bridge via reflection",
+ inputSchema={"type": "object", "properties": {
+ "class_name": {"type": "string"},
+ "method_name": {"type": "string"},
+ "arguments": {"type": "array"},
+ "target_id": {"type": "string"}
+ }, "required": ["class_name", "method_name", "arguments"]}
+ ),
+ ProviderTool(
+ name="powerbi_reflect_get",
+ description="Get a C# property value from a Power BI bridge object via reflection",
+ inputSchema={"type": "object", "properties": {
+ "target_id": {"type": "string"},
+ "property_name": {"type": "string"}
+ }, "required": ["target_id", "property_name"]}
+ ),
+ ProviderTool(
+ name="powerbi_reflect_set",
+ description="Set a C# property value on a Power BI bridge object via reflection",
+ inputSchema={"type": "object", "properties": {
+ "target_id": {"type": "string"},
+ "property_name": {"type": "string"},
+ "value": {}
+ }, "required": ["target_id", "property_name", "value"]}
+ ),
+ ]
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/providers/rhino.py b/packages/mcp-server-revit/src/revit_mcp_server/providers/rhino.py
index 68ecc1a..5cf5edd 100644
--- a/packages/mcp-server-revit/src/revit_mcp_server/providers/rhino.py
+++ b/packages/mcp-server-revit/src/revit_mcp_server/providers/rhino.py
@@ -1,56 +1,34 @@
-from __future__ import annotations
+import logging
+from typing import Any, Dict, List
-import base64
-import os
-from urllib.parse import urlparse
-from pathlib import Path
-from typing import Any, Dict, List, Mapping, Sequence
-
-import httpx
-
-from ..errors import BridgeError, WorkspaceViolation
+from ..config import config, BridgeMode
+from ..bridge.client import BridgeClient
from ..security.workspace import WorkspaceMonitor
from .base import AECProvider, ProviderTool
+logger = logging.getLogger(__name__)
-class RhinoProvider(AECProvider):
- SUPPORTED_DEFINITION_EXTENSIONS = {".gh", ".ghx"}
- SUPPORTED_GEOMETRY_EXTENSIONS = {".3dm"}
+def _optional(args: Dict, *keys) -> Dict:
+ """Return a dict of only the keys present in args (used to build sparse bridge payloads)."""
+ return {k: args[k] for k in keys if k in args}
+
+
+class RhinoProvider(AECProvider):
def __init__(
self,
workspace: WorkspaceMonitor,
- base_url: str | None = None,
- api_key: str | None = None,
- api_key_header: str = "RhinoComputeKey",
- client: httpx.AsyncClient | None = None,
- timeout: float = 30.0,
- grasshopper_prefix: str = "/grasshopper",
- rhino_prefix: str = "/rhino",
- io_path: str = "/io",
- solve_path: str = "/solve",
- geometry_query_path: str = "/query_file_geometry",
- layers_path: str = "/layers",
- geometry_details_path: str = "/geometry_details",
- max_upload_bytes: int | None = None,
+ mode: BridgeMode = config.mode,
+ bridge_url: str | None = None,
+ bridge_factory=None
) -> None:
self.workspace = workspace
- self.base_url = (base_url or os.getenv("MCP_RHINO_COMPUTE_URL") or os.getenv("RHINO_COMPUTE_URL") or "https://localhost:5001").rstrip("/")
- self._enforce_base_url_policy(self.base_url)
- self.api_key = api_key or os.getenv("MCP_RHINO_COMPUTE_KEY") or os.getenv("RHINO_COMPUTE_KEY")
- self.api_key_header = api_key_header
- self.timeout = timeout
- self.max_upload_bytes = self._resolve_max_upload_bytes(max_upload_bytes)
- self._own_client = client is None
- self._client = client or httpx.AsyncClient(base_url=self.base_url, timeout=timeout, follow_redirects=True)
- self._grasshopper_prefix = self._normalize_prefix(grasshopper_prefix)
- self._rhino_prefix = self._normalize_prefix(rhino_prefix)
- self._io_path = self._normalize_suffix(io_path)
- self._solve_path = self._normalize_suffix(solve_path)
- self._geometry_query_path = self._normalize_suffix(geometry_query_path)
- self._layers_path = self._normalize_suffix(layers_path)
- self._geometry_details_path = self._normalize_suffix(geometry_details_path)
- self._init_capabilities()
+ self.mode = mode
+
+ url = bridge_url or "http://127.0.0.1:3004"
+ bridge_factory = bridge_factory or (lambda u, t=None: BridgeClient(u, token=t))
+ self._bridge = bridge_factory(url, None)
+ self._init_tool_mapping()
def get_identity(self) -> str:
return "rhino"
@@ -59,285 +37,279 @@ class RhinoProvider(AECProvider):
return self._capabilities
async def check_health(self) -> Dict[str, Any]:
- response = await self._request_json("GET", "/health")
- return response
+ if self.mode == BridgeMode.bridge:
+ try:
+ if hasattr(self._bridge, '_get'):
+ return self._bridge._get("/health")
+ return {"status": "healthy", "mode": "bridge"}
+ except Exception as e:
+ return {"status": "unhealthy", "error": str(e)}
+ return {"status": "healthy", "mode": "mock"}
async def execute_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
- normalized = name.replace(".", "_")
- if normalized == "rhino_health":
- return await self.check_health()
- if normalized == "rhino_get_definition_io":
- definition_path = self._require_path(arguments, "definition_path", self.SUPPORTED_DEFINITION_EXTENSIONS)
- return await self._definition_io(definition_path)
- if normalized == "rhino_evaluate_definition":
- definition_path = self._require_path(arguments, "definition_path", self.SUPPORTED_DEFINITION_EXTENSIONS)
- input_trees = self._validate_input_trees(arguments.get("input_trees"))
- return await self._evaluate_definition(definition_path, input_trees)
- if normalized == "rhino_query_file_geometry":
- file_path = self._require_path(arguments, "file_path", self.SUPPORTED_GEOMETRY_EXTENSIONS)
- return await self._query_file_geometry(file_path, arguments)
- if normalized == "rhino_get_layers":
- file_path = self._require_path(arguments, "file_path", self.SUPPORTED_GEOMETRY_EXTENSIONS)
- return await self._get_layers(file_path)
- if normalized == "rhino_get_geometry_details":
- file_path = self._require_path(arguments, "file_path", self.SUPPORTED_GEOMETRY_EXTENSIONS)
- return await self._get_geometry_details(file_path, arguments)
- raise ValueError(f"Unknown Rhino tool '{name}'")
-
- async def shutdown(self) -> None:
- if self._own_client:
- await self._client.aclose()
-
- def _init_capabilities(self) -> None:
- self._capabilities = [
- ProviderTool(
- name="rhino_health",
- description="Check Rhino.Compute connectivity and service status",
- inputSchema={"type": "object", "properties": {}, "required": []},
- ),
- ProviderTool(
- name="rhino_get_definition_io",
- description="Upload a Grasshopper definition and return its Resthopper input/output metadata",
- inputSchema={
- "type": "object",
- "properties": {
- "definition_path": {
- "type": "string",
- "description": "Workspace path to a .gh or .ghx Grasshopper definition",
- }
- },
- "required": ["definition_path"],
- },
- ),
- ProviderTool(
- name="rhino_evaluate_definition",
- description="Upload a Grasshopper definition, solve it against Resthopper-compatible trees, and return the compute response",
- inputSchema={
- "type": "object",
- "properties": {
- "definition_path": {
- "type": "string",
- "description": "Workspace path to a .gh or .ghx Grasshopper definition",
- },
- "input_trees": {
- "type": "array",
- "description": "Resthopper-compatible input trees",
- "items": {
- "type": "object",
- "properties": {
- "ParamName": {"type": "string"},
- "InnerTree": {"type": "object"},
- },
- "required": ["ParamName", "InnerTree"],
- },
- },
- },
- "required": ["definition_path"],
- },
- ),
- ProviderTool(
- name="rhino_query_file_geometry",
- description="Upload a .3dm file and query geometry summaries through Rhino.Compute",
- inputSchema={
- "type": "object",
- "properties": {
- "file_path": {
- "type": "string",
- "description": "Workspace path to a .3dm file",
- },
- "include_hidden": {
- "type": "boolean",
- "default": False,
- "description": "Include hidden objects when querying geometry",
- },
- },
- "required": ["file_path"],
- },
- ),
- ProviderTool(
- name="rhino_get_layers",
- description="Return layer metadata for a .3dm file through Rhino.Compute",
- inputSchema={
- "type": "object",
- "properties": {
- "file_path": {
- "type": "string",
- "description": "Workspace path to a .3dm file",
- }
- },
- "required": ["file_path"],
- },
- ),
- ProviderTool(
- name="rhino_get_geometry_details",
- description="Return detailed geometry metadata for a .3dm file through Rhino.Compute",
- inputSchema={
- "type": "object",
- "properties": {
- "file_path": {
- "type": "string",
- "description": "Workspace path to a .3dm file",
- }
- },
- "required": ["file_path"],
- },
- ),
- ]
-
- def _normalize_prefix(self, prefix: str) -> str:
- cleaned = prefix.strip()
- if not cleaned:
- return ""
- return "/" + cleaned.strip("/")
-
- def _normalize_suffix(self, suffix: str) -> str:
- cleaned = suffix.strip()
- if not cleaned:
- return ""
- return "/" + cleaned.strip("/")
-
- def _build_endpoint(self, prefix: str, suffix: str) -> str:
- if not prefix:
- return suffix or "/"
- if not suffix:
- return prefix
- return f"{prefix}{suffix}"
-
- def _require_path(self, arguments: Mapping[str, Any], key: str, allowed_extensions: Sequence[str]) -> Path:
- raw_path = arguments.get(key)
- if not isinstance(raw_path, str) or not raw_path.strip():
- raise ValueError(f"Argument '{key}' is required.")
- try:
- resolved = self.workspace.assert_in_workspace(Path(raw_path))
- except WorkspaceViolation as exc:
- raise ValueError("Path is outside the allowed workspace.") from exc
- if resolved.suffix.lower() not in {ext.lower() for ext in allowed_extensions}:
- raise ValueError(
- f"Unsupported Rhino file extension '{resolved.suffix or '<none>'}' for '{resolved.name}'."
- )
- if not resolved.exists():
- raise FileNotFoundError(f"Rhino file not found: {resolved.name}")
- return resolved
+ if name not in self._tool_mapping:
+ raise ValueError(f"Unknown Rhino tool '{name}'")
+
+ bridge_tool, payload_builder = self._tool_mapping[name]
+ payload = payload_builder(arguments)
+
+ if "request_id" in arguments and "request_id" not in payload:
+ payload["request_id"] = arguments["request_id"]
- def _validate_input_trees(self, input_trees: Any) -> list[dict[str, Any]]:
- if input_trees is None:
- return []
- if not isinstance(input_trees, list):
- raise ValueError("Argument 'input_trees' must be a list when provided.")
- validated: list[dict[str, Any]] = []
- for index, tree in enumerate(input_trees):
- if not isinstance(tree, dict):
- raise ValueError(f"Input tree at index {index} must be an object.")
- if "ParamName" not in tree or "InnerTree" not in tree:
- raise ValueError(f"Input tree at index {index} must include 'ParamName' and 'InnerTree'.")
- validated.append(tree)
- return validated
+ if self.mode == BridgeMode.bridge:
+ return self._bridge.send_tool(bridge_tool, payload)
+ else:
+ return {"mock": True, "tool": bridge_tool, "payload": payload}
- def _tree_to_resthopper_values(self, input_trees: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
- return [dict(tree) for tree in input_trees]
-
- def _file_payload(self, file_path: Path) -> dict[str, Any]:
- self._enforce_upload_size(file_path)
- return {
- "file_name": file_path.name,
- "file_data": base64.b64encode(file_path.read_bytes()).decode("ascii"),
- }
-
- async def _definition_io(self, definition_path: Path) -> Dict[str, Any]:
- payload = self._file_payload(definition_path)
- response = await self._request_json(
- "POST",
- self._build_endpoint(self._grasshopper_prefix, self._io_path),
- payload=payload,
- )
- return response
-
- async def _evaluate_definition(self, definition_path: Path, input_trees: Sequence[Mapping[str, Any]]) -> Dict[str, Any]:
- io_response = await self._definition_io(definition_path)
- definition_id = (
- io_response.get("definition_id")
- or io_response.get("id")
- or io_response.get("DefinitionId")
- or io_response.get("DefinitionID")
- )
- if not definition_id:
- raise BridgeError("Rhino.Compute did not return a definition identifier from the IO endpoint.")
-
- solve_payload = {
- "definition_id": definition_id,
- "input_trees": self._tree_to_resthopper_values(input_trees),
+ def _init_tool_mapping(self):
+ self._tool_mapping = {
+ # ── Core ──────────────────────────────────────────────────────────────
+ "rhino_health": ("health", lambda args: {}),
+ "rhino_get_document_info": ("get_document_info", lambda args: {}),
+ "rhino_get_lines": ("get_lines", lambda args: {}),
+ # ── Scene ─────────────────────────────────────────────────────────────
+ "rhino_get_scene": ("get_scene", lambda args: {}),
+ "rhino_list_layers": ("list_layers", lambda args: {}),
+ "rhino_clear_scene": ("clear_scene", lambda args: {
+ **({"layer": args["layer"]} if "layer" in args else {})
+ }),
+ "rhino_set_view": ("set_view", lambda args: {
+ "view": args.get("view", "perspective")
+ }),
+ # ── Geometry creation ─────────────────────────────────────────────────
+ "rhino_create_box": ("create_box", lambda args: {
+ "min_pt": args["min_pt"],
+ "max_pt": args["max_pt"],
+ **_optional(args, "layer", "color"),
+ }),
+ "rhino_create_sphere": ("create_sphere", lambda args: {
+ "center": args["center"],
+ "radius": args["radius"],
+ **_optional(args, "layer", "color"),
+ }),
+ "rhino_create_cylinder": ("create_cylinder", lambda args: {
+ "base": args["base"],
+ "height": args["height"],
+ "radius": args["radius"],
+ **_optional(args, "layer", "color"),
+ }),
+ # ── Booleans ──────────────────────────────────────────────────────────
+ "rhino_boolean_union": ("boolean_union", lambda args: {
+ "ids": args["ids"],
+ **_optional(args, "layer"),
+ }),
+ "rhino_boolean_difference": ("boolean_difference", lambda args: {
+ "base_id": args["base_id"],
+ "cutter_ids": args["cutter_ids"],
+ }),
+ # ── Materials ─────────────────────────────────────────────────────────
+ "rhino_set_material": ("set_material", lambda args: {
+ **_optional(args, "ids", "layer", "color", "transparency",
+ "reflectivity", "name"),
+ }),
+ # ── Transform ─────────────────────────────────────────────────────────
+ "rhino_transform_objects": ("transform_objects", lambda args: {
+ "ids": args["ids"],
+ **_optional(args, "translation", "rotation", "scale"),
+ }),
+ # ── Python execution ──────────────────────────────────────────────────
+ "rhino_run_python": ("run_python", lambda args: {
+ "code": args["code"]
+ }),
+ # ── Parametric tower ──────────────────────────────────────────────────
+ "rhino_generate_diagrid_tower": ("generate_diagrid_tower", lambda args: {
+ "base_radius": args.get("base_radius", 22.0),
+ "waist_radius": args.get("waist_radius", 14.0),
+ "top_radius": args.get("top_radius", 19.0),
+ "height": args.get("height", 180.0),
+ "u_divs": args.get("u_divs", 16),
+ "v_divs": args.get("v_divs", 28),
+ "mullion_width": args.get("mullion_width", 0.15),
+ "mullion_depth": args.get("mullion_depth", 0.30),
+ "glass_thickness": args.get("glass_thickness", 0.024),
+ "inset_ratio": args.get("inset_ratio", 0.12),
+ }),
+ # ── Reflection ────────────────────────────────────────────────────────
+ "rhino_invoke_method": ("invoke_method", lambda args: {
+ "class_name": args.get("class_name"),
+ "method_name": args.get("method_name"),
+ "arguments": args.get("arguments"),
+ "target_id": args.get("target_id"),
+ }),
+ "rhino_reflect_get": ("reflect_get", lambda args: {
+ "target_id": args.get("target_id"),
+ "property_name": args.get("property_name"),
+ }),
+ "rhino_reflect_set": ("reflect_set", lambda args: {
+ "target_id": args.get("target_id"),
+ "property_name": args.get("property_name"),
+ "value": args.get("value"),
+ }),
}
- return await self._request_json(
- "POST",
- self._build_endpoint(self._grasshopper_prefix, self._solve_path),
- payload=solve_payload,
- )
-
- async def _query_file_geometry(self, file_path: Path, arguments: Mapping[str, Any]) -> Dict[str, Any]:
- payload = self._file_payload(file_path)
- payload["include_hidden"] = bool(arguments.get("include_hidden", False))
- return await self._request_json(
- "POST",
- self._build_endpoint(self._rhino_prefix, self._geometry_query_path),
- payload=payload,
- )
-
- async def _get_layers(self, file_path: Path) -> Dict[str, Any]:
- payload = self._file_payload(file_path)
- return await self._request_json(
- "POST",
- self._build_endpoint(self._rhino_prefix, self._layers_path),
- payload=payload,
- )
-
- async def _get_geometry_details(self, file_path: Path, arguments: Mapping[str, Any]) -> Dict[str, Any]:
- payload = self._file_payload(file_path)
- if "object_ids" in arguments:
- payload["object_ids"] = arguments["object_ids"]
- return await self._request_json(
- "POST",
- self._build_endpoint(self._rhino_prefix, self._geometry_details_path),
- payload=payload,
- )
-
- async def _request_json(self, method: str, endpoint: str, *, payload: dict[str, Any] | None = None) -> Dict[str, Any]:
- headers = {}
- if self.api_key:
- headers[self.api_key_header] = self.api_key
- try:
- response = await self._client.request(method, endpoint, json=payload, headers=headers)
- response.raise_for_status()
- response_payload = response.json()
- except httpx.HTTPStatusError as exc:
- raise BridgeError(f"Rhino.Compute request to {endpoint} failed with status {exc.response.status_code}") from exc
- except httpx.RequestError as exc:
- raise BridgeError(f"Rhino.Compute request to {endpoint} failed: {exc.__class__.__name__}") from exc
- except ValueError as exc:
- raise BridgeError(f"Rhino.Compute response from {endpoint} was not valid JSON") from exc
- if not isinstance(response_payload, dict):
- raise BridgeError(f"Rhino.Compute response from {endpoint} was not a JSON object")
- return response_payload
-
- def _enforce_upload_size(self, file_path: Path) -> None:
- if file_path.stat().st_size > self.max_upload_bytes:
- raise ValueError(
- f"Rhino file '{file_path.name}' exceeds the maximum upload size of {self.max_upload_bytes} bytes."
- )
-
- def _enforce_base_url_policy(self, base_url: str) -> None:
- parsed = urlparse(base_url)
- if parsed.scheme not in {"http", "https"}:
- raise ValueError("Rhino.Compute base URL must use http or https.")
- if parsed.scheme == "http" and not self._is_loopback_host(parsed.hostname):
- raise ValueError("Rhino.Compute base URL must use https unless the host is localhost or 127.0.0.1.")
-
- def _is_loopback_host(self, hostname: str | None) -> bool:
- return hostname in {"localhost", "127.0.0.1", "::1"}
- def _resolve_max_upload_bytes(self, max_upload_bytes: int | None) -> int:
- if max_upload_bytes is not None:
- return int(max_upload_bytes)
- env_value = os.getenv("MCP_RHINO_COMPUTE_MAX_UPLOAD_BYTES") or os.getenv("RHINO_COMPUTE_MAX_UPLOAD_BYTES")
- if env_value:
- return int(env_value)
- return 50 * 1024 * 1024
+ _capabilities = [
+ ProviderTool(
+ name="rhino_health",
+ description="Check if the Rhino bridge is running and healthy",
+ inputSchema={"type": "object", "properties": {}, "required": []}
+ ),
+ ProviderTool(
+ name="rhino_get_document_info",
+ description="Get the active Rhino document name, path, unit system, and object count",
+ inputSchema={"type": "object", "properties": {}, "required": []}
+ ),
+ ProviderTool(
+ name="rhino_get_lines",
+ description="Get all curves/lines from the active Rhino document",
+ inputSchema={"type": "object", "properties": {}, "required": []}
+ ),
+ ProviderTool(
+ name="rhino_get_scene",
+ description="Get all objects in the Rhino scene with their type, layer, and bounding box",
+ inputSchema={"type": "object", "properties": {}, "required": []}
+ ),
+ ProviderTool(
+ name="rhino_list_layers",
+ description="List all layers in the Rhino document with name, color, visibility, and lock state",
+ inputSchema={"type": "object", "properties": {}, "required": []}
+ ),
+ ProviderTool(
+ name="rhino_clear_scene",
+ description="Delete all objects in the Rhino document, or only objects on a specific layer",
+ inputSchema={"type": "object", "properties": {
+ "layer": {"type": "string", "description": "Optional layer name; omit to delete everything"}
+ }, "required": []}
+ ),
+ ProviderTool(
+ name="rhino_set_view",
+ description="Set the active Rhino viewport display mode or projection",
+ inputSchema={"type": "object", "properties": {
+ "view": {"type": "string",
+ "enum": ["perspective", "top", "front", "right", "rendered", "arctic"],
+ "description": "Viewport to switch to"}
+ }, "required": ["view"]}
+ ),
+ ProviderTool(
+ name="rhino_create_box",
+ description="Create a box (rectangular prism) from two corner points in metres",
+ inputSchema={"type": "object", "properties": {
+ "min_pt": {"type": "array", "items": {"type": "number"}, "description": "[x,y,z] min corner"},
+ "max_pt": {"type": "array", "items": {"type": "number"}, "description": "[x,y,z] max corner"},
+ "layer": {"type": "string"},
+ "color": {"type": "array", "items": {"type": "integer"}, "description": "[r,g,b]"},
+ }, "required": ["min_pt", "max_pt"]}
+ ),
+ ProviderTool(
+ name="rhino_create_sphere",
+ description="Create a sphere by centre point and radius in metres",
+ inputSchema={"type": "object", "properties": {
+ "center": {"type": "array", "items": {"type": "number"}, "description": "[x,y,z]"},
+ "radius": {"type": "number"},
+ "layer": {"type": "string"},
+ "color": {"type": "array", "items": {"type": "integer"}},
+ }, "required": ["center", "radius"]}
+ ),
+ ProviderTool(
+ name="rhino_create_cylinder",
+ description="Create a capped cylinder from base point, height, and radius in metres",
+ inputSchema={"type": "object", "properties": {
+ "base": {"type": "array", "items": {"type": "number"}, "description": "[x,y,z] base centre"},
+ "height": {"type": "number"},
+ "radius": {"type": "number"},
+ "layer": {"type": "string"},
+ "color": {"type": "array", "items": {"type": "integer"}},
+ }, "required": ["base", "height", "radius"]}
+ ),
+ ProviderTool(
+ name="rhino_boolean_union",
+ description="Boolean union a list of Brep objects by GUID; returns new object GUIDs",
+ inputSchema={"type": "object", "properties": {
+ "ids": {"type": "array", "items": {"type": "string"}, "description": "Object GUIDs to union"},
+ "layer": {"type": "string"},
+ }, "required": ["ids"]}
+ ),
+ ProviderTool(
+ name="rhino_boolean_difference",
+ description="Subtract cutter Breps from a base Brep; returns new object GUIDs",
+ inputSchema={"type": "object", "properties": {
+ "base_id": {"type": "string"},
+ "cutter_ids": {"type": "array", "items": {"type": "string"}},
+ }, "required": ["base_id", "cutter_ids"]}
+ ),
+ ProviderTool(
+ name="rhino_set_material",
+ description="Apply a material to objects by GUID list or by layer name",
+ inputSchema={"type": "object", "properties": {
+ "ids": {"type": "array", "items": {"type": "string"}},
+ "layer": {"type": "string"},
+ "color": {"type": "array", "items": {"type": "integer"}, "description": "[r,g,b]"},
+ "transparency": {"type": "number", "minimum": 0, "maximum": 1},
+ "reflectivity": {"type": "number", "minimum": 0, "maximum": 1},
+ "name": {"type": "string"},
+ }, "required": []}
+ ),
+ ProviderTool(
+ name="rhino_transform_objects",
+ description="Move, rotate, or scale objects by GUID. Provide exactly one of: translation, rotation, or scale",
+ inputSchema={"type": "object", "properties": {
+ "ids": {"type": "array", "items": {"type": "string"}},
+ "translation": {"type": "array", "items": {"type": "number"}, "description": "[dx,dy,dz] in metres"},
+ "rotation": {"type": "object", "properties": {
+ "axis": {"type": "array", "items": {"type": "number"}},
+ "angle_deg": {"type": "number"},
+ "origin": {"type": "array", "items": {"type": "number"}},
+ }},
+ "scale": {"type": "array", "items": {"type": "number"}, "description": "[sx,sy,sz]"},
+ }, "required": ["ids"]}
+ ),
+ ProviderTool(
+ name="rhino_run_python",
+ description="Execute arbitrary IronPython code inside Rhino with full RhinoCommon access. stdout is captured and returned.",
+ inputSchema={"type": "object", "properties": {
+ "code": {"type": "string", "description": "Python source code to run inside Rhino"},
+ }, "required": ["code"]}
+ ),
+ ProviderTool(
+ name="rhino_generate_diagrid_tower",
+ description="Generate a parametric diagrid skyscraper with aluminum mullion sweeps and glass panel solids. All dims in metres.",
+ inputSchema={"type": "object", "properties": {
+ "base_radius": {"type": "number", "description": "Ground floor radius (m)"},
+ "waist_radius": {"type": "number", "description": "Narrowest radius at mid-height (m)"},
+ "top_radius": {"type": "number", "description": "Crown radius (m)"},
+ "height": {"type": "number", "description": "Total tower height (m)"},
+ "u_divs": {"type": "integer", "description": "Panels around circumference"},
+ "v_divs": {"type": "integer", "description": "Panels up the height"},
+ "mullion_width": {"type": "number", "description": "Visible face width (m)"},
+ "mullion_depth": {"type": "number", "description": "Structural depth toward exterior (m)"},
+ "glass_thickness": {"type": "number", "description": "IGU depth (m)"},
+ "inset_ratio": {"type": "number", "description": "Fraction to inset glass corners from cell edge"},
+ }, "required": []}
+ ),
+ ProviderTool(
+ name="rhino_invoke_method",
+ description="Invoke a C# method on a Rhino object via reflection",
+ inputSchema={"type": "object", "properties": {
+ "class_name": {"type": "string"},
+ "method_name": {"type": "string"},
+ "arguments": {"type": "array"},
+ "target_id": {"type": "string"},
+ }, "required": ["class_name", "method_name", "arguments"]}
+ ),
+ ProviderTool(
+ name="rhino_reflect_get",
+ description="Get a C# property value from a Rhino object via reflection",
+ inputSchema={"type": "object", "properties": {
+ "target_id": {"type": "string"},
+ "property_name": {"type": "string"},
+ }, "required": ["target_id", "property_name"]}
+ ),
+ ProviderTool(
+ name="rhino_reflect_set",
+ description="Set a C# property value on a Rhino object via reflection",
+ inputSchema={"type": "object", "properties": {
+ "target_id": {"type": "string"},
+ "property_name": {"type": "string"},
+ "value": {},
+ }, "required": ["target_id", "property_name", "value"]}
+ ),
+ ]
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/server.py b/packages/mcp-server-revit/src/revit_mcp_server/server.py
index c87a73a..981db9c 100644
--- a/packages/mcp-server-revit/src/revit_mcp_server/server.py
+++ b/packages/mcp-server-revit/src/revit_mcp_server/server.py
@@ -18,6 +18,7 @@ from .providers import (
IfcProvider,
AECMapperProvider,
RhinoProvider,
+ NavisworksProvider,
SemanticGraphProvider,
AutodeskDataProvider,
JobProvider,
@@ -81,6 +82,11 @@ class MCPServer:
except Exception as e:
logger.warning("Could not initialize RhinoProvider: %s", e)
+ try:
+ self.registry.register(NavisworksProvider(workspace=self.workspace))
+ except Exception as e:
+ logger.warning("Could not initialize NavisworksProvider: %s", e)
+
try:
self.registry.register(SemanticGraphProvider())
except Exception as e:
diff --git a/packages/navisworks-bridge-addin/src/BridgeCommands.cs b/packages/navisworks-bridge-addin/src/BridgeCommands.cs
index 471aa66..7f6c4c8 100644
--- a/packages/navisworks-bridge-addin/src/BridgeCommands.cs
+++ b/packages/navisworks-bridge-addin/src/BridgeCommands.cs
@@ -182,5 +182,61 @@ namespace NavisworksBridge
activated = vp.DisplayName
};
}
+ [BridgeCommand("navis.invoke_method", IsMutating = true)]
+ public static object InvokeMethod(JsonElement payload)
+ {
+ var doc = Application.ActiveDocument;
+ var className = payload.GetProperty("class_name").GetString();
+ var methodName = payload.GetProperty("method_name").GetString();
+ var args = payload.GetProperty("arguments");
+ var targetId = payload.TryGetProperty("target_id", out var tId) ? tId.GetString() : null;
+
+ return ReflectionHelper.InvokeMethod(doc, className, methodName, args, targetId);
+ }
+
+ [BridgeCommand("navis.reflect_get", IsMutating = false)]
+ public static object ReflectGet(JsonElement payload)
+ {
+ var doc = Application.ActiveDocument;
+ var targetId = payload.GetProperty("target_id").GetString();
+ var propertyName = payload.GetProperty("property_name").GetString();
+
+ var target = ReflectionHelper.GetObject(targetId, doc);
+ if (target == null) throw new Exception($"Target '{targetId}' not found");
+
+ var prop = target.GetType().GetProperty(propertyName);
+ if (prop == null) throw new Exception($"Property '{propertyName}' not found on type '{target.GetType().Name}'");
+
+ var value = prop.GetValue(target);
+ if (value == null) return null;
+ if (value.GetType().IsPrimitive || value is string) return value;
+
+ var refId = ReflectionHelper.RegisterObject(value);
+ return new { type = "reference", id = refId, class_name = value.GetType().Name, str = value.ToString() };
+ }
+
+ [BridgeCommand("navis.reflect_set", IsMutating = true)]
+ public static object ReflectSet(JsonElement payload)
+ {
+ var doc = Application.ActiveDocument;
+ var targetId = payload.GetProperty("target_id").GetString();
+ var propertyName = payload.GetProperty("property_name").GetString();
+ var valueElement = payload.GetProperty("value");
+
+ var target = ReflectionHelper.GetObject(targetId, doc);
+ if (target == null) throw new Exception($"Target '{targetId}' not found");
+
+ var prop = target.GetType().GetProperty(propertyName);
+ if (prop == null) throw new Exception($"Property '{propertyName}' not found on type '{target.GetType().Name}'");
+
+ var value = ReflectionHelper.ParseArgument(valueElement, doc);
+ if (value != null && !prop.PropertyType.IsAssignableFrom(value.GetType()))
+ {
+ value = Convert.ChangeType(value, prop.PropertyType);
+ }
+
+ prop.SetValue(target, value);
+ return new { status = "success", target_id = targetId, property = propertyName };
+ }
}
}
diff --git a/packages/navisworks-bridge-addin/src/ReflectionHelper.cs b/packages/navisworks-bridge-addin/src/ReflectionHelper.cs
new file mode 100644
index 0000000..ddc1a82
--- /dev/null
+++ b/packages/navisworks-bridge-addin/src/ReflectionHelper.cs
@@ -0,0 +1,172 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Text.Json;
+using Autodesk.Navisworks.Api;
+
+namespace NavisworksBridge
+{
+ public static class ReflectionHelper
+ {
+ private static Dictionary<string, object> _objectRegistry = new Dictionary<string, object>();
+ private static int _objectIdCounter = 0;
+
+ public static string RegisterObject(object obj)
+ {
+ if (obj == null) return null;
+
+ string id = $"obj_{++_objectIdCounter}";
+ _objectRegistry[id] = obj;
+ return id;
+ }
+
+ public static object GetObject(string id, Document doc)
+ {
+ if (string.IsNullOrEmpty(id)) return null;
+ if (_objectRegistry.ContainsKey(id)) return _objectRegistry[id];
+ return null;
+ }
+
+ public static void ClearRegistry()
+ {
+ _objectRegistry.Clear();
+ _objectIdCounter = 0;
+ }
+
+ public static object ParseArgument(JsonElement arg, Document doc)
+ {
+ switch (arg.ValueKind)
+ {
+ case JsonValueKind.String:
+ return arg.GetString();
+ case JsonValueKind.Number:
+ if (arg.TryGetInt32(out int i)) return i;
+ return arg.GetDouble();
+ case JsonValueKind.True: return true;
+ case JsonValueKind.False: return false;
+ case JsonValueKind.Null: return null;
+ case JsonValueKind.Object:
+ if (arg.TryGetProperty("type", out var typeProp) && typeProp.GetString() == "reference")
+ {
+ return GetObject(arg.GetProperty("id").GetString(), doc);
+ }
+ if (arg.TryGetProperty("x", out _) && arg.TryGetProperty("y", out _) && arg.TryGetProperty("z", out _))
+ {
+ return new Point3D(arg.GetProperty("x").GetDouble(), arg.GetProperty("y").GetDouble(), arg.GetProperty("z").GetDouble());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ public static Type ResolveType(string typeName)
+ {
+ if (typeName == "int" || typeName == "System.Int32") return typeof(int);
+ if (typeName == "double" || typeName == "System.Double") return typeof(double);
+ if (typeName == "string" || typeName == "System.String") return typeof(string);
+ if (typeName == "bool" || typeName == "System.Boolean") return typeof(bool);
+
+ var assemblies = AppDomain.CurrentDomain.GetAssemblies()
+ .Where(a => a.FullName.StartsWith("Autodesk.Navisworks") || a.FullName.StartsWith("System"));
+
+ foreach (var asm in assemblies)
+ {
+ var type = asm.GetType(typeName) ?? asm.GetType("Autodesk.Navisworks.Api." + typeName) ?? asm.GetType("Autodesk.Navisworks.Api.Interop." + typeName);
+ if (type != null) return type;
+ }
+
+ return null;
+ }
+
+ public static object InvokeMethod(Document doc, string typeName, string methodName, JsonElement argsElement, string targetId = null)
+ {
+ Type type = ResolveType(typeName);
+ if (type == null) throw new Exception($"Type '{typeName}' not found.");
+
+ object target = null;
+ if (!string.IsNullOrEmpty(targetId))
+ {
+ target = GetObject(targetId, doc);
+ if (target == null) throw new Exception($"Target object '{targetId}' not found.");
+ }
+
+ List<object> args = new List<object>();
+ if (argsElement.ValueKind == JsonValueKind.Array)
+ {
+ foreach (var argJson in argsElement.EnumerateArray())
+ {
+ args.Add(ParseArgument(argJson, doc));
+ }
+ }
+
+ if (methodName == "new" || methodName == "ctor")
+ {
+ var constructors = type.GetConstructors().Where(c => c.GetParameters().Length == args.Count).ToList();
+ if (constructors.Count == 0) throw new Exception($"Constructor with {args.Count} arguments not found on type '{type.Name}'.");
+
+ var ctor = constructors.First();
+ var ctorParams = ctor.GetParameters();
+ object[] ctorArgs = new object[args.Count];
+
+ for (int i = 0; i < args.Count; i++)
+ {
+ var targetType = ctorParams[i].ParameterType;
+ var val = args[i];
+
+ if (targetType.IsEnum)
+ {
+ if (val is string s) val = Enum.Parse(targetType, s);
+ else if (val is int n) val = Enum.ToObject(targetType, n);
+ }
+
+ if (val is IConvertible && !targetType.IsAssignableFrom(val.GetType()))
+ {
+ try { val = Convert.ChangeType(val, targetType); } catch {}
+ }
+ ctorArgs[i] = val;
+ }
+
+ object instance = ctor.Invoke(ctorArgs);
+ string regId = RegisterObject(instance);
+ return new { type = "reference", id = regId, class_name = instance.GetType().Name, str = instance.ToString() };
+ }
+
+ var flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;
+ var methods = type.GetMethods(flags).Where(m => m.Name == methodName && m.GetParameters().Length == args.Count).ToList();
+
+ if (methods.Count == 0) throw new Exception($"Method '{methodName}' with {args.Count} arguments not found on type '{type.Name}'.");
+
+ MethodInfo methodToInvoke = methods.First();
+ var parameters = methodToInvoke.GetParameters();
+ object[] finalArgs = new object[args.Count];
+ for (int i = 0; i < args.Count; i++)
+ {
+ var targetType = parameters[i].ParameterType;
+ var val = args[i];
+
+ if (targetType.IsEnum)
+ {
+ if (val is string s) val = Enum.Parse(targetType, s);
+ else if (val is int n) val = Enum.ToObject(targetType, n);
+ }
+
+ if (val is IConvertible && !targetType.IsAssignableFrom(val.GetType()))
+ {
+ try { val = Convert.ChangeType(val, targetType); } catch {}
+ }
+
+ finalArgs[i] = val;
+ }
+
+ object result = methodToInvoke.Invoke(target, finalArgs);
+
+ if (result == null) return null;
+ if (result.GetType().IsPrimitive || result is string) return result;
+
+ string resultRegId = RegisterObject(result);
+ return new { type = "reference", id = resultRegId, class_name = result.GetType().Name, str = result.ToString() };
+ }
+ }
+}
diff --git a/packages/powerbi-bridge-tool/AECModelBridge.pbitool.json b/packages/powerbi-bridge-tool/AECModelBridge.pbitool.json
new file mode 100644
index 0000000..77669f2
--- /dev/null
+++ b/packages/powerbi-bridge-tool/AECModelBridge.pbitool.json
@@ -0,0 +1,7 @@
+{
+ "name": "AEC Model Bridge",
+ "description": "Connects Power BI to the AEC Model Bridge Hub",
+ "path": "%PBITOOL_PATH%\\PowerBIBridge.exe",
+ "arguments": "\"%server%\" \"%database%\"",
+ "iconData": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEwAACxMBAJqcGAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAAydEVYdFRpdGxlAENyZWF0aXZlIENvbW1vbnMgQXR0cmlidXRpb24gMy4wIFVucG9ydGVkIExpY2Vuc2Xp9yqAAAAAElFTkSuQmCC"
+}
diff --git a/packages/powerbi-bridge-tool/AECModelBridge.pbitool_filled.json b/packages/powerbi-bridge-tool/AECModelBridge.pbitool_filled.json
new file mode 100644
index 0000000..b82f3da
--- /dev/null
+++ b/packages/powerbi-bridge-tool/AECModelBridge.pbitool_filled.json
@@ -0,0 +1,8 @@
+{
+ "name": "AEC Model Bridge",
+ "description": "Connects Power BI to the AEC Model Bridge Hub",
+ "path": "C:\\Users\\sammo\\OneDrive\\Documenten\\GitHub\\Autodesk-Revit-MCP-Server\\packages\\powerbi-bridge-tool\\bin\\Release\\net8.0-windows\\PowerBIBridge.exe",
+ "arguments": "\"%server%\" \"%database%\"",
+ "iconData": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEwAACxMBAJqcGAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAAydEVYdFRpdGxlAENyZWF0aXZlIENvbW1vbnMgQXR0cmlidXRpb24gMy4wIFVucG9ydGVkIExpY2Vuc2Xp9yqAAAAAElFTkSuQmCC"
+}
+
diff --git a/packages/powerbi-bridge-tool/PowerBIBridge.csproj b/packages/powerbi-bridge-tool/PowerBIBridge.csproj
new file mode 100644
index 0000000..ff1cc0a
--- /dev/null
+++ b/packages/powerbi-bridge-tool/PowerBIBridge.csproj
@@ -0,0 +1,19 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net8.0-windows</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ <AssemblyName>PowerBIBridge</AssemblyName>
+ <RootNamespace>PowerBIBridge</RootNamespace>
+ <Version>1.0.0</Version>
+ <OutputPath>bin\$(Configuration)\</OutputPath>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.AnalysisServices.AdomdClient.NetCore.retail.amd64" Version="19.78.1.1" />
+ <PackageReference Include="System.Text.Json" Version="8.0.0" />
+ </ItemGroup>
+
+</Project>
diff --git a/packages/powerbi-bridge-tool/src/Program.cs b/packages/powerbi-bridge-tool/src/Program.cs
new file mode 100644
index 0000000..1dc7224
--- /dev/null
+++ b/packages/powerbi-bridge-tool/src/Program.cs
@@ -0,0 +1,211 @@
+using System;
+using System.Net;
+using System.Text;
+using System.Text.Json;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.AnalysisServices.AdomdClient;
+
+namespace PowerBIBridge
+{
+ class Program
+ {
+ static async Task Main(string[] args)
+ {
+ Console.WriteLine("AEC Model Bridge - Power BI External Tool");
+
+ if (args.Length < 2)
+ {
+ Console.WriteLine("Error: Missing Server and Database arguments. This tool must be launched from Power BI Desktop.");
+ Console.WriteLine("Usage: PowerBIBridge.exe <server> <database>");
+ Console.WriteLine("Press any key to exit...");
+ Console.ReadKey();
+ return;
+ }
+
+ string server = args[0];
+ string database = args[1];
+
+ Console.WriteLine($"Connected to local Power BI instance:");
+ Console.WriteLine($"Server: {server}");
+ Console.WriteLine($"Database: {database}");
+
+ int port = 3006;
+ var listener = new HttpListener();
+ listener.Prefixes.Add($"http://127.0.0.1:{port}/");
+ listener.Prefixes.Add($"http://localhost:{port}/");
+
+ try
+ {
+ listener.Start();
+ Console.WriteLine($"\nHTTP Bridge listening on port {port}...");
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Failed to start HTTP listener: {ex.Message}");
+ return;
+ }
+
+ var cts = new CancellationTokenSource();
+ Console.CancelKeyPress += (s, e) =>
+ {
+ Console.WriteLine("Shutting down bridge...");
+ cts.Cancel();
+ e.Cancel = true;
+ };
+
+ while (!cts.IsCancellationRequested)
+ {
+ try
+ {
+ var context = await listener.GetContextAsync();
+ _ = Task.Run(() => HandleRequest(context, server, database));
+ }
+ catch (HttpListenerException) { break; }
+ catch (OperationCanceledException) { break; }
+ }
+ }
+
+ static async Task HandleRequest(HttpListenerContext context, string server, string database)
+ {
+ var request = context.Request;
+ var response = context.Response;
+
+ response.Headers.Add("Access-Control-Allow-Origin", "*");
+ response.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
+
+ if (request.HttpMethod == "OPTIONS")
+ {
+ response.StatusCode = 200;
+ response.Close();
+ return;
+ }
+
+ try
+ {
+ string resultJson = "";
+
+ if (request.Url?.AbsolutePath == "/health" && request.HttpMethod == "GET")
+ {
+ resultJson = JsonSerializer.Serialize(new { status = "healthy", bridge = "Power BI External Tool", port = 3006 });
+ }
+ else if (request.Url?.AbsolutePath == "/execute" && request.HttpMethod == "POST")
+ {
+ using var reader = new System.IO.StreamReader(request.InputStream, request.ContentEncoding ?? Encoding.UTF8);
+ var body = await reader.ReadToEndAsync();
+
+ using var doc = JsonDocument.Parse(body);
+ var root = doc.RootElement;
+ string command = root.GetProperty("command").GetString() ?? "";
+
+ if (command == "execute_dax")
+ {
+ string query = root.GetProperty("query").GetString() ?? "";
+ resultJson = ExecuteDaxQuery(server, database, query);
+ }
+ else if (command == "invoke_method")
+ {
+ var className = root.GetProperty("class_name").GetString();
+ var methodName = root.GetProperty("method_name").GetString();
+ var args = root.GetProperty("arguments");
+ var targetId = root.TryGetProperty("target_id", out var tId) ? tId.GetString() : null;
+
+ var result = ReflectionHelper.InvokeMethod(className, methodName, args, targetId);
+ resultJson = JsonSerializer.Serialize(new { success = true, data = result });
+ }
+ else if (command == "reflect_get")
+ {
+ var targetId = root.GetProperty("target_id").GetString();
+ var propertyName = root.GetProperty("property_name").GetString();
+
+ var target = ReflectionHelper.GetObject(targetId);
+ if (target == null) throw new Exception($"Target '{targetId}' not found");
+
+ var prop = target.GetType().GetProperty(propertyName);
+ if (prop == null) throw new Exception($"Property '{propertyName}' not found on type '{target.GetType().Name}'");
+
+ var value = prop.GetValue(target);
+ if (value == null) resultJson = JsonSerializer.Serialize(new { success = true, data = (object)null });
+ else if (value.GetType().IsPrimitive || value is string) resultJson = JsonSerializer.Serialize(new { success = true, data = value });
+ else
+ {
+ var refId = ReflectionHelper.RegisterObject(value);
+ resultJson = JsonSerializer.Serialize(new { success = true, data = new { type = "reference", id = refId, class_name = value.GetType().Name, str = value.ToString() } });
+ }
+ }
+ else if (command == "reflect_set")
+ {
+ var targetId = root.GetProperty("target_id").GetString();
+ var propertyName = root.GetProperty("property_name").GetString();
+ var valueElement = root.GetProperty("value");
+
+ var target = ReflectionHelper.GetObject(targetId);
+ if (target == null) throw new Exception($"Target '{targetId}' not found");
+
+ var prop = target.GetType().GetProperty(propertyName);
+ if (prop == null) throw new Exception($"Property '{propertyName}' not found on type '{target.GetType().Name}'");
+
+ var value = ReflectionHelper.ParseArgument(valueElement);
+ if (value != null && !prop.PropertyType.IsAssignableFrom(value.GetType()))
+ {
+ value = Convert.ChangeType(value, prop.PropertyType);
+ }
+
+ prop.SetValue(target, value);
+ resultJson = JsonSerializer.Serialize(new { success = true, data = new { status = "success", target_id = targetId, property = propertyName } });
+ }
+ else
+ {
+ response.StatusCode = 404;
+ resultJson = JsonSerializer.Serialize(new { error = $"Unknown command: {command}" });
+ }
+ }
+ else
+ {
+ response.StatusCode = 404;
+ resultJson = JsonSerializer.Serialize(new { error = "Not found" });
+ }
+
+ var buffer = Encoding.UTF8.GetBytes(resultJson);
+ response.ContentType = "application/json";
+ response.ContentLength64 = buffer.Length;
+ await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
+ }
+ catch (Exception ex)
+ {
+ response.StatusCode = 500;
+ var errBuffer = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { error = ex.Message }));
+ try { await response.OutputStream.WriteAsync(errBuffer, 0, errBuffer.Length); } catch { }
+ }
+ finally
+ {
+ response.Close();
+ }
+ }
+
+ static string ExecuteDaxQuery(string server, string database, string query)
+ {
+ string connectionString = $"Data Source={server};Initial Catalog={database};";
+ using var connection = new AdomdConnection(connectionString);
+ connection.Open();
+
+ using var cmd = connection.CreateCommand();
+ cmd.CommandText = query;
+
+ using var reader = cmd.ExecuteReader();
+
+ var results = new System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, object>>();
+ while (reader.Read())
+ {
+ var row = new System.Collections.Generic.Dictionary<string, object>();
+ for (int i = 0; i < reader.FieldCount; i++)
+ {
+ row[reader.GetName(i)] = reader.GetValue(i);
+ }
+ results.Add(row);
+ }
+
+ return JsonSerializer.Serialize(new { success = true, data = results });
+ }
+ }
+}
diff --git a/packages/powerbi-bridge-tool/src/ReflectionHelper.cs b/packages/powerbi-bridge-tool/src/ReflectionHelper.cs
new file mode 100644
index 0000000..d04aafe
--- /dev/null
+++ b/packages/powerbi-bridge-tool/src/ReflectionHelper.cs
@@ -0,0 +1,168 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Text.Json;
+using Microsoft.AnalysisServices.AdomdClient;
+
+namespace PowerBIBridge
+{
+ public static class ReflectionHelper
+ {
+ private static Dictionary<string, object> _objectRegistry = new Dictionary<string, object>();
+ private static int _objectIdCounter = 0;
+
+ public static string RegisterObject(object obj)
+ {
+ if (obj == null) return null;
+
+ string id = $"obj_{++_objectIdCounter}";
+ _objectRegistry[id] = obj;
+ return id;
+ }
+
+ public static object GetObject(string id)
+ {
+ if (string.IsNullOrEmpty(id)) return null;
+ if (_objectRegistry.ContainsKey(id)) return _objectRegistry[id];
+ return null;
+ }
+
+ public static void ClearRegistry()
+ {
+ _objectRegistry.Clear();
+ _objectIdCounter = 0;
+ }
+
+ public static object ParseArgument(JsonElement arg)
+ {
+ switch (arg.ValueKind)
+ {
+ case JsonValueKind.String:
+ return arg.GetString();
+ case JsonValueKind.Number:
+ if (arg.TryGetInt32(out int i)) return i;
+ return arg.GetDouble();
+ case JsonValueKind.True: return true;
+ case JsonValueKind.False: return false;
+ case JsonValueKind.Null: return null;
+ case JsonValueKind.Object:
+ if (arg.TryGetProperty("type", out var typeProp) && typeProp.GetString() == "reference")
+ {
+ return GetObject(arg.GetProperty("id").GetString());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ public static Type ResolveType(string typeName)
+ {
+ if (typeName == "int" || typeName == "System.Int32") return typeof(int);
+ if (typeName == "double" || typeName == "System.Double") return typeof(double);
+ if (typeName == "string" || typeName == "System.String") return typeof(string);
+ if (typeName == "bool" || typeName == "System.Boolean") return typeof(bool);
+
+ var assemblies = AppDomain.CurrentDomain.GetAssemblies()
+ .Where(a => a.FullName.StartsWith("Microsoft.AnalysisServices") || a.FullName.StartsWith("System"));
+
+ foreach (var asm in assemblies)
+ {
+ var type = asm.GetType(typeName) ?? asm.GetType("Microsoft.AnalysisServices.AdomdClient." + typeName);
+ if (type != null) return type;
+ }
+
+ return null;
+ }
+
+ public static object InvokeMethod(string typeName, string methodName, JsonElement argsElement, string targetId = null)
+ {
+ Type type = ResolveType(typeName);
+ if (type == null) throw new Exception($"Type '{typeName}' not found.");
+
+ object target = null;
+ if (!string.IsNullOrEmpty(targetId))
+ {
+ target = GetObject(targetId);
+ if (target == null) throw new Exception($"Target object '{targetId}' not found.");
+ }
+
+ List<object> args = new List<object>();
+ if (argsElement.ValueKind == JsonValueKind.Array)
+ {
+ foreach (var argJson in argsElement.EnumerateArray())
+ {
+ args.Add(ParseArgument(argJson));
+ }
+ }
+
+ if (methodName == "new" || methodName == "ctor")
+ {
+ var constructors = type.GetConstructors().Where(c => c.GetParameters().Length == args.Count).ToList();
+ if (constructors.Count == 0) throw new Exception($"Constructor with {args.Count} arguments not found on type '{type.Name}'.");
+
+ var ctor = constructors.First();
+ var ctorParams = ctor.GetParameters();
+ object[] ctorArgs = new object[args.Count];
+
+ for (int i = 0; i < args.Count; i++)
+ {
+ var targetType = ctorParams[i].ParameterType;
+ var val = args[i];
+
+ if (targetType.IsEnum)
+ {
+ if (val is string s) val = Enum.Parse(targetType, s);
+ else if (val is int n) val = Enum.ToObject(targetType, n);
+ }
+
+ if (val is IConvertible && !targetType.IsAssignableFrom(val.GetType()))
+ {
+ try { val = Convert.ChangeType(val, targetType); } catch {}
+ }
+ ctorArgs[i] = val;
+ }
+
+ object instance = ctor.Invoke(ctorArgs);
+ string regId = RegisterObject(instance);
+ return new { type = "reference", id = regId, class_name = instance.GetType().Name, str = instance.ToString() };
+ }
+
+ var flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;
+ var methods = type.GetMethods(flags).Where(m => m.Name == methodName && m.GetParameters().Length == args.Count).ToList();
+
+ if (methods.Count == 0) throw new Exception($"Method '{methodName}' with {args.Count} arguments not found on type '{type.Name}'.");
+
+ MethodInfo methodToInvoke = methods.First();
+ var parameters = methodToInvoke.GetParameters();
+ object[] finalArgs = new object[args.Count];
+ for (int i = 0; i < args.Count; i++)
+ {
+ var targetType = parameters[i].ParameterType;
+ var val = args[i];
+
+ if (targetType.IsEnum)
+ {
+ if (val is string s) val = Enum.Parse(targetType, s);
+ else if (val is int n) val = Enum.ToObject(targetType, n);
+ }
+
+ if (val is IConvertible && !targetType.IsAssignableFrom(val.GetType()))
+ {
+ try { val = Convert.ChangeType(val, targetType); } catch {}
+ }
+
+ finalArgs[i] = val;
+ }
+
+ object result = methodToInvoke.Invoke(target, finalArgs);
+
+ if (result == null) return null;
+ if (result.GetType().IsPrimitive || result is string) return result;
+
+ string resultRegId = RegisterObject(result);
+ return new { type = "reference", id = resultRegId, class_name = result.GetType().Name, str = result.ToString() };
+ }
+ }
+}
diff --git a/packages/rhino-bridge-addin/RhinoBridge.csproj b/packages/rhino-bridge-addin/RhinoBridge.csproj
new file mode 100644
index 0000000..a8f7e77
--- /dev/null
+++ b/packages/rhino-bridge-addin/RhinoBridge.csproj
@@ -0,0 +1,19 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>net48</TargetFramework>
+ <TargetExt>.rhp</TargetExt>
+ <AssemblyName>RhinoBridge</AssemblyName>
+ <RootNamespace>RhinoBridge</RootNamespace>
+ <Version>1.1.0</Version>
+ <OutputType>Library</OutputType>
+ <OutputPath>bin\$(Configuration)\</OutputPath>
+ <LangVersion>latest</LangVersion>
+ <Nullable>enable</Nullable>
+ <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="RhinoCommon" Version="7.16.22067.13001" IncludeAssets="compile; build" />
+ <PackageReference Include="System.Text.Json" Version="8.0.0" />
+ </ItemGroup>
+</Project>
diff --git a/packages/rhino-bridge-addin/src/BridgeCommands.cs b/packages/rhino-bridge-addin/src/BridgeCommands.cs
new file mode 100644
index 0000000..287273d
--- /dev/null
+++ b/packages/rhino-bridge-addin/src/BridgeCommands.cs
@@ -0,0 +1,564 @@
+using System;
+using System.Collections.Generic;
+using System.Drawing;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Text.Json;
+using Rhino;
+using Rhino.DocObjects;
+using Rhino.Geometry;
+
+namespace RhinoBridge
+{
+ public static class BridgeCommands
+ {
+ public static string ExecuteCommand(string jsonPayload)
+ {
+ try
+ {
+ using var doc = JsonDocument.Parse(jsonPayload);
+ var root = doc.RootElement;
+ if (!root.TryGetProperty("command", out var commandElement))
+ return JsonSerializer.Serialize(new { error = "Missing 'command' property in request." });
+
+ var command = commandElement.GetString();
+ var activeDoc = RhinoDoc.ActiveDoc;
+ if (activeDoc == null)
+ return JsonSerializer.Serialize(new { error = "No active Rhino document." });
+
+ switch (command)
+ {
+ case "get_document_info":
+ return JsonSerializer.Serialize(new
+ {
+ success = true,
+ data = new
+ {
+ name = activeDoc.Name,
+ path = activeDoc.Path,
+ modelUnitSystem = activeDoc.ModelUnitSystem.ToString(),
+ objectCount = activeDoc.Objects.Count()
+ }
+ });
+
+ case "get_lines":
+ var lines = activeDoc.Objects
+ .Where(o => o.Geometry is Rhino.Geometry.Curve)
+ .Select(o => {
+ var crv = (Rhino.Geometry.Curve)o.Geometry;
+ return new {
+ start = new { x = crv.PointAtStart.X, y = crv.PointAtStart.Y, z = crv.PointAtStart.Z },
+ end = new { x = crv.PointAtEnd.X, y = crv.PointAtEnd.Y, z = crv.PointAtEnd.Z }
+ };
+ }).ToList();
+ return JsonSerializer.Serialize(new { success = true, data = lines });
+
+ case "invoke_method":
+ {
+ var className = root.GetProperty("class_name").GetString();
+ var methodName = root.GetProperty("method_name").GetString();
+ var args = root.GetProperty("arguments");
+ var targetId = root.TryGetProperty("target_id", out var tId) ? tId.GetString() : null;
+ var result = ReflectionHelper.InvokeMethod(activeDoc, className, methodName, args, targetId);
+ return JsonSerializer.Serialize(new { success = true, data = result });
+ }
+
+ case "reflect_get":
+ {
+ var targetId = root.GetProperty("target_id").GetString();
+ var propertyName = root.GetProperty("property_name").GetString();
+ var target = ReflectionHelper.GetObject(targetId, activeDoc);
+ if (target == null) throw new Exception($"Target '{targetId}' not found");
+ var prop = target.GetType().GetProperty(propertyName)
+ ?? throw new Exception($"Property '{propertyName}' not found on '{target.GetType().Name}'");
+ var value = prop.GetValue(target);
+ if (value == null) return JsonSerializer.Serialize(new { success = true, data = (object)null });
+ if (value.GetType().IsPrimitive || value is string) return JsonSerializer.Serialize(new { success = true, data = value });
+ if (value is Guid g) return JsonSerializer.Serialize(new { success = true, data = g.ToString() });
+ var refId = ReflectionHelper.RegisterObject(value);
+ return JsonSerializer.Serialize(new { success = true, data = new { type = "reference", id = refId, class_name = value.GetType().Name, str = value.ToString() } });
+ }
+
+ case "reflect_set":
+ {
+ var targetId = root.GetProperty("target_id").GetString();
+ var propertyName = root.GetProperty("property_name").GetString();
+ var valueElement = root.GetProperty("value");
+ var target = ReflectionHelper.GetObject(targetId, activeDoc)
+ ?? throw new Exception($"Target '{targetId}' not found");
+ var prop = target.GetType().GetProperty(propertyName)
+ ?? throw new Exception($"Property '{propertyName}' not found on '{target.GetType().Name}'");
+ var value = ReflectionHelper.ParseArgument(valueElement, activeDoc);
+ if (value != null && !prop.PropertyType.IsAssignableFrom(value.GetType()))
+ value = Convert.ChangeType(value, prop.PropertyType);
+ prop.SetValue(target, value);
+ return JsonSerializer.Serialize(new { success = true, data = new { status = "success", target_id = targetId, property = propertyName } });
+ }
+
+ // Executes arbitrary Python code inside Rhino's IronPython engine.
+ // All geometry written in the Python code runs with full RhinoCommon access.
+ case "run_python":
+ {
+ var code = root.GetProperty("code").GetString()
+ ?? throw new Exception("Missing 'code' property");
+
+ var outputSb = new StringBuilder();
+
+ // IronPython via Rhino.Runtime.PythonScript (Rhino 6/7/8)
+ var python = Rhino.Runtime.PythonScript.Create();
+ if (python != null)
+ {
+ python.Output += s => outputSb.Append(s);
+ python.ExecuteScript(code);
+ activeDoc.Views.Redraw();
+ return JsonSerializer.Serialize(new { success = true, output = outputSb.ToString() });
+ }
+
+ // Fallback: write temp .py file and invoke Rhino command
+ var tmp = Path.Combine(Path.GetTempPath(), $"rh_{Guid.NewGuid():N}.py");
+ File.WriteAllText(tmp, code, Encoding.UTF8);
+ try
+ {
+ RhinoApp.RunScript($"_RunPythonScript \"{tmp}\"", false);
+ activeDoc.Views.Redraw();
+ return JsonSerializer.Serialize(new { success = true, output = "Script executed (file mode)" });
+ }
+ finally { try { File.Delete(tmp); } catch { } }
+ }
+
+ case "generate_diagrid_tower":
+ {
+ double scale = RhinoMath.UnitScale(UnitSystem.Meters, activeDoc.ModelUnitSystem);
+
+ double baseRad = (root.TryGetProperty("base_radius", out var br) ? br.GetDouble() : 22.0) * scale;
+ double waistRad = (root.TryGetProperty("waist_radius", out var wr) ? wr.GetDouble() : 14.0) * scale;
+ double topRad = (root.TryGetProperty("top_radius", out var tr) ? tr.GetDouble() : 19.0) * scale;
+ double height = (root.TryGetProperty("height", out var h) ? h.GetDouble() : 180.0) * scale;
+ int uDivs = root.TryGetProperty("u_divs", out var u) ? u.GetInt32() : 16;
+ int vDivs = root.TryGetProperty("v_divs", out var v) ? v.GetInt32() : 28;
+ double mullionW = root.TryGetProperty("mullion_width", out var mw) ? mw.GetDouble() : 0.15;
+ double mullionD = root.TryGetProperty("mullion_depth", out var md) ? md.GetDouble() : 0.30;
+ double glassThick = root.TryGetProperty("glass_thickness", out var gt) ? gt.GetDouble() : 0.024;
+ double insetRatio = root.TryGetProperty("inset_ratio", out var ir) ? ir.GetDouble() : 0.12;
+
+ // --- Geometry ---
+ var surface = DiagridGenerator.GenerateTowerSurface(baseRad, waistRad, topRad, height);
+ if (surface == null) throw new Exception("Failed to generate tower surface.");
+
+ var face = surface.Faces[0];
+ var pts = DiagridGenerator.SampleGridPoints(face, uDivs, vDivs);
+ var diagridLines = DiagridGenerator.GenerateDiagridLines(pts, uDivs, vDivs);
+
+ var profile = CurtainWallDetailer.CreateMullionCurve(mullionW, mullionD, scale);
+ var mullions = CurtainWallDetailer.GenerateMullionSweeps(diagridLines, profile, face);
+ var glassPanels = CurtainWallDetailer.GenerateGlassPanels(pts, face, uDivs, vDivs, glassThick, insetRatio, 0.02, scale);
+
+ // --- PBR Materials ---
+ int mullionMatIdx = CreateAluminumMaterial(activeDoc);
+ int glassMatIdx = CreateGlassMaterial(activeDoc);
+
+ // --- Layers ---
+ int mullionLayer = GetOrCreateLayer(activeDoc, "Mullions", Color.FromArgb(38, 40, 48));
+ int glassLayer = GetOrCreateLayer(activeDoc, "Glass", Color.FromArgb(18, 75, 52));
+
+ var mullionAttr = new ObjectAttributes
+ {
+ LayerIndex = mullionLayer,
+ MaterialIndex = mullionMatIdx,
+ MaterialSource = ObjectMaterialSource.MaterialFromObject
+ };
+ var glassAttr = new ObjectAttributes
+ {
+ LayerIndex = glassLayer,
+ MaterialIndex = glassMatIdx,
+ MaterialSource = ObjectMaterialSource.MaterialFromObject
+ };
+
+ // --- Bake ---
+ int mullionCount = 0;
+ foreach (var m in mullions) { activeDoc.Objects.AddBrep(m, mullionAttr); mullionCount++; }
+
+ int glassCount = 0;
+ foreach (var g in glassPanels) { activeDoc.Objects.AddBrep(g, glassAttr); glassCount++; }
+
+ activeDoc.Views.Redraw();
+
+ return JsonSerializer.Serialize(new
+ {
+ success = true,
+ data = new
+ {
+ message = $"Generated {mullionCount} mullion sweeps and {glassCount} glass solids with PBR materials.",
+ mullionCount,
+ glassCount
+ }
+ });
+ }
+
+ // ── God Mode commands ─────────────────────────────────────────────────
+
+ case "get_scene":
+ {
+ var objects = activeDoc.Objects.Select(o => {
+ var bb = o.Geometry.GetBoundingBox(false);
+ return new {
+ id = o.Id.ToString(),
+ type = o.Geometry.GetType().Name,
+ layer = activeDoc.Layers[o.Attributes.LayerIndex].Name,
+ bbox = new {
+ min = new { x = bb.Min.X, y = bb.Min.Y, z = bb.Min.Z },
+ max = new { x = bb.Max.X, y = bb.Max.Y, z = bb.Max.Z }
+ }
+ };
+ }).ToList();
+ return JsonSerializer.Serialize(new { success = true, data = objects });
+ }
+
+ case "list_layers":
+ {
+ var layers = activeDoc.Layers.Select(l => new {
+ name = l.Name,
+ color = new { r = l.Color.R, g = l.Color.G, b = l.Color.B },
+ visible = l.IsVisible,
+ locked = l.IsLocked
+ }).ToList();
+ return JsonSerializer.Serialize(new { success = true, data = layers });
+ }
+
+ case "clear_scene":
+ {
+ int deleted = 0;
+ if (root.TryGetProperty("layer", out var layerEl))
+ {
+ var layerName = layerEl.GetString();
+ var li = activeDoc.Layers.FindName(layerName, -1);
+ if (li == null) throw new Exception($"Layer '{layerName}' not found");
+ var ids = activeDoc.Objects
+ .Where(o => o.Attributes.LayerIndex == li.Index)
+ .Select(o => o.Id).ToList();
+ foreach (var id in ids) { activeDoc.Objects.Delete(id, true); deleted++; }
+ }
+ else
+ {
+ var ids = activeDoc.Objects.Select(o => o.Id).ToList();
+ foreach (var id in ids) { activeDoc.Objects.Delete(id, true); deleted++; }
+ }
+ activeDoc.Views.Redraw();
+ return JsonSerializer.Serialize(new { success = true, data = new { deleted } });
+ }
+
+ case "set_view":
+ {
+ var view = root.TryGetProperty("view", out var vEl) ? vEl.GetString() : "perspective";
+ var vp = activeDoc.Views.ActiveView?.ActiveViewport;
+ if (vp == null) throw new Exception("No active viewport");
+
+ switch (view.ToLower())
+ {
+ case "top":
+ vp.SetCameraLocations(new Point3d(0, 0, 100), new Point3d(0, 0, 0));
+ vp.CameraUp = Vector3d.YAxis;
+ vp.ChangeToParallelProjection(true);
+ break;
+ case "front":
+ vp.SetCameraLocations(new Point3d(0, -100, 0), new Point3d(0, 0, 0));
+ vp.CameraUp = Vector3d.ZAxis;
+ vp.ChangeToParallelProjection(true);
+ break;
+ case "right":
+ vp.SetCameraLocations(new Point3d(100, 0, 0), new Point3d(0, 0, 0));
+ vp.CameraUp = Vector3d.ZAxis;
+ vp.ChangeToParallelProjection(true);
+ break;
+ case "perspective":
+ default:
+ vp.ChangeToPerspectiveProjection(true, 50);
+ break;
+ case "rendered":
+ RhinoApp.RunScript("_SetDisplayMode _Rendered", false);
+ break;
+ case "arctic":
+ RhinoApp.RunScript("_SetDisplayMode _Arctic", false);
+ break;
+ }
+ activeDoc.Views.Redraw();
+ return JsonSerializer.Serialize(new { success = true, data = new { view } });
+ }
+
+ case "create_box":
+ {
+ double sc = RhinoMath.UnitScale(UnitSystem.Meters, activeDoc.ModelUnitSystem);
+ var minArr = root.GetProperty("min_pt");
+ var maxArr = root.GetProperty("max_pt");
+ var min = new Point3d(minArr[0].GetDouble() * sc, minArr[1].GetDouble() * sc, minArr[2].GetDouble() * sc);
+ var max = new Point3d(maxArr[0].GetDouble() * sc, maxArr[1].GetDouble() * sc, maxArr[2].GetDouble() * sc);
+ var box = new Box(new BoundingBox(min, max));
+ var brep = box.ToBrep();
+ var attr = BuildAttr(root, activeDoc);
+ var id = activeDoc.Objects.AddBrep(brep, attr);
+ activeDoc.Views.Redraw();
+ return JsonSerializer.Serialize(new { success = true, data = new { id = id.ToString() } });
+ }
+
+ case "create_sphere":
+ {
+ double sc = RhinoMath.UnitScale(UnitSystem.Meters, activeDoc.ModelUnitSystem);
+ var cArr = root.GetProperty("center");
+ var center = new Point3d(cArr[0].GetDouble() * sc, cArr[1].GetDouble() * sc, cArr[2].GetDouble() * sc);
+ double radius = root.GetProperty("radius").GetDouble() * sc;
+ var sphere = new Sphere(center, radius);
+ var attr = BuildAttr(root, activeDoc);
+ var id = activeDoc.Objects.AddBrep(sphere.ToBrep(), attr);
+ activeDoc.Views.Redraw();
+ return JsonSerializer.Serialize(new { success = true, data = new { id = id.ToString() } });
+ }
+
+ case "create_cylinder":
+ {
+ double sc = RhinoMath.UnitScale(UnitSystem.Meters, activeDoc.ModelUnitSystem);
+ var bArr = root.GetProperty("base");
+ var basePt = new Point3d(bArr[0].GetDouble() * sc, bArr[1].GetDouble() * sc, bArr[2].GetDouble() * sc);
+ double height = root.GetProperty("height").GetDouble() * sc;
+ double radius = root.GetProperty("radius").GetDouble() * sc;
+ var circle = new Circle(new Plane(basePt, Vector3d.ZAxis), radius);
+ var cyl = new Cylinder(circle, height);
+ var attr = BuildAttr(root, activeDoc);
+ var id = activeDoc.Objects.AddBrep(cyl.ToBrep(true, true), attr);
+ activeDoc.Views.Redraw();
+ return JsonSerializer.Serialize(new { success = true, data = new { id = id.ToString() } });
+ }
+
+ case "boolean_union":
+ {
+ var idsEl = root.GetProperty("ids");
+ var breps = new List<Brep>();
+ foreach (var idEl in idsEl.EnumerateArray())
+ {
+ var obj = activeDoc.Objects.FindId(Guid.Parse(idEl.GetString()));
+ if (obj?.Geometry is Brep b) breps.Add(b);
+ }
+ var results = Brep.CreateBooleanUnion(breps, activeDoc.ModelAbsoluteTolerance);
+ if (results == null || results.Length == 0) throw new Exception("Boolean union failed");
+ var attr = BuildAttr(root, activeDoc);
+ var resultIds = results.Select(r => activeDoc.Objects.AddBrep(r, attr).ToString()).ToList();
+ // Remove inputs
+ foreach (var idEl in root.GetProperty("ids").EnumerateArray())
+ activeDoc.Objects.Delete(Guid.Parse(idEl.GetString()), true);
+ activeDoc.Views.Redraw();
+ return JsonSerializer.Serialize(new { success = true, data = new { ids = resultIds } });
+ }
+
+ case "boolean_difference":
+ {
+ var baseObj = activeDoc.Objects.FindId(Guid.Parse(root.GetProperty("base_id").GetString()));
+ if (baseObj?.Geometry is not Brep baseBrep) throw new Exception("base_id not a Brep");
+ var cutters = new List<Brep>();
+ foreach (var idEl in root.GetProperty("cutter_ids").EnumerateArray())
+ {
+ var obj = activeDoc.Objects.FindId(Guid.Parse(idEl.GetString()));
+ if (obj?.Geometry is Brep b) cutters.Add(b);
+ }
+ var results = Brep.CreateBooleanDifference(
+ new[] { baseBrep }, cutters, activeDoc.ModelAbsoluteTolerance);
+ if (results == null || results.Length == 0) throw new Exception("Boolean difference failed");
+ var attr = BuildAttr(root, activeDoc);
+ var resultIds = results.Select(r => activeDoc.Objects.AddBrep(r, attr).ToString()).ToList();
+ activeDoc.Objects.Delete(baseObj.Id, true);
+ foreach (var idEl in root.GetProperty("cutter_ids").EnumerateArray())
+ activeDoc.Objects.Delete(Guid.Parse(idEl.GetString()), true);
+ activeDoc.Views.Redraw();
+ return JsonSerializer.Serialize(new { success = true, data = new { ids = resultIds } });
+ }
+
+ case "set_material":
+ {
+ var mat = new Material();
+ if (root.TryGetProperty("name", out var nameEl)) mat.Name = nameEl.GetString();
+ if (root.TryGetProperty("color", out var colorEl))
+ mat.DiffuseColor = Color.FromArgb(colorEl[0].GetInt32(), colorEl[1].GetInt32(), colorEl[2].GetInt32());
+ if (root.TryGetProperty("transparency", out var transEl)) mat.Transparency = transEl.GetDouble();
+ if (root.TryGetProperty("reflectivity", out var reflEl)) mat.Reflectivity = reflEl.GetDouble();
+ mat.FresnelReflections = true;
+ int matIdx = activeDoc.Materials.Add(mat);
+
+ var objAttr = new ObjectAttributes
+ {
+ MaterialIndex = matIdx,
+ MaterialSource = ObjectMaterialSource.MaterialFromObject
+ };
+
+ var targets = new List<Guid>();
+ if (root.TryGetProperty("ids", out var idsEl2))
+ foreach (var idEl in idsEl2.EnumerateArray())
+ targets.Add(Guid.Parse(idEl.GetString()));
+ else if (root.TryGetProperty("layer", out var lEl2))
+ {
+ var li = activeDoc.Layers.FindName(lEl2.GetString(), -1);
+ if (li != null)
+ targets.AddRange(activeDoc.Objects
+ .Where(o => o.Attributes.LayerIndex == li.Index)
+ .Select(o => o.Id));
+ }
+
+ int changed = 0;
+ foreach (var id in targets)
+ {
+ var obj = activeDoc.Objects.FindId(id);
+ if (obj == null) continue;
+ var a = obj.Attributes.Duplicate();
+ a.MaterialIndex = matIdx;
+ a.MaterialSource = ObjectMaterialSource.MaterialFromObject;
+ activeDoc.Objects.ModifyAttributes(obj, a, true);
+ changed++;
+ }
+ activeDoc.Views.Redraw();
+ return JsonSerializer.Serialize(new { success = true, data = new { changed, materialIndex = matIdx } });
+ }
+
+ case "transform_objects":
+ {
+ var ids = root.GetProperty("ids").EnumerateArray()
+ .Select(e => Guid.Parse(e.GetString())).ToList();
+ double sc = RhinoMath.UnitScale(UnitSystem.Meters, activeDoc.ModelUnitSystem);
+
+ Transform xform = Transform.Identity;
+ if (root.TryGetProperty("translation", out var tEl))
+ {
+ xform = Transform.Translation(
+ tEl[0].GetDouble() * sc,
+ tEl[1].GetDouble() * sc,
+ tEl[2].GetDouble() * sc);
+ }
+ else if (root.TryGetProperty("rotation", out var rEl))
+ {
+ var axis = new Vector3d(rEl.GetProperty("axis")[0].GetDouble(),
+ rEl.GetProperty("axis")[1].GetDouble(),
+ rEl.GetProperty("axis")[2].GetDouble());
+ double deg = rEl.GetProperty("angle_deg").GetDouble();
+ Point3d origin = Point3d.Origin;
+ if (rEl.TryGetProperty("origin", out var oEl))
+ origin = new Point3d(oEl[0].GetDouble() * sc, oEl[1].GetDouble() * sc, oEl[2].GetDouble() * sc);
+ xform = Transform.Rotation(RhinoMath.ToRadians(deg), axis, origin);
+ }
+ else if (root.TryGetProperty("scale", out var sEl))
+ {
+ xform = Transform.Scale(Point3d.Origin,
+ (sEl[0].GetDouble() + sEl[1].GetDouble() + sEl[2].GetDouble()) / 3.0);
+ }
+
+ int moved = 0;
+ foreach (var id in ids)
+ {
+ if (activeDoc.Objects.Transform(id, xform, true) != Guid.Empty) moved++;
+ }
+ activeDoc.Views.Redraw();
+ return JsonSerializer.Serialize(new { success = true, data = new { moved } });
+ }
+
+ default:
+ return JsonSerializer.Serialize(new { error = $"Unknown command: {command}" });
+ }
+ }
+ catch (Exception ex)
+ {
+ return JsonSerializer.Serialize(new { error = ex.Message, stackTrace = ex.StackTrace });
+ }
+ }
+
+ // ── Material helpers ──────────────────────────────────────────────────────
+
+ private static int CreateAluminumMaterial(RhinoDoc doc)
+ {
+ var mat = new Material { Name = "DarkAnodizedAluminum" };
+ try
+ {
+ mat.ToPhysicallyBased(); // void in Rhino 7, bool in Rhino 8 — just call it
+ var pbr = mat.PhysicallyBased;
+ pbr.BaseColor = new Rhino.Display.Color4f(0.035f, 0.038f, 0.046f, 1.0f);
+ pbr.Metallic = 0.95;
+ pbr.Roughness = 0.22;
+ // "Reflectance" in Rhino 8, "Specular" in Rhino 7 — try both via reflection
+ SetPbrProperty(pbr, 0.85, "Reflectance", "Specular");
+ }
+ catch { /* no PBR support in this build — standard props used below */ }
+
+ // Standard props: always set so the material looks correct in all display modes
+ mat.DiffuseColor = Color.FromArgb(30, 32, 38);
+ mat.SpecularColor = Color.FromArgb(155, 160, 170);
+ mat.Reflectivity = 0.85;
+ mat.FresnelReflections = true;
+ mat.Shine = (int)(0.65 * Material.MaxShine);
+ return doc.Materials.Add(mat);
+ }
+
+ private static int CreateGlassMaterial(RhinoDoc doc)
+ {
+ var mat = new Material { Name = "ArchitecturalGlass_PBR" };
+ try
+ {
+ mat.ToPhysicallyBased();
+ var pbr = mat.PhysicallyBased;
+ pbr.BaseColor = new Rhino.Display.Color4f(0.030f, 0.160f, 0.090f, 1.0f);
+ pbr.Metallic = 0.0;
+ pbr.Roughness = 0.02;
+ pbr.Opacity = 0.12; // 88% transparent
+ SetPbrProperty(pbr, 0.92, "Reflectance", "Specular");
+ SetPbrProperty(pbr, 1.52, "OpacityIOR"); // Rhino 8+ only; silently skipped on Rhino 7
+ }
+ catch { /* fall through */ }
+
+ // Standard fallback properties — always set for Shaded/Arctic/non-PBR display modes
+ mat.DiffuseColor = Color.FromArgb(18, 75, 52);
+ mat.Transparency = 0.85;
+ mat.Reflectivity = 0.92;
+ mat.FresnelReflections = true;
+ mat.IndexOfRefraction = 1.52;
+ return doc.Materials.Add(mat);
+ }
+
+ // Tries each candidate property name in order; silently ignores missing ones.
+ // Using reflection means we compile against Rhino 7 SDK but benefit from Rhino 8 PBR props at runtime.
+ private static void SetPbrProperty(object pbr, object value, params string[] candidateNames)
+ {
+ foreach (var name in candidateNames)
+ {
+ try
+ {
+ var prop = pbr.GetType().GetProperty(name);
+ if (prop == null) continue;
+ // PhysicallyBasedMaterial is a class, so SetValue modifies the actual instance
+ prop.SetValue(pbr, Convert.ChangeType(value, prop.PropertyType));
+ return;
+ }
+ catch { }
+ }
+ }
+
+ private static int GetOrCreateLayer(RhinoDoc doc, string name, Color color)
+ {
+ var existing = doc.Layers.FindName(name, -1);
+ if (existing != null) return existing.Index;
+ var layer = new Layer { Name = name, Color = color };
+ return doc.Layers.Add(layer);
+ }
+
+ // Builds ObjectAttributes from optional "layer" and "color" keys in the request.
+ private static ObjectAttributes BuildAttr(JsonElement root, RhinoDoc doc)
+ {
+ var attr = new ObjectAttributes();
+ if (root.TryGetProperty("layer", out var lEl))
+ attr.LayerIndex = GetOrCreateLayer(doc, lEl.GetString(), Color.White);
+ if (root.TryGetProperty("color", out var cEl))
+ {
+ var mat = new Material
+ {
+ DiffuseColor = Color.FromArgb(cEl[0].GetInt32(), cEl[1].GetInt32(), cEl[2].GetInt32())
+ };
+ attr.MaterialIndex = doc.Materials.Add(mat);
+ attr.MaterialSource = ObjectMaterialSource.MaterialFromObject;
+ }
+ return attr;
+ }
+ }
+}
diff --git a/packages/rhino-bridge-addin/src/BridgeServer.cs b/packages/rhino-bridge-addin/src/BridgeServer.cs
new file mode 100644
index 0000000..4645522
--- /dev/null
+++ b/packages/rhino-bridge-addin/src/BridgeServer.cs
@@ -0,0 +1,140 @@
+using System;
+using System.IO;
+using System.Net;
+using System.Text;
+using System.Text.Json;
+using System.Threading;
+using System.Threading.Tasks;
+using Rhino;
+
+namespace RhinoBridge
+{
+ public class BridgeServer
+ {
+ private readonly HttpListener _listener;
+ private CancellationTokenSource _cts = new();
+ private Task? _listenerTask;
+
+ public BridgeServer(int port)
+ {
+ Port = port;
+ _listener = new HttpListener();
+ _listener.Prefixes.Add($"http://127.0.0.1:{Port}/");
+ _listener.Prefixes.Add($"http://localhost:{Port}/");
+ }
+
+ public int Port { get; private set; }
+ public bool IsListening { get; private set; }
+
+ public void Start()
+ {
+ if (IsListening) return;
+ try
+ {
+ _listener.Start();
+ IsListening = true;
+ _cts = new CancellationTokenSource();
+ _listenerTask = Task.Run(() => ListenLoop(_cts.Token));
+ }
+ catch (Exception ex)
+ {
+ RhinoApp.WriteLine($"Failed to start HTTP listener on port {Port}: {ex.Message}");
+ }
+ }
+
+ public void Stop()
+ {
+ if (!IsListening) return;
+ IsListening = false;
+ _cts.Cancel();
+ _listener.Stop();
+ try { _listenerTask?.Wait(2000); } catch { }
+ }
+
+ private async Task ListenLoop(CancellationToken token)
+ {
+ while (!token.IsCancellationRequested && _listener.IsListening)
+ {
+ try
+ {
+ var context = await _listener.GetContextAsync().ConfigureAwait(false);
+ _ = Task.Run(() => HandleRequestAsync(context), token);
+ }
+ catch (HttpListenerException) { break; }
+ catch (OperationCanceledException) { break; }
+ catch (Exception) { /* log error */ }
+ }
+ }
+
+ private async Task HandleRequestAsync(HttpListenerContext context)
+ {
+ var request = context.Request;
+ var response = context.Response;
+
+ // CORS headers
+ response.Headers.Add("Access-Control-Allow-Origin", "*");
+ response.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
+ response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
+
+ if (request.HttpMethod == "OPTIONS")
+ {
+ response.StatusCode = 200;
+ response.Close();
+ return;
+ }
+
+ try
+ {
+ string resultJson;
+
+ if (request.Url?.AbsolutePath == "/health" && request.HttpMethod == "GET")
+ {
+ resultJson = JsonSerializer.Serialize(new { status = "healthy", bridge = "Rhino Bridge Addin", port = Port });
+ }
+ else if (request.Url?.AbsolutePath == "/execute" && request.HttpMethod == "POST")
+ {
+ using var reader = new StreamReader(request.InputStream, request.ContentEncoding ?? Encoding.UTF8);
+ var body = await reader.ReadToEndAsync();
+
+ var tcs = new TaskCompletionSource<string>();
+
+ // Execute on Rhino main thread
+ RhinoApp.InvokeOnUiThread((Action)(() =>
+ {
+ try
+ {
+ var result = BridgeCommands.ExecuteCommand(body);
+ tcs.SetResult(result);
+ }
+ catch (Exception ex)
+ {
+ tcs.SetException(ex);
+ }
+ }));
+
+ resultJson = await tcs.Task;
+ }
+ else
+ {
+ response.StatusCode = 404;
+ resultJson = JsonSerializer.Serialize(new { error = "Not found" });
+ }
+
+ var buffer = Encoding.UTF8.GetBytes(resultJson);
+ response.ContentType = "application/json";
+ response.ContentLength64 = buffer.Length;
+ await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
+ }
+ catch (Exception ex)
+ {
+ response.StatusCode = 500;
+ var errBuffer = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { error = ex.Message }));
+ try { await response.OutputStream.WriteAsync(errBuffer, 0, errBuffer.Length); } catch { }
+ }
+ finally
+ {
+ response.Close();
+ }
+ }
+ }
+}
diff --git a/packages/rhino-bridge-addin/src/CurtainWallDetailer.cs b/packages/rhino-bridge-addin/src/CurtainWallDetailer.cs
new file mode 100644
index 0000000..433401e
--- /dev/null
+++ b/packages/rhino-bridge-addin/src/CurtainWallDetailer.cs
@@ -0,0 +1,153 @@
+using System;
+using System.Collections.Generic;
+using Rhino.Geometry;
+
+namespace RhinoBridge
+{
+ public static class CurtainWallDetailer
+ {
+ public static Curve CreateMullionCurve(double width = 0.15, double depth = 0.30, double scale = 1.0)
+ {
+ double hw = width * scale * 0.5;
+ double d = depth * scale;
+ var rect = new Rectangle3d(Plane.WorldXY, new Interval(-hw, hw), new Interval(-d, 0.0));
+ return rect.ToNurbsCurve();
+ }
+
+ public static List<Brep> GenerateMullionSweeps(
+ List<Curve> lines, Curve profileCurve, BrepFace face, double tolerance = 0.001)
+ {
+ var sweeps = new List<Brep>();
+ foreach (var line in lines)
+ {
+ if (!line.PerpendicularFrameAt(line.Domain.Min, out Plane startFrame))
+ continue;
+
+ var midPt = line.PointAt(line.Domain.Mid);
+ if (!face.ClosestPoint(midPt, out double cu, out double cv))
+ {
+ var xf = Transform.PlaneToPlane(Plane.WorldXY, startFrame);
+ var pf = profileCurve.DuplicateCurve(); pf.Transform(xf);
+ var fb = Brep.CreateFromSweep(line, pf, true, tolerance);
+ if (fb != null) sweeps.AddRange(fb);
+ continue;
+ }
+
+ var surfNormal = face.NormalAt(cu, cv); surfNormal.Unitize();
+ var tangent = startFrame.ZAxis;
+
+ double dot = surfNormal * tangent;
+ var depthDir = new Vector3d(
+ surfNormal.X - dot * tangent.X,
+ surfNormal.Y - dot * tangent.Y,
+ surfNormal.Z - dot * tangent.Z);
+ if (depthDir.IsZero || !depthDir.Unitize()) depthDir = startFrame.YAxis;
+
+ var widthDir = Vector3d.CrossProduct(tangent, depthDir);
+ if (widthDir.IsZero || !widthDir.Unitize()) widthDir = startFrame.XAxis;
+
+ var sweepPlane = new Plane(startFrame.Origin, widthDir, depthDir);
+ var xform = Transform.PlaneToPlane(Plane.WorldXY, sweepPlane);
+ var oriented = profileCurve.DuplicateCurve(); oriented.Transform(xform);
+
+ var result = Brep.CreateFromSweep(line, oriented, true, tolerance);
+ if (result != null) sweeps.AddRange(result);
+ }
+ return sweeps;
+ }
+
+ // Glass strategy: each rectangular UV cell is divided into 4 triangles by the X of the
+ // two crossing diagonal mullions. Each triangle has vertices at:
+ // - the X crossing point (cell centre, where the two mullions intersect)
+ // - two adjacent UV grid corners (where 4 mullions from neighbouring cells meet)
+ //
+ // The glass triangle is inset from all 3 vertices toward its own centroid so it clears
+ // the mullion profile widths, then extruded inward along the surface normal.
+ public static List<Brep> GenerateGlassPanels(
+ Point3d[,] pts, BrepFace face, int uDivs, int vDivs,
+ double thickness = 0.024,
+ double insetRatio = 0.12, // pull each vertex 12 % toward triangle centroid
+ double setback = 0.020,
+ double scale = 1.0)
+ {
+ double tol = 0.001 * scale;
+ var panels = new List<Brep>();
+
+ for (int i = 0; i < uDivs; i++)
+ {
+ for (int j = 0; j < vDivs; j++)
+ {
+ var p0 = pts[i, j ]; // bottom-left
+ var p1 = pts[i + 1, j ]; // bottom-right
+ var p2 = pts[i + 1, j + 1]; // top-right
+ var p3 = pts[i, j + 1]; // top-left
+
+ // Cell centre = where the two diagonal mullions cross
+ var cx = new Point3d(
+ (p0.X + p1.X + p2.X + p3.X) * 0.25,
+ (p0.Y + p1.Y + p2.Y + p3.Y) * 0.25,
+ (p0.Z + p1.Z + p2.Z + p3.Z) * 0.25);
+
+ // The X splits the cell into 4 triangles.
+ // Winding: counter-clockwise when viewed from outside.
+ var tris = new[]
+ {
+ new[] { p0, p1, cx }, // bottom
+ new[] { p1, p2, cx }, // right
+ new[] { p2, p3, cx }, // top
+ new[] { p3, p0, cx }, // left
+ };
+
+ foreach (var tri in tris)
+ {
+ var A = tri[0]; var B = tri[1]; var C = tri[2];
+
+ // Triangle centroid
+ var tc = new Point3d(
+ (A.X + B.X + C.X) / 3.0,
+ (A.Y + B.Y + C.Y) / 3.0,
+ (A.Z + B.Z + C.Z) / 3.0);
+
+ // Inset each vertex toward centroid to clear mullion profiles
+ var gA = tc + (A - tc) * (1.0 - insetRatio);
+ var gB = tc + (B - tc) * (1.0 - insetRatio);
+ var gC = tc + (C - tc) * (1.0 - insetRatio);
+
+ // Surface normal at centroid for setback + thickness direction
+ if (!face.ClosestPoint(tc, out double cu, out double cv)) continue;
+ var n = face.NormalAt(cu, cv);
+ if (!n.Unitize()) continue;
+
+ var push = n * (-setback * scale);
+ var thick = n * (-thickness * scale);
+
+ // Outer (front) triangle face — set back slightly behind mullion plane
+ var fA = gA + push; var fB = gB + push; var fC = gC + push;
+ // Inner (back) face — extruded by glass thickness
+ var bA = fA + thick; var bB = fB + thick; var bC = fC + thick;
+
+ // 5-face triangular prism
+ var front = NurbsSurface.CreateFromCorners(fA, fB, fC); // outer face
+ var back = NurbsSurface.CreateFromCorners(bA, bC, bB); // inner face (reversed)
+ var s1 = NurbsSurface.CreateFromCorners(fA, fB, bB, bA); // side A-B
+ var s2 = NurbsSurface.CreateFromCorners(fB, fC, bC, bB); // side B-C
+ var s3 = NurbsSurface.CreateFromCorners(fC, fA, bA, bC); // side C-A
+
+ var faces = new List<Brep>();
+ foreach (var ns in new[] { front, back, s1, s2, s3 })
+ if (ns != null) faces.Add(ns.ToBrep());
+
+ if (faces.Count < 5) continue;
+
+ var joined = Brep.JoinBreps(faces, tol);
+ if (joined != null && joined.Length > 0)
+ panels.Add(joined[0]);
+ else
+ panels.AddRange(faces);
+ }
+ }
+ }
+ return panels;
+ }
+ }
+}
diff --git a/packages/rhino-bridge-addin/src/DiagridGenerator.cs b/packages/rhino-bridge-addin/src/DiagridGenerator.cs
new file mode 100644
index 0000000..b1b92cc
--- /dev/null
+++ b/packages/rhino-bridge-addin/src/DiagridGenerator.cs
@@ -0,0 +1,92 @@
+using System;
+using System.Collections.Generic;
+using Rhino.Geometry;
+
+namespace RhinoBridge
+{
+ public static class DiagridGenerator
+ {
+ public static Brep GenerateTowerSurface(double baseRadius, double waistRadius, double topRadius, double height)
+ {
+ // 11 rings give a smooth hyperboloid — enough for cubic-eased curvature without control-point noise
+ int rings = 11;
+ var crvs = new List<Curve>();
+ for (int i = 0; i <= rings; i++)
+ {
+ double t = (double)i / rings;
+ double r = SmoothRadius(baseRadius, waistRadius, topRadius, t);
+ double z = t * height;
+ var circle = new Circle(new Plane(new Point3d(0, 0, z), Vector3d.ZAxis), r);
+ crvs.Add(circle.ToNurbsCurve());
+ }
+
+ var breps = Brep.CreateFromLoft(crvs, Point3d.Unset, Point3d.Unset, LoftType.Normal, false);
+ return breps != null && breps.Length > 0 ? breps[0] : null;
+ }
+
+ // Smoothstep between a→b (first half) and b→c (second half)
+ private static double SmoothRadius(double a, double b, double c, double t)
+ {
+ if (t <= 0.5)
+ {
+ double s = t * 2.0;
+ return a + (b - a) * (s * s * (3.0 - 2.0 * s));
+ }
+ else
+ {
+ double s = (t - 0.5) * 2.0;
+ return b + (c - b) * (s * s * (3.0 - 2.0 * s));
+ }
+ }
+
+ // Pre-compute the UV grid so generators can share the same point array.
+ public static Point3d[,] SampleGridPoints(BrepFace face, int uDivs, int vDivs)
+ {
+ face.SetDomain(0, new Interval(0, 1));
+ face.SetDomain(1, new Interval(0, 1));
+
+ var pts = new Point3d[uDivs + 1, vDivs + 1];
+ for (int i = 0; i <= uDivs; i++)
+ {
+ double u = (double)i / uDivs;
+ for (int j = 0; j <= vDivs; j++)
+ {
+ double v = (double)j / vDivs;
+ pts[i, j] = face.PointAt(u, v);
+ }
+ }
+ return pts;
+ }
+
+ public static List<Curve> GenerateDiagridLines(Point3d[,] pts, int uDivs, int vDivs)
+ {
+ var lines = new List<Curve>();
+ for (int i = 0; i < uDivs; i++)
+ {
+ for (int j = 0; j < vDivs; j++)
+ {
+ lines.Add(new LineCurve(pts[i, j], pts[i + 1, j + 1]));
+ lines.Add(new LineCurve(pts[i + 1, j], pts[i, j + 1]));
+ }
+ }
+ return lines;
+ }
+
+ // Quad panel boundaries — used for reference; glass panels are built directly from pts.
+ public static List<Curve> GeneratePanels(Point3d[,] pts, int uDivs, int vDivs)
+ {
+ var panels = new List<Curve>();
+ for (int i = 0; i < uDivs; i++)
+ {
+ for (int j = 0; j < vDivs; j++)
+ {
+ var p1 = pts[i, j]; var p2 = pts[i + 1, j];
+ var p3 = pts[i + 1, j + 1]; var p4 = pts[i, j + 1];
+ var quad = new Polyline(new[] { p1, p2, p3, p4, p1 });
+ panels.Add(quad.ToNurbsCurve());
+ }
+ }
+ return panels;
+ }
+ }
+}
diff --git a/packages/rhino-bridge-addin/src/GenerateDiagridTowerCommand.cs b/packages/rhino-bridge-addin/src/GenerateDiagridTowerCommand.cs
new file mode 100644
index 0000000..e0e452e
--- /dev/null
+++ b/packages/rhino-bridge-addin/src/GenerateDiagridTowerCommand.cs
@@ -0,0 +1,98 @@
+using System;
+using System.Drawing;
+using Rhino;
+using Rhino.Commands;
+using Rhino.Geometry;
+using Rhino.DocObjects;
+
+namespace RhinoBridge
+{
+ public class GenerateDiagridTowerCommand : Command
+ {
+ public GenerateDiagridTowerCommand() { Instance = this; }
+
+ public static GenerateDiagridTowerCommand Instance { get; private set; }
+
+ public override string EnglishName => "generate_diagrid_tower";
+
+ protected override Result RunCommand(RhinoDoc doc, RunMode mode)
+ {
+ double scale = RhinoMath.UnitScale(UnitSystem.Meters, doc.ModelUnitSystem);
+
+ double baseRad = 22.0 * scale;
+ double waistRad = 14.0 * scale;
+ double topRad = 19.0 * scale;
+ double height = 180.0 * scale;
+ int uDivs = 16;
+ int vDivs = 28;
+ double mullionW = 0.15;
+ double mullionD = 0.30;
+ double glassThick = 0.024;
+
+ RhinoApp.WriteLine("Generating tower surface...");
+ var surface = DiagridGenerator.GenerateTowerSurface(baseRad, waistRad, topRad, height);
+ if (surface == null) { RhinoApp.WriteLine("Failed to generate surface."); return Result.Failure; }
+
+ var face = surface.Faces[0];
+ var pts = DiagridGenerator.SampleGridPoints(face, uDivs, vDivs);
+
+ RhinoApp.WriteLine("Computing diagrid topology...");
+ var diagridLines = DiagridGenerator.GenerateDiagridLines(pts, uDivs, vDivs);
+
+ RhinoApp.WriteLine("Sweeping mullion profiles...");
+ var profile = CurtainWallDetailer.CreateMullionCurve(mullionW, mullionD, scale);
+ var mullions = CurtainWallDetailer.GenerateMullionSweeps(diagridLines, profile, face);
+
+ RhinoApp.WriteLine("Generating volumetric glass panels...");
+ var glassPanels = CurtainWallDetailer.GenerateGlassPanels(pts, face, uDivs, vDivs, glassThick, 0.12, 0.02, scale);
+
+ // Materials
+ var aluminumMat = new Material { Name = "DarkAnodizedAluminum" };
+ aluminumMat.DiffuseColor = Color.FromArgb(30, 32, 38);
+ aluminumMat.SpecularColor = Color.FromArgb(155, 160, 170);
+ aluminumMat.Reflectivity = 0.85;
+ aluminumMat.FresnelReflections = true;
+ int aluminumMatIdx = doc.Materials.Add(aluminumMat);
+
+ var glassMat = new Material { Name = "ArchitecturalGlass" };
+ glassMat.DiffuseColor = Color.FromArgb(18, 75, 52);
+ glassMat.Transparency = 0.85;
+ glassMat.Reflectivity = 0.92;
+ glassMat.FresnelReflections = true;
+ glassMat.IndexOfRefraction = 1.52;
+ int glassMatIdx = doc.Materials.Add(glassMat);
+
+ // Layers
+ int mullionLayerIdx = GetOrCreateLayer(doc, "Mullions", Color.FromArgb(38, 40, 48));
+ int glassLayerIdx = GetOrCreateLayer(doc, "Glass", Color.FromArgb(18, 75, 52));
+
+ var mullionAttr = new ObjectAttributes
+ {
+ LayerIndex = mullionLayerIdx, MaterialIndex = aluminumMatIdx,
+ MaterialSource = ObjectMaterialSource.MaterialFromObject
+ };
+ var glassAttr = new ObjectAttributes
+ {
+ LayerIndex = glassLayerIdx, MaterialIndex = glassMatIdx,
+ MaterialSource = ObjectMaterialSource.MaterialFromObject
+ };
+
+ RhinoApp.WriteLine($"Baking {mullions.Count} mullion sweeps...");
+ foreach (var m in mullions) doc.Objects.AddBrep(m, mullionAttr);
+
+ RhinoApp.WriteLine($"Baking {glassPanels.Count} glass panels...");
+ foreach (var g in glassPanels) doc.Objects.AddBrep(g, glassAttr);
+
+ doc.Views.Redraw();
+ RhinoApp.WriteLine("High-fidelity diagrid tower complete!");
+ return Result.Success;
+ }
+
+ private static int GetOrCreateLayer(RhinoDoc doc, string name, Color color)
+ {
+ var existing = doc.Layers.FindName(name, -1);
+ if (existing != null) return existing.Index;
+ return doc.Layers.Add(new Layer { Name = name, Color = color });
+ }
+ }
+}
diff --git a/packages/rhino-bridge-addin/src/ReflectionHelper.cs b/packages/rhino-bridge-addin/src/ReflectionHelper.cs
new file mode 100644
index 0000000..624aeac
--- /dev/null
+++ b/packages/rhino-bridge-addin/src/ReflectionHelper.cs
@@ -0,0 +1,182 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Text.Json;
+using Rhino;
+using Rhino.DocObjects;
+
+namespace RhinoBridge
+{
+ public static class ReflectionHelper
+ {
+ private static Dictionary<string, object> _objectRegistry = new Dictionary<string, object>();
+ private static int _objectIdCounter = 0;
+
+ public static string RegisterObject(object obj)
+ {
+ if (obj == null) return null;
+ if (obj is RhinoObject elem) return elem.Id.ToString();
+
+ string id = $"obj_{++_objectIdCounter}";
+ _objectRegistry[id] = obj;
+ return id;
+ }
+
+ public static object GetObject(string id, RhinoDoc doc)
+ {
+ if (string.IsNullOrEmpty(id)) return null;
+
+ if (_objectRegistry.ContainsKey(id)) return _objectRegistry[id];
+
+ if (Guid.TryParse(id, out Guid guid))
+ {
+ return doc.Objects.FindId(guid);
+ }
+
+ return null;
+ }
+
+ public static void ClearRegistry()
+ {
+ _objectRegistry.Clear();
+ _objectIdCounter = 0;
+ }
+
+ public static object ParseArgument(JsonElement arg, RhinoDoc doc)
+ {
+ switch (arg.ValueKind)
+ {
+ case JsonValueKind.String:
+ return arg.GetString();
+ case JsonValueKind.Number:
+ if (arg.TryGetInt32(out int i)) return i;
+ return arg.GetDouble();
+ case JsonValueKind.True: return true;
+ case JsonValueKind.False: return false;
+ case JsonValueKind.Null: return null;
+ case JsonValueKind.Object:
+ if (arg.TryGetProperty("type", out var typeProp) && typeProp.GetString() == "reference")
+ {
+ return GetObject(arg.GetProperty("id").GetString(), doc);
+ }
+ if (arg.TryGetProperty("x", out _) && arg.TryGetProperty("y", out _) && arg.TryGetProperty("z", out _))
+ {
+ return new Rhino.Geometry.Point3d(arg.GetProperty("x").GetDouble(), arg.GetProperty("y").GetDouble(), arg.GetProperty("z").GetDouble());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ public static Type ResolveType(string typeName)
+ {
+ if (typeName == "int" || typeName == "System.Int32") return typeof(int);
+ if (typeName == "double" || typeName == "System.Double") return typeof(double);
+ if (typeName == "string" || typeName == "System.String") return typeof(string);
+ if (typeName == "bool" || typeName == "System.Boolean") return typeof(bool);
+
+ var assemblies = AppDomain.CurrentDomain.GetAssemblies()
+ .Where(a => a.FullName.StartsWith("RhinoCommon") || a.FullName.StartsWith("System"));
+
+ foreach (var asm in assemblies)
+ {
+ var type = asm.GetType(typeName) ?? asm.GetType("Rhino." + typeName) ?? asm.GetType("Rhino.Geometry." + typeName) ?? asm.GetType("Rhino.DocObjects." + typeName);
+ if (type != null) return type;
+ }
+
+ return null;
+ }
+
+ public static object InvokeMethod(RhinoDoc doc, string typeName, string methodName, JsonElement argsElement, string targetId = null)
+ {
+ Type type = ResolveType(typeName);
+ if (type == null) throw new Exception($"Type '{typeName}' not found.");
+
+ object target = null;
+ if (!string.IsNullOrEmpty(targetId))
+ {
+ target = GetObject(targetId, doc);
+ if (target == null) throw new Exception($"Target object '{targetId}' not found.");
+ }
+
+ List<object> args = new List<object>();
+ if (argsElement.ValueKind == JsonValueKind.Array)
+ {
+ foreach (var argJson in argsElement.EnumerateArray())
+ {
+ args.Add(ParseArgument(argJson, doc));
+ }
+ }
+
+ if (methodName == "new" || methodName == "ctor")
+ {
+ var constructors = type.GetConstructors().Where(c => c.GetParameters().Length == args.Count).ToList();
+ if (constructors.Count == 0) throw new Exception($"Constructor with {args.Count} arguments not found on type '{type.Name}'.");
+
+ var ctor = constructors.First();
+ var ctorParams = ctor.GetParameters();
+ object[] ctorArgs = new object[args.Count];
+
+ for (int i = 0; i < args.Count; i++)
+ {
+ var targetType = ctorParams[i].ParameterType;
+ var val = args[i];
+
+ if (targetType.IsEnum)
+ {
+ if (val is string s) val = Enum.Parse(targetType, s);
+ else if (val is int n) val = Enum.ToObject(targetType, n);
+ }
+
+ if (val is IConvertible && !targetType.IsAssignableFrom(val.GetType()))
+ {
+ try { val = Convert.ChangeType(val, targetType); } catch {}
+ }
+ ctorArgs[i] = val;
+ }
+
+ object instance = ctor.Invoke(ctorArgs);
+ string regId = RegisterObject(instance);
+ return new { type = "reference", id = regId, class_name = instance.GetType().Name, str = instance.ToString() };
+ }
+
+ var flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;
+ var methods = type.GetMethods(flags).Where(m => m.Name == methodName && m.GetParameters().Length == args.Count).ToList();
+
+ if (methods.Count == 0) throw new Exception($"Method '{methodName}' with {args.Count} arguments not found on type '{type.Name}'.");
+
+ MethodInfo methodToInvoke = methods.First();
+ var parameters = methodToInvoke.GetParameters();
+ object[] finalArgs = new object[args.Count];
+ for (int i = 0; i < args.Count; i++)
+ {
+ var targetType = parameters[i].ParameterType;
+ var val = args[i];
+
+ if (targetType.IsEnum)
+ {
+ if (val is string s) val = Enum.Parse(targetType, s);
+ else if (val is int n) val = Enum.ToObject(targetType, n);
+ }
+
+ if (val is IConvertible && !targetType.IsAssignableFrom(val.GetType()))
+ {
+ try { val = Convert.ChangeType(val, targetType); } catch {}
+ }
+
+ finalArgs[i] = val;
+ }
+
+ object result = methodToInvoke.Invoke(target, finalArgs);
+
+ if (result == null) return null;
+ if (result is Guid guid) return guid.ToString();
+ if (result.GetType().IsPrimitive || result is string) return result;
+
+ string resultRegId = RegisterObject(result);
+ return new { type = "reference", id = resultRegId, class_name = result.GetType().Name, str = result.ToString() };
+ }
+ }
+}
diff --git a/packages/rhino-bridge-addin/src/RhinoBridgePlugIn.cs b/packages/rhino-bridge-addin/src/RhinoBridgePlugIn.cs
new file mode 100644
index 0000000..6129628
--- /dev/null
+++ b/packages/rhino-bridge-addin/src/RhinoBridgePlugIn.cs
@@ -0,0 +1,45 @@
+using System;
+using Rhino;
+using Rhino.PlugIns;
+
+namespace RhinoBridge
+{
+ public class RhinoBridgePlugIn : PlugIn
+ {
+ private BridgeServer? _server;
+
+ public RhinoBridgePlugIn()
+ {
+ Instance = this;
+ }
+
+ public static RhinoBridgePlugIn Instance { get; private set; }
+
+ protected override LoadReturnCode OnLoad(ref string errorMessage)
+ {
+ try
+ {
+ // Start the HTTP bridge on port 3004
+ _server = new BridgeServer(3004);
+ _server.Start();
+ RhinoApp.WriteLine($"AEC Model Bridge for Rhino started on port 3004.");
+ return LoadReturnCode.Success;
+ }
+ catch (Exception ex)
+ {
+ errorMessage = ex.Message;
+ return LoadReturnCode.ErrorNoDialog;
+ }
+ }
+
+ protected override void OnShutdown()
+ {
+ if (_server != null)
+ {
+ _server.Stop();
+ _server = null;
+ }
+ base.OnShutdown();
+ }
+ }
+}
diff --git a/scratch/diag.py b/scratch/diag.py
new file mode 100644
index 0000000..4ca3d56
--- /dev/null
+++ b/scratch/diag.py
@@ -0,0 +1,51 @@
+import scriptcontext as sc, Rhino, Rhino.Geometry as rg
+
+BASE_R=22.0; WAIST_R=13.5; TOP_R=19.0; HEIGHT=200.0
+U_DIVS=20; V_DIVS=36
+scale = Rhino.RhinoMath.UnitScale(Rhino.UnitSystem.Meters, sc.doc.ModelUnitSystem)
+
+def smooth_r(a,b,c,t):
+ if t<=0.5: s=t*2.0; return a+(b-a)*(s*s*(3-2*s))
+ s=(t-0.5)*2.0; return b+(c-b)*(s*s*(3-2*s))
+
+crvs=[]
+for i in range(12):
+ t=float(i)/11; r=smooth_r(BASE_R,WAIST_R,TOP_R,t)*scale; z=t*HEIGHT*scale
+ crvs.append(rg.Circle(rg.Plane(rg.Point3d(0,0,z),rg.Vector3d.ZAxis),r).ToNurbsCurve())
+breps=rg.Brep.CreateFromLoft(crvs,rg.Point3d.Unset,rg.Point3d.Unset,rg.LoftType.Normal,False)
+face=breps[0].Faces[0]
+face.SetDomain(0,rg.Interval(0,1)); face.SetDomain(1,rg.Interval(0,1))
+
+print("Brep faces:", breps[0].Faces.Count)
+p0=face.PointAt(0.0, 0.5)
+p1=face.PointAt(1.0, 0.5)
+print("PointAt(0,0.5): %.3f %.3f %.3f" % (p0.X, p0.Y, p0.Z))
+print("PointAt(1,0.5): %.3f %.3f %.3f" % (p1.X, p1.Y, p1.Z))
+print("U seam distance: %.4f" % p0.DistanceTo(p1))
+print("IsClosed U:", face.IsClosed(0))
+print("IsPeriodic U:", face.IsPeriodic(0))
+
+def gpt(i,j): return face.PointAt(float(i%U_DIVS)/U_DIVS, float(j)/V_DIVS)
+def cc(i,j): return face.PointAt(((i+0.5)/float(U_DIVS))%1.0, (j+0.5)/float(V_DIVS))
+
+import math
+cell_w = 2*math.pi*22*scale/U_DIVS
+print("Expected cell width ~: %.2f" % cell_w)
+
+# Check bounding box of each seam panel type
+print("--- TypeB seam panels (i=19) ---")
+for j in [0,17,35]:
+ A=cc(19,j); B=gpt(20,j); C=cc(0,j); D=gpt(20,j+1)
+ bb=rg.BoundingBox([A,B,C,D])
+ print(" j=%d diag=%.2f" % (j, bb.Diagonal.Length))
+
+print("--- TypeA seam panels (i=19) ---")
+for j in [0,17,34]:
+ A=cc(19,j); B=gpt(20,j+1); C=cc(19,j+1); D=gpt(19,j+1)
+ bb=rg.BoundingBox([A,B,C,D])
+ print(" j=%d diag=%.2f" % (j, bb.Diagonal.Length))
+
+print("--- Normal TypeB (i=10) ---")
+A=cc(10,18); B=gpt(11,18); C=cc(11,18); D=gpt(11,19)
+bb=rg.BoundingBox([A,B,C,D])
+print(" diag=%.2f" % bb.Diagonal.Length)
diff --git a/scratch/diagrid_tower_hd.py b/scratch/diagrid_tower_hd.py
new file mode 100644
index 0000000..005acfe
--- /dev/null
+++ b/scratch/diagrid_tower_hd.py
@@ -0,0 +1,106 @@
+"""
+High-fidelity diagrid skyscraper generator via Rhino MCP bridge.
+
+Sends a single command to http://127.0.0.1:3004/execute which triggers:
+ - Smooth hyperboloid tower surface (waisted profile, 11 loft rings)
+ - Properly-oriented 150x300mm rectangular mullion sweeps (depth axis = surface normal)
+ - Volumetric glass panel solids inset within the frame grid
+ - PBR materials: dark anodised aluminium + highly-reflective tinted green glass
+
+Switch to Rendered Mode in Rhino after running to see the photorealistic result.
+"""
+
+import json
+import sys
+
+try:
+ import requests
+except ImportError:
+ sys.exit("Install requests first: pip install requests")
+
+BRIDGE = "http://127.0.0.1:3004"
+EXECUTE = f"{BRIDGE}/execute"
+HEALTH = f"{BRIDGE}/health"
+
+
+def post(payload: dict) -> dict:
+ r = requests.post(EXECUTE, json=payload, timeout=300) # generous timeout for heavy geometry
+ r.raise_for_status()
+ return r.json()
+
+
+def main() -> None:
+ # ── Health check ────────────────────────────────────────────────────────────
+ try:
+ health = requests.get(HEALTH, timeout=5).json()
+ print(f"Bridge: {health.get('bridge', '?')} | status: {health.get('status', '?')}")
+ except Exception as e:
+ sys.exit(f"Rhino bridge not reachable at {BRIDGE} — is the addin running?\n{e}")
+
+ print()
+
+ # ── Tower parameters ────────────────────────────────────────────────────────
+ # Sizes are in metres; the C# handler converts to the document unit automatically.
+ #
+ # Topology tip: u_divs controls the diagrid panel count around the perimeter;
+ # v_divs controls the vertical rhythm. 16×28 gives elegant ~8×6m panels on a
+ # 180m tower — increase both for a denser facade on a faster machine.
+
+ command = {
+ "command": "generate_diagrid_tower",
+
+ # Form — waisted hyperboloid
+ "base_radius": 22.0, # m — ground-floor footprint radius
+ "waist_radius": 14.0, # m — narrowest point at mid-height
+ "top_radius": 19.0, # m — crown radius (slightly flared)
+ "height": 180.0, # m — total tower height
+
+ # Diagrid density
+ "u_divs": 16, # panels around circumference
+ "v_divs": 28, # panels up the height
+
+ # Mullion cross-section (metres)
+ "mullion_width": 0.15, # 150 mm — visible face width
+ "mullion_depth": 0.30, # 300 mm — structural depth (aligns to surface normal)
+
+ # Glass panel (metres)
+ "glass_thickness": 0.024, # 24 mm — IGU depth (realistic double-glazing unit)
+ "inset_ratio": 0.12, # 12 % — pull each glass corner in toward cell centroid
+ }
+
+ # ── Execute ─────────────────────────────────────────────────────────────────
+ print("Generating high-fidelity diagrid tower…")
+ print(f" {command['u_divs']} × {command['v_divs']} cell grid | "
+ f"{command['u_divs'] * command['v_divs'] * 2} mullion members | "
+ f"{command['u_divs'] * command['v_divs']} glass panels")
+ print()
+
+ try:
+ result = post(command)
+ except requests.exceptions.ReadTimeout:
+ sys.exit("Request timed out — the geometry is heavy; try reducing u_divs/v_divs and retry.")
+ except Exception as e:
+ sys.exit(f"HTTP error: {e}")
+
+ # ── Result ──────────────────────────────────────────────────────────────────
+ print(json.dumps(result, indent=2))
+
+ if result.get("success"):
+ data = result.get("data", {})
+ print()
+ print(f" Mullion sweeps : {data.get('mullionCount', '?')}")
+ print(f" Glass solids : {data.get('glassCount', '?')}")
+ print()
+ print("Done. Switch Rhino to Rendered Mode (V → Rendered) to see the PBR result.")
+ print("Apply a HDRI sky in Rhino's Rendering panel for maximum realism.")
+ else:
+ err = result.get("error", "unknown error")
+ tb = result.get("stackTrace", "")
+ print(f"\nERROR: {err}")
+ if tb:
+ print(f"\nStack trace:\n{tb}")
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scratch/diagrid_tower_python.py b/scratch/diagrid_tower_python.py
new file mode 100644
index 0000000..927da5d
--- /dev/null
+++ b/scratch/diagrid_tower_python.py
@@ -0,0 +1,99 @@
+"""
+diagrid_tower_python.py
+-----------------------
+MCP client: reads rhino_diagrid_tower.py and sends it to the Rhino bridge.
+
+USAGE
+ python scratch/diagrid_tower_python.py
+
+The geometry script (rhino_diagrid_tower.py) runs INSIDE Rhino's IronPython
+engine — no C# recompile ever needed for geometry changes.
+
+ITERATION WORKFLOW
+ - Edit the PARAMETERS block in rhino_diagrid_tower.py
+ - Run this file again → new tower appears in Rhino within seconds
+ - Or open rhino_diagrid_tower.py directly in Rhino's PythonEdit editor
+ and press F5 to run without the bridge at all.
+
+BRIDGE SETUP (one-time after C# compile)
+ 1. Close Rhino
+ 2. dotnet build -c Release (in packages/rhino-bridge-addin)
+ 3. Open Rhino — plugin loads, prints "AEC Model Bridge for Rhino started on port 3004"
+ 4. Run this script
+"""
+
+import os
+import sys
+
+try:
+ import requests
+except ImportError:
+ sys.exit("pip install requests")
+
+BRIDGE = "http://127.0.0.1:3004"
+EXECUTE_URL = BRIDGE + "/execute"
+
+# The geometry script lives next to this file
+TOWER_SCRIPT = os.path.join(os.path.dirname(__file__), "rhino_diagrid_tower.py")
+
+
+def load_tower_script() -> str:
+ if not os.path.exists(TOWER_SCRIPT):
+ sys.exit("Cannot find rhino_diagrid_tower.py next to this file: " + TOWER_SCRIPT)
+ with open(TOWER_SCRIPT, encoding="utf-8") as f:
+ return f.read()
+
+
+def check_bridge() -> None:
+ try:
+ h = requests.get(BRIDGE + "/health", timeout=5).json()
+ status = h.get("status", "?")
+ bridge = h.get("bridge", "?")
+ print("Bridge: {0} | status: {1}".format(bridge, status))
+ except Exception as e:
+ print("")
+ print("ERROR: Rhino bridge not reachable at " + BRIDGE)
+ print(" Make sure Rhino is open and the RhinoBridge plugin is loaded.")
+ print(" Rhino command line should show: 'AEC Model Bridge for Rhino started on port 3004'")
+ print(" If not, run: PlugInManager -> drag-drop RhinoBridge.rhp -> restart Rhino")
+ print("")
+ sys.exit(str(e))
+
+
+def run_tower() -> None:
+ code = load_tower_script()
+
+ print("Sending tower script to Rhino ({0} lines)...".format(len(code.splitlines())))
+ print("")
+
+ try:
+ r = requests.post(
+ EXECUTE_URL,
+ json={"command": "run_python", "code": code},
+ timeout=300
+ )
+ r.raise_for_status()
+ result = r.json()
+ except requests.exceptions.ReadTimeout:
+ sys.exit("Timed out — reduce U_DIVS/V_DIVS in rhino_diagrid_tower.py and retry.")
+ except Exception as e:
+ sys.exit("HTTP error: " + str(e))
+
+ if result.get("success"):
+ output = (result.get("output") or "").strip()
+ if output:
+ print("Rhino output:")
+ for line in output.splitlines():
+ print(" " + line)
+ else:
+ err = result.get("error", "unknown error")
+ tb = result.get("stackTrace", "")
+ print("ERROR: " + err)
+ if tb:
+ print(tb)
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ check_bridge()
+ run_tower()
diff --git a/scratch/glass_diamond.py b/scratch/glass_diamond.py
new file mode 100644
index 0000000..30a978f
--- /dev/null
+++ b/scratch/glass_diamond.py
@@ -0,0 +1,163 @@
+import scriptcontext as sc
+import Rhino, Rhino.Geometry as rg, Rhino.DocObjects as rdo, System.Drawing as sd
+
+# ── Tower params (must match mullion generation) ─────────────────────────────
+BASE_R=22.0; WAIST_R=13.5; TOP_R=19.0; HEIGHT=200.0
+U_DIVS=20 # divisions in i-direction (= surface U = HEIGHT direction on this loft)
+V_DIVS=36 # divisions in j-direction (= surface V = CIRCUMFERENTIAL direction)
+THICKNESS=0.028; SETBACK=0.06
+
+scale = Rhino.RhinoMath.UnitScale(Rhino.UnitSystem.Meters, sc.doc.ModelUnitSystem)
+
+# ── Rebuild tower loft ────────────────────────────────────────────────────────
+def smooth_r(a,b,c,t):
+ if t<=0.5: s=t*2.0; return a+(b-a)*(s*s*(3-2*s))
+ s=(t-0.5)*2.0; return b+(c-b)*(s*s*(3-2*s))
+
+crvs=[]
+for k in range(12):
+ t=float(k)/11; r=smooth_r(BASE_R,WAIST_R,TOP_R,t)*scale; z=t*HEIGHT*scale
+ crvs.append(rg.Circle(rg.Plane(rg.Point3d(0,0,z),rg.Vector3d.ZAxis),r).ToNurbsCurve())
+breps=rg.Brep.CreateFromLoft(crvs,rg.Point3d.Unset,rg.Point3d.Unset,rg.LoftType.Normal,False)
+face=breps[0].Faces[0]
+face.SetDomain(0,rg.Interval(0,1)); face.SetDomain(1,rg.Interval(0,1))
+
+# Confirmed: surface U = HEIGHT (i direction), surface V = CIRCUMFERENCE (j direction)
+# The circumferential seam is at V=0/V=1 (j=0/j=V_DIVS).
+# i goes from 0 (bottom) to U_DIVS (top) — NO wrap needed for i.
+# j wraps: j % V_DIVS keeps us inside the closed circumferential range.
+
+def gpt(i, j):
+ """Grid corner: i=height index (0..U_DIVS), j=circumference index (wraps)."""
+ u = float(i) / U_DIVS
+ v = float(j % V_DIVS) / V_DIVS
+ return face.PointAt(u, v)
+
+def cc(i, j):
+ """Cell centre on surface: i=height cell (0..U_DIVS-1), j=circ cell (wraps)."""
+ u = (i + 0.5) / U_DIVS
+ v = ((j % V_DIVS) + 0.5) / V_DIVS
+ return face.PointAt(u, v)
+
+# ── Layer + material ──────────────────────────────────────────────────────────
+def get_layer(name, rgb, clear=False):
+ idx = sc.doc.Layers.FindByFullPath(name,-1)
+ if idx < 0:
+ lay=rdo.Layer(); lay.Name=name
+ lay.Color=sd.Color.FromArgb(*rgb)
+ idx=sc.doc.Layers.Add(lay)
+ elif clear:
+ for o in list(sc.doc.Objects):
+ if o.Attributes.LayerIndex==idx:
+ sc.doc.Objects.Delete(o.Id,True)
+ return idx
+
+glass_layer = get_layer("Glass",(18,75,52),clear=True)
+mat=rdo.Material(); mat.Name="ArchGlass"
+mat.DiffuseColor=sd.Color.FromArgb(35,155,105)
+mat.Transparency=0.55; mat.Reflectivity=0.95
+mat.FresnelReflections=True; mat.IndexOfRefraction=1.52
+mat.Shine=int(0.92*rdo.Material.MaxShine)
+try:
+ mat.ToPhysicallyBased()
+ pbr=mat.PhysicallyBased
+ pbr.BaseColor=Rhino.Display.Color4f(0.04,0.28,0.16,1.0)
+ pbr.Metallic=0.0; pbr.Roughness=0.02; pbr.Opacity=0.48
+except:
+ pass
+glass_mat=sc.doc.Materials.Add(mat)
+
+attr=rdo.ObjectAttributes()
+attr.LayerIndex=glass_layer; attr.MaterialIndex=glass_mat
+attr.MaterialSource=rdo.ObjectMaterialSource.MaterialFromObject
+
+tol=sc.doc.ModelAbsoluteTolerance
+# Reject any panel whose bbox diagonal exceeds 2 cell widths (catches spanning artifacts)
+MAX_DIAG = 15000.0 * scale
+added=0; skipped=0
+
+# ── Quad panel (6-face solid) ─────────────────────────────────────────────────
+def make_panel(A, B, C, D):
+ bb = rg.BoundingBox([A,B,C,D])
+ if bb.Diagonal.Length > MAX_DIAG:
+ return False
+ cpt=rg.Point3d((A.X+B.X+C.X+D.X)/4.,(A.Y+B.Y+C.Y+D.Y)/4.,(A.Z+B.Z+C.Z+D.Z)/4.)
+ ok,cu,cv=face.ClosestPoint(cpt)
+ if not ok: return False
+ n=face.NormalAt(cu,cv)
+ if not n.Unitize(): return False
+ push=n*(-SETBACK*scale); thick=n*(-THICKNESS*scale)
+ fA=A+push; fB=B+push; fC=C+push; fD=D+push
+ bA=fA+thick; bB=fB+thick; bC=fC+thick; bD=fD+thick
+ front=rg.NurbsSurface.CreateFromCorners(fA,fB,fC,fD)
+ back =rg.NurbsSurface.CreateFromCorners(bA,bD,bC,bB)
+ s1=rg.NurbsSurface.CreateFromCorners(fA,fB,bB,bA)
+ s2=rg.NurbsSurface.CreateFromCorners(fB,fC,bC,bB)
+ s3=rg.NurbsSurface.CreateFromCorners(fC,fD,bD,bC)
+ s4=rg.NurbsSurface.CreateFromCorners(fD,fA,bA,bD)
+ faces=[x.ToBrep() for x in [front,back,s1,s2,s3,s4] if x]
+ if len(faces)<6: return False
+ joined=rg.Brep.JoinBreps(faces,tol)
+ if joined and len(joined)>0: sc.doc.Objects.AddBrep(joined[0],attr)
+ else: [sc.doc.Objects.AddBrep(f,attr) for f in faces]
+ return True
+
+# ── Triangular panel (5-face solid, for top/bottom caps) ─────────────────────
+def make_tri(A, B, C):
+ bb = rg.BoundingBox([A,B,C])
+ if bb.Diagonal.Length > MAX_DIAG:
+ return False
+ cpt=rg.Point3d((A.X+B.X+C.X)/3.,(A.Y+B.Y+C.Y)/3.,(A.Z+B.Z+C.Z)/3.)
+ ok,cu,cv=face.ClosestPoint(cpt)
+ if not ok: return False
+ n=face.NormalAt(cu,cv)
+ if not n.Unitize(): return False
+ push=n*(-SETBACK*scale); thick=n*(-THICKNESS*scale)
+ fA=A+push; fB=B+push; fC=C+push
+ bA=fA+thick; bB=fB+thick; bC=fC+thick
+ front=rg.NurbsSurface.CreateFromCorners(fA,fB,fC)
+ back =rg.NurbsSurface.CreateFromCorners(bA,bC,bB)
+ s1=rg.NurbsSurface.CreateFromCorners(fA,fB,bB,bA)
+ s2=rg.NurbsSurface.CreateFromCorners(fB,fC,bC,bB)
+ s3=rg.NurbsSurface.CreateFromCorners(fC,fA,bA,bC)
+ faces=[x.ToBrep() for x in [front,back,s1,s2,s3] if x]
+ if len(faces)<5: return False
+ joined=rg.Brep.JoinBreps(faces,tol)
+ if joined and len(joined)>0: sc.doc.Objects.AddBrep(joined[0],attr)
+ else: [sc.doc.Objects.AddBrep(f,attr) for f in faces]
+ return True
+
+# ── Type A: TOP triangle of cell(i,j) + BOTTOM triangle of cell(i,j+1) ──────
+# Vertices: cc(i,j), gpt(i+1,j+1), cc(i,j+1), gpt(i,j+1)
+# i spans full height range, j wraps circumferentially via gpt/cc % V_DIVS
+for i in range(U_DIVS):
+ for j in range(V_DIVS):
+ r = make_panel(cc(i,j), gpt(i+1,j+1), cc(i,j+1), gpt(i,j+1))
+ if r: added+=1
+ else: skipped+=1
+
+# ── Type B: RIGHT triangle of cell(i,j) + LEFT triangle of cell(i+1,j) ──────
+# Vertices: cc(i,j), gpt(i+1,j), cc(i+1,j), gpt(i+1,j+1)
+# i goes 0..U_DIVS-2 (height cells that have a valid i+1 cell above them, NO wrap)
+for i in range(U_DIVS - 1):
+ for j in range(V_DIVS):
+ r = make_panel(cc(i,j), gpt(i+1,j), cc(i+1,j), gpt(i+1,j+1))
+ if r: added+=1
+ else: skipped+=1
+
+# ── Bottom caps: LEFT triangle of cell(i=0, j) ───────────────────────────────
+# LEFT(0,j): gpt(0,j), gpt(0,j+1), cc(0,j) (all at height i=0 = tower base)
+for j in range(V_DIVS):
+ r = make_tri(gpt(0,j), gpt(0,j+1), cc(0,j))
+ if r: added+=1
+ else: skipped+=1
+
+# ── Top caps: RIGHT triangle of cell(i=U_DIVS-1, j) ──────────────────────────
+# RIGHT(U_DIVS-1,j): cc(U_DIVS-1,j), gpt(U_DIVS,j+1), gpt(U_DIVS,j)
+for j in range(V_DIVS):
+ r = make_tri(cc(U_DIVS-1,j), gpt(U_DIVS,j+1), gpt(U_DIVS,j))
+ if r: added+=1
+ else: skipped+=1
+
+sc.doc.Views.Redraw()
+print("Panels added: %d skipped: %d" % (added, skipped))
diff --git a/scratch/omega_gh_builder.py b/scratch/omega_gh_builder.py
new file mode 100644
index 0000000..8a3ad9b
--- /dev/null
+++ b/scratch/omega_gh_builder.py
@@ -0,0 +1,583 @@
+# =============================================================================
+# OMEGA TOWER — Grasshopper Canvas Builder
+# Runs via: MCP bridge run_python (Grasshopper must be open)
+#
+# Programmatically populates the open GH canvas with:
+# - 24 number sliders in 6 colour-coded groups
+# - 1 Python Script component containing the full tower generator
+# - Wires connecting every slider to the Python component
+# - Annotation panels
+# =============================================================================
+
+import clr
+import System
+import System.Drawing as sd
+import System.Reflection as sr
+
+clr.AddReference('Grasshopper')
+import Grasshopper as gh
+from Grasshopper.Kernel import GH_Document
+from Grasshopper.Kernel.Special import GH_NumberSlider, GH_Group
+
+# ─── Access open GH canvas ────────────────────────────────────────────────────
+canvas = gh.Instances.ActiveCanvas
+if canvas is None:
+ print("ERROR: Grasshopper is not open. Run _Grasshopper in Rhino first.")
+ raise SystemExit("GH canvas not found")
+
+gd = canvas.Document
+if gd is None:
+ gd = GH_Document()
+ canvas.Document = gd
+ print("Created blank GH document")
+else:
+ print("Using existing GH document")
+
+gd.Enabled = False # pause solver while building
+
+# ─── Clear only objects added by previous builder runs ───────────────────────
+# (We tag objects by nickname prefix; safe to comment out on first run)
+# gd.Objects.Clear()
+
+# ─── Layout constants (GH canvas pixels) ────────────────────────────────────
+COL_A = 80 # left column X (sliders)
+COL_B = 280 # right column X (second slider column inside each group)
+PY_X = 560 # Python Script component X
+PY_Y = 80
+ROW_H = 30 # vertical spacing between sliders
+GROUP_PAD = 20 # extra vertical padding between groups
+
+# ─── Helper: add number slider ────────────────────────────────────────────────
+def add_slider(name, mn, mx, val, x, y, dec=2):
+ s = GH_NumberSlider()
+ s.CreateAttributes()
+ s.Name = name
+ s.NickName = name
+ s.Slider.Minimum = System.Decimal(mn)
+ s.Slider.Maximum = System.Decimal(mx)
+ s.Slider.Value = System.Decimal(val)
+ s.Slider.DecimalPlaces = dec
+ s.Attributes.Pivot = sd.PointF(float(x), float(y))
+ gd.AddObject(s, False)
+ return s
+
+# ─── Helper: add group around a list of objects ───────────────────────────────
+def add_group(title, rgb, objects):
+ g = GH_Group()
+ g.NickName = title
+ g.Colour = sd.Color.FromArgb(*rgb)
+ for o in objects:
+ g.AddObject(o.InstanceGuid)
+ gd.AddObject(g, False)
+ return g
+
+# ─── Helper: add a text panel ────────────────────────────────────────────────
+from Grasshopper.Kernel.Special import GH_Panel
+
+def add_panel(text, x, y):
+ p = GH_Panel()
+ p.CreateAttributes()
+ p.UserText = text
+ p.Attributes.Pivot = sd.PointF(float(x), float(y))
+ gd.AddObject(p, False)
+ return p
+
+# =============================================================================
+# BUILD SLIDERS — 6 groups, 24 sliders
+# =============================================================================
+
+sliders = {} # name → GH_NumberSlider object
+y = 80
+
+# ── Group 1: TOWER FORM ──────────────────────────────────────────────────────
+g1_items = []
+labels_g1 = [
+ ("base_r", 5.0, 60.0, 26.0, COL_A, y, 1),
+ ("waist_r", 3.0, 50.0, 14.5, COL_A, y+30, 1),
+ ("top_r", 5.0, 55.0, 21.0, COL_A, y+60, 1),
+ ("height", 50.0, 600.0, 272.0, COL_B, y, 1),
+ ("squircle_n", 2.0, 8.0, 3.5, COL_B, y+30, 2),
+ ("twist_deg", 0.0, 180.0, 72.0, COL_B, y+60, 1),
+]
+for lbl, mn, mx, val, x, yy, dec in labels_g1:
+ s = add_slider(lbl, mn, mx, val, x, yy, dec)
+ g1_items.append(s)
+ sliders[lbl] = s
+
+add_group("A — TOWER FORM", (45, 80, 135, 60), g1_items)
+y += 60 + ROW_H + GROUP_PAD
+
+# ── Group 2: DIAGRID SYSTEM ──────────────────────────────────────────────────
+g2_items = []
+labels_g2 = [
+ ("u_divs", 12, 48, 24, COL_A, y, 0),
+ ("v_divs", 20, 96, 52, COL_A, y+30, 0),
+ ("mul_w_base", 0.10, 0.80, 0.30, COL_B, y, 3),
+ ("mul_w_top", 0.05, 0.40, 0.12, COL_B, y+30, 3),
+ ("mul_d_base", 0.15, 1.20, 0.52, COL_A, y+60, 3),
+ ("mul_d_top", 0.08, 0.60, 0.20, COL_B, y+60, 3),
+]
+for lbl, mn, mx, val, x, yy, dec in labels_g2:
+ s = add_slider(lbl, mn, mx, val, x, yy, dec)
+ g2_items.append(s)
+ sliders[lbl] = s
+
+add_group("B — DIAGRID SYSTEM", (135, 80, 45, 60), g2_items)
+y += 60 + ROW_H + GROUP_PAD
+
+# ── Group 3: FACADE ZONES ────────────────────────────────────────────────────
+g3_items = []
+labels_g3 = [
+ ("zone_solid", 0.0, 0.5, 0.22, COL_A, y, 3),
+ ("zone_glass", 0.5, 1.0, 0.80, COL_B, y, 3),
+ ("glass_t", 0.010, 0.060, 0.028, COL_A, y+30, 3),
+ ("glass_inset", 0.02, 0.20, 0.09, COL_B, y+30, 3),
+]
+for lbl, mn, mx, val, x, yy, dec in labels_g3:
+ s = add_slider(lbl, mn, mx, val, x, yy, dec)
+ g3_items.append(s)
+ sliders[lbl] = s
+
+add_group("C/D — FACADE ZONES", (45, 135, 80, 60), g3_items)
+y += 30 + ROW_H + GROUP_PAD
+
+# ── Group 4: SOLAR FINS ──────────────────────────────────────────────────────
+g4_items = []
+labels_g4 = [
+ ("sun_azimuth", 0.0, 360.0, 195.0, COL_A, y, 1),
+ ("sun_altitude", 5.0, 85.0, 40.0, COL_B, y, 1),
+ ("fin_len", 0.2, 3.0, 1.1, COL_A, y+30, 2),
+ ("fin_thick", 0.02, 0.20, 0.055, COL_B, y+30, 3),
+ ("fin_step", 1, 6, 2, COL_A, y+60, 0),
+]
+for lbl, mn, mx, val, x, yy, dec in labels_g4:
+ s = add_slider(lbl, mn, mx, val, x, yy, dec)
+ g4_items.append(s)
+ sliders[lbl] = s
+
+add_group("F — SOLAR FIN SYSTEM", (135, 120, 40, 60), g4_items)
+y += 60 + ROW_H + GROUP_PAD
+
+# ── Group 5: FLOOR PLATES ────────────────────────────────────────────────────
+g5_items = []
+labels_g5 = [
+ ("floor_h", 2.5, 6.5, 4.3, COL_A, y, 2),
+ ("slab_t", 0.15, 0.6, 0.30, COL_B, y, 3),
+ ("slab_in", 0.05, 0.4, 0.14, COL_A, y+30, 3),
+]
+for lbl, mn, mx, val, x, yy, dec in labels_g5:
+ s = add_slider(lbl, mn, mx, val, x, yy, dec)
+ g5_items.append(s)
+ sliders[lbl] = s
+
+add_group("G — FLOOR PLATES", (80, 80, 80, 60), g5_items)
+y += 30 + ROW_H + GROUP_PAD
+
+# ── Group 6: BRANCHING COLUMNS ───────────────────────────────────────────────
+g6_items = []
+labels_g6 = [
+ ("col_n", 4, 16, 8, COL_A, y, 0),
+ ("col_depth", 1, 4, 3, COL_B, y, 0),
+ ("col_angle", 8.0, 50.0, 26.0, COL_A, y+30, 1),
+ ("col_h", 5.0, 30.0, 15.0, COL_B, y+30, 1),
+]
+for lbl, mn, mx, val, x, yy, dec in labels_g6:
+ s = add_slider(lbl, mn, mx, val, x, yy, dec)
+ g6_items.append(s)
+ sliders[lbl] = s
+
+add_group("H — BRANCHING COLUMNS", (100, 55, 20, 60), g6_items)
+y += 30 + ROW_H + GROUP_PAD
+
+total_sliders = len(sliders)
+print("Sliders added: %d" % total_sliders)
+
+# =============================================================================
+# PYTHON SCRIPT COMPONENT — with complete tower generator code
+# =============================================================================
+
+# The GHPython component GUID (GH1 IronPython)
+PY_GUID_STR = "410755b1-224a-4c1e-a407-bf32fb45ea7e"
+
+# Search the component server
+server = gh.Instances.ComponentServer
+py_proxy = None
+
+# Try exact GUID first
+try:
+ py_proxy = server.FindObjectByGuid(System.Guid(PY_GUID_STR))
+except:
+ pass
+
+# Fallback: search by name
+if py_proxy is None:
+ for proxy in server.ObjectProxies:
+ n = proxy.Desc.Name.lower()
+ if "python" in n:
+ py_proxy = proxy
+ print("Found Python component: %s (%s)" % (proxy.Desc.Name, proxy.Desc.Guid))
+ break
+
+if py_proxy is None:
+ print("WARNING: No Python Script component found in this GH version.")
+ print(" Sliders are built. Add a Python Script component manually and")
+ print(" paste the code from scratch/omega_tower.py.")
+else:
+ py_comp = py_proxy.CreateInstance()
+ py_comp.CreateAttributes()
+ py_comp.Attributes.Pivot = sd.PointF(float(PY_X), float(PY_Y))
+ gd.AddObject(py_comp, False)
+
+ # ── Embed the tower code as the component's source ────────────────────────
+ TOWER_CODE = r'''
+import math, Rhino, Rhino.Geometry as rg, Rhino.DocObjects as rdo
+import Rhino.Display as rdp, scriptcontext as sc, System.Drawing as sd
+
+# ── Read GH slider inputs (all named variables from input params) ──────────
+# Defaults are used when running standalone (F5 in Rhino editor).
+def _f(v, default):
+ try: return float(v) if v is not None else default
+ except: return default
+def _i(v, default):
+ try: return int(v) if v is not None else default
+ except: return default
+
+BASE_R = _f(base_r, 26.0)
+WAIST_R = _f(waist_r, 14.5)
+TOP_R = _f(top_r, 21.0)
+HEIGHT = _f(height, 272.0)
+SQUIRCLE_N = _f(squircle_n, 3.5)
+TWIST_DEG = _f(twist_deg, 72.0)
+U_DIVS = _i(u_divs, 24)
+V_DIVS = _i(v_divs, 52)
+MUL_W_BASE = _f(mul_w_base, 0.30)
+MUL_W_TOP = _f(mul_w_top, 0.12)
+MUL_D_BASE = _f(mul_d_base, 0.52)
+MUL_D_TOP = _f(mul_d_top, 0.20)
+ZONE_SOLID = _f(zone_solid, 0.22)
+ZONE_GLASS = _f(zone_glass, 0.80)
+GLASS_T = _f(glass_t, 0.028)
+GLASS_INSET = _f(glass_inset, 0.09)
+SUN_AZ = _f(sun_azimuth, 195.0)
+SUN_ALT = _f(sun_altitude, 40.0)
+FIN_LEN = _f(fin_len, 1.10)
+FIN_THICK = _f(fin_thick, 0.055)
+FIN_STEP = _i(fin_step, 2)
+FLOOR_H = _f(floor_h, 4.3)
+SLAB_T = _f(slab_t, 0.30)
+SLAB_IN = _f(slab_in, 0.14)
+COL_N = _i(col_n, 8)
+COL_DEPTH = _i(col_depth, 3)
+COL_ANGLE = _f(col_angle, 26.0)
+COL_H = _f(col_h, 15.0)
+
+WAIST_T = 0.42
+PROFILE_PTS = 64
+LOFT_RINGS = 22
+SPIRE_H = 38.0; SPIRE_BASE_R = 1.80; SPIRE_TIP_R = 0.08
+FIN_ON = True; CLEAR_BEFORE = True
+
+doc = sc.doc; tol = doc.ModelAbsoluteTolerance
+S = Rhino.RhinoMath.UnitScale(rg.UnitSystem.Meters, doc.ModelUnitSystem)
+
+def smoothstep(a,b,t):
+ t=max(0.0,min(1.0,t)); t=t*t*(3.0-2.0*t); return a+(b-a)*t
+def tower_r(t):
+ if t<=WAIST_T: return smoothstep(BASE_R,WAIST_R,t/WAIST_T)
+ return smoothstep(WAIST_R,TOP_R,(t-WAIST_T)/(1.0-WAIST_T))
+def cs(mag,sgn): return abs(mag) if sgn>=0 else -abs(mag)
+def sqxy(ang,r,n):
+ c=math.cos(ang); s=math.sin(ang)
+ return r*cs(abs(c)**(2.0/n),c), r*cs(abs(s)**(2.0/n),s)
+def mk_layer(name,rgb):
+ idx=doc.Layers.FindByFullPath(name,-1)
+ if idx<0:
+ lyr=rdo.Layer(); lyr.Name=name; lyr.Color=sd.Color.FromArgb(*rgb)
+ idx=doc.Layers.Add(lyr)
+ elif CLEAR_BEFORE:
+ objs=doc.Objects.FindByLayer(name)
+ if objs:
+ for o in objs: doc.Objects.Delete(o,True)
+ return idx
+def mk_attr(li,mi):
+ a=rdo.ObjectAttributes(); a.LayerIndex=li; a.MaterialIndex=mi
+ a.MaterialSource=rdo.ObjectMaterialSource.MaterialFromObject; return a
+def d3(a,b): return a.X*b.X+a.Y*b.Y+a.Z*b.Z
+def prj(pt,o,n):
+ d=(pt.X-o.X)*n.X+(pt.Y-o.Y)*n.Y+(pt.Z-o.Z)*n.Z
+ return rg.Point3d(pt.X-d*n.X,pt.Y-d*n.Y,pt.Z-d*n.Z)
+def add_m(nm,bc,me,ro,dif,tr=0.0,re=0.0,sh=0.5,op=1.0):
+ m=rdo.Material(); m.Name=nm
+ try:
+ m.ToPhysicallyBased(); pb=m.PhysicallyBased
+ pb.BaseColor=rdp.Color4f(*bc); pb.Metallic=me; pb.Roughness=ro
+ try: pb.Opacity=op
+ except: pass
+ except: pass
+ m.DiffuseColor=sd.Color.FromArgb(*dif); m.Transparency=tr
+ m.Reflectivity=re; m.FresnelReflections=True
+ m.Shine=int(sh*rdo.Material.MaxShine); return doc.Materials.Add(m)
+
+mf=add_m("Frame",(0.038,0.040,0.048,1.0),0.94,0.17,(30,32,38),re=0.87,sh=0.74)
+mg=add_m("Glass",(0.025,0.14,0.09,1.0),0.00,0.01,(10,58,40),tr=0.88,re=0.94,sh=0.96,op=0.10)
+mc=add_m("Corten",(0.16,0.055,0.018,1.0),0.80,0.48,(105,48,18),re=0.42,sh=0.30)
+mfi=add_m("Fin",(0.52,0.48,0.40,1.0),0.65,0.22,(155,142,115),re=0.60,sh=0.55)
+ms=add_m("Slab",(0.26,0.26,0.24,1.0),0.00,0.82,(132,130,122),re=0.06,sh=0.04)
+mcol=add_m("Col",(0.20,0.07,0.022,1.0),0.82,0.44,(118,55,22),re=0.40,sh=0.28)
+msp=add_m("Spire",(0.78,0.76,0.74,1.0),0.96,0.08,(200,195,188),re=0.92,sh=0.90)
+
+lf=mk_layer("Diagrid",(35,38,46)); lg=mk_layer("Glass",(12,65,45))
+lc=mk_layer("Cladding",(105,50,20)); lfn=mk_layer("SolarFins",(158,144,112))
+lsl=mk_layer("FloorSlabs",(140,136,126)); lco=mk_layer("Columns",(112,52,20))
+lsp=mk_layer("Spire",(195,190,182))
+
+af=mk_attr(lf,mf); ag=mk_attr(lg,mg); ac=mk_attr(lc,mc)
+afn=mk_attr(lfn,mfi); asl=mk_attr(lsl,ms); aco=mk_attr(lco,mcol); asp=mk_attr(lsp,msp)
+
+# Tower surface
+loft=[];
+for k in range(LOFT_RINGS+1):
+ t=float(k)/LOFT_RINGS; r=tower_r(t)
+ twist=math.radians(TWIST_DEG*t); z=t*HEIGHT*S
+ ring=[rg.Point3d(*(list(sqxy(2.0*math.pi*p/PROFILE_PTS+twist,r*S,SQUIRCLE_N))+[z])) for p in range(PROFILE_PTS)]
+ crv=rg.NurbsCurve.CreateInterpolatedCurve(ring,3,rg.CurveKnotStyle.ChordPeriodic)
+ if not crv: ring.append(ring[0]); crv=rg.NurbsCurve.CreateInterpolatedCurve(ring,3)
+ if crv: loft.append(crv)
+
+breps=rg.Brep.CreateFromLoft(loft,rg.Point3d.Unset,rg.Point3d.Unset,rg.LoftType.Normal,False)
+if not breps: print("Loft failed"); raise SystemExit
+face=breps[0].Faces[0]
+face.SetDomain(0,rg.Interval(0,1)); face.SetDomain(1,rg.Interval(0,1))
+pts=[[face.PointAt(float(i)/U_DIVS,float(j)/V_DIVS) for j in range(V_DIVS+1)] for i in range(U_DIVS+1)]
+
+# Diagrid
+nm=0
+for i in range(U_DIVS):
+ for j in range(V_DIVS):
+ th=(float(j)+0.5)/V_DIVS
+ mw=(MUL_W_BASE+(MUL_W_TOP-MUL_W_BASE)*th)*S
+ md=(MUL_D_BASE+(MUL_D_TOP-MUL_D_BASE)*th)*S
+ if th<ZONE_SOLID: mw*=1.35; md*=1.55
+ for p0,p1 in [(pts[i][j],pts[i+1][j+1]),(pts[i+1][j],pts[i][j+1])]:
+ line=rg.LineCurve(p0,p1); ok,fr=line.PerpendicularFrameAt(line.Domain.Min)
+ if not ok: continue
+ mid=line.PointAt(line.Domain.Mid); ok2,cu,cv=face.ClosestPoint(mid)
+ if not ok2: continue
+ sn=face.NormalAt(cu,cv); sn.Unitize(); tang=fr.ZAxis
+ tn=d3(tang,sn); dep=rg.Vector3d(sn.X-tn*tang.X,sn.Y-tn*tang.Y,sn.Z-tn*tang.Z)
+ if not dep.Unitize(): continue
+ wid=rg.Vector3d.CrossProduct(tang,dep)
+ if not wid.Unitize(): continue
+ rect=rg.Rectangle3d(rg.Plane.WorldXY,rg.Interval(-mw*0.5,mw*0.5),rg.Interval(-md,0.0))
+ prof=rect.ToNurbsCurve(); spln=rg.Plane(fr.Origin,wid,dep)
+ xf=rg.Transform.PlaneToPlane(rg.Plane.WorldXY,spln); prof.Transform(xf)
+ sw=rg.Brep.CreateFromSweep(line,prof,True,tol)
+ if sw:
+ for b in sw: doc.Objects.AddBrep(b,af)
+ nm+=1
+
+# Panels
+def panel(p1,p2,p3,p4,t,sb,ins,c,n,attr):
+ k=1.0-ins
+ gi=[rg.Point3d(c.X+(p.X-c.X)*k,c.Y+(p.Y-c.Y)*k,c.Z+(p.Z-c.Z)*k) for p in[p1,p2,p3,p4]]
+ fp=[prj(g,c,n) for g in gi]; off=n*(-sb)
+ sp=[rg.Point3d(f.X+off.X,f.Y+off.Y,f.Z+off.Z) for f in fp]; tv=n*(-t)
+ bp=[rg.Point3d(s.X+tv.X,s.Y+tv.Y,s.Z+tv.Z) for s in sp]
+ ss=[rg.NurbsSurface.CreateFromCorners(sp[0],sp[1],sp[2],sp[3]),
+ rg.NurbsSurface.CreateFromCorners(bp[0],bp[3],bp[2],bp[1]),
+ rg.NurbsSurface.CreateFromCorners(sp[0],sp[1],bp[1],bp[0]),
+ rg.NurbsSurface.CreateFromCorners(sp[1],sp[2],bp[2],bp[1]),
+ rg.NurbsSurface.CreateFromCorners(sp[2],sp[3],bp[3],bp[2]),
+ rg.NurbsSurface.CreateFromCorners(sp[3],sp[0],bp[0],bp[3])]
+ fb=[s.ToBrep() for s in ss if s]
+ if len(fb)<6: return
+ j2=rg.Brep.JoinBreps(fb,tol)
+ if j2: doc.Objects.AddBrep(j2[0],attr)
+
+for i in range(U_DIVS):
+ for j in range(V_DIVS):
+ th=(float(j)+0.5)/V_DIVS
+ if th>ZONE_GLASS: continue
+ p1=pts[i][j];p2=pts[i+1][j];p3=pts[i+1][j+1];p4=pts[i][j+1]
+ cx=(p1.X+p2.X+p3.X+p4.X)*0.25;cy=(p1.Y+p2.Y+p3.Y+p4.Y)*0.25;cz=(p1.Z+p2.Z+p3.Z+p4.Z)*0.25
+ c=rg.Point3d(cx,cy,cz); ok,cu,cv=face.ClosestPoint(c)
+ if not ok: continue
+ n=face.NormalAt(cu,cv)
+ if not n.Unitize(): continue
+ if th<ZONE_SOLID: panel(p1,p2,p3,p4,0.055*S,0.018*S,0.03,c,n,ac)
+ else: panel(p1,p2,p3,p4,GLASS_T*S,0.030*S,GLASS_INSET,c,n,ag)
+
+# Solar fins
+if FIN_ON:
+ az=math.radians(SUN_AZ); alt=math.radians(SUN_ALT)
+ sv=rg.Vector3d(math.sin(az)*math.cos(alt),math.cos(az)*math.cos(alt),math.sin(alt)); sv.Unitize()
+ for i in range(U_DIVS):
+ for j in range(0,V_DIVS,FIN_STEP):
+ th=float(j)/V_DIVS
+ if th<ZONE_SOLID or th>ZONE_GLASS: continue
+ nd=pts[i][j]; ok,cu,cv=face.ClosestPoint(nd)
+ if not ok: continue
+ sn=face.NormalAt(cu,cv)
+ if not sn.Unitize(): continue
+ dsn=d3(sv,sn); pj=rg.Vector3d(sv.X-dsn*sn.X,sv.Y-dsn*sn.Y,sv.Z-dsn*sn.Z)
+ if pj.Length<0.01: pj=rg.Vector3d(0,0,1)
+ pj.Unitize(); fw=rg.Vector3d.CrossProduct(sn,pj)
+ if not fw.Unitize(): continue
+ fl=FIN_LEN*S; ft=FIN_THICK*S; bo=sn*(0.02*S)
+ c1=rg.Point3d(nd.X+bo.X-fw.X*ft*0.5,nd.Y+bo.Y-fw.Y*ft*0.5,nd.Z+bo.Z)
+ c2=rg.Point3d(c1.X+fw.X*ft,c1.Y+fw.Y*ft,c1.Z)
+ c3=rg.Point3d(c2.X+sn.X*fl,c2.Y+sn.Y*fl,c2.Z+sn.Z*fl)
+ c4=rg.Point3d(c1.X+sn.X*fl,c1.Y+sn.Y*fl,c1.Z+sn.Z*fl)
+ fs=rg.NurbsSurface.CreateFromCorners(c1,c2,c3,c4)
+ if fs: doc.Objects.AddSurface(fs,afn)
+
+# Floor slabs
+nfl=int(HEIGHT/FLOOR_H)
+for fi in range(1,nfl+1):
+ zf=float(fi)*FLOOR_H/HEIGHT
+ if zf>=1.0: break
+ z=zf*HEIGHT*S; tw=math.radians(TWIST_DEG*zf); r=tower_r(zf)-SLAB_IN
+ sr=[rg.Point3d(*(list(sqxy(2.0*math.pi*p/PROFILE_PTS+tw,r*S,SQUIRCLE_N))+[z])) for p in range(PROFILE_PTS)]
+ sc2=rg.NurbsCurve.CreateInterpolatedCurve(sr,3,rg.CurveKnotStyle.ChordPeriodic)
+ if not sc2: sr.append(sr[0]); sc2=rg.NurbsCurve.CreateInterpolatedCurve(sr,3)
+ if not sc2: continue
+ ex=rg.Surface.CreateExtrusion(sc2,rg.Vector3d(0,0,SLAB_T*S))
+ if ex:
+ sb=ex.ToBrep(); sb=rg.Brep.CapPlanarHoles(sb,tol)
+ if sb: doc.Objects.AddBrep(sb,asl)
+
+# Branching columns
+def grow(st,dr,ln,rad,dep,out):
+ en=rg.Point3d(st.X+dr.X*ln,st.Y+dr.Y*ln,st.Z+dr.Z*ln)
+ pp=rg.Brep.CreatePipe(rg.LineCurve(st,en),rad,True,rg.PipeCapMode.Flat,False,tol,tol)
+ if pp: out.extend(pp)
+ if dep<COL_DEPTH:
+ ar=math.radians(COL_ANGLE); pe=rg.Vector3d(-dr.Y,dr.X,0.0)
+ if pe.Length<1e-6: pe=rg.Vector3d(1,0,0)
+ pe.Unitize()
+ for sg in [1,-1]:
+ rt=rg.Transform.Rotation(sg*ar,pe,en); nd2=rg.Vector3d(dr); nd2.Transform(rt); nd2.Unitize()
+ grow(en,nd2,ln*0.60,rad*0.62,dep+1,out)
+
+cb=[]
+for k in range(COL_N):
+ ang=2.0*math.pi*k/COL_N
+ xb,yb=sqxy(ang,BASE_R*0.85*S,SQUIRCLE_N)
+ grow(rg.Point3d(xb,yb,0.0),rg.Vector3d(0,0,1),COL_H*S,0.44*S,0,cb)
+for b in cb: doc.Objects.AddBrep(b,aco)
+
+# Spire
+sr2=[]
+for k in range(6):
+ t=float(k)/5.0; rs=(SPIRE_BASE_R+(SPIRE_TIP_R-SPIRE_BASE_R)*(t*t))*S
+ zs=(HEIGHT+SPIRE_H*t)*S
+ sr2.append(rg.Circle(rg.Plane(rg.Point3d(0,0,zs),rg.Vector3d.ZAxis),rs).ToNurbsCurve())
+spb=rg.Brep.CreateFromLoft(sr2,rg.Point3d.Unset,rg.Point3d.Unset,rg.LoftType.Normal,False)
+if spb:
+ for b in spb:
+ b2=rg.Brep.CapPlanarHoles(b,tol)
+ doc.Objects.AddBrep(b2 if b2 else b,asp)
+
+doc.Views.Redraw()
+print("Omega Tower: mullions=%d Done." % nm)
+'''
+
+ # Try to set the code on the Python component
+ code_set = False
+ for prop_name in ("Code", "ScriptSource", "Expression"):
+ try:
+ prop = py_comp.GetType().GetProperty(prop_name)
+ if prop and prop.CanWrite:
+ prop.SetValue(py_comp, TOWER_CODE, None)
+ code_set = True
+ print("Code set via property: %s" % prop_name)
+ break
+ except:
+ pass
+
+ if not code_set:
+ print("NOTE: Could not auto-set code. Open the Python component and paste from:")
+ print(" scratch/omega_tower.py")
+
+ # ── Wire sliders to Python component inputs ───────────────────────────────
+ # Ordered to match expected GHPython input variable names
+ SLIDER_ORDER = [
+ "base_r","waist_r","top_r","height","squircle_n","twist_deg",
+ "u_divs","v_divs","mul_w_base","mul_w_top","mul_d_base","mul_d_top",
+ "zone_solid","zone_glass","glass_t","glass_inset",
+ "sun_azimuth","sun_altitude","fin_len","fin_thick","fin_step",
+ "floor_h","slab_t","slab_in",
+ "col_n","col_depth","col_angle","col_h",
+ ]
+
+ n_wired = 0
+ try:
+ inputs = py_comp.Params.Input
+ n_inputs = inputs.Count if hasattr(inputs, 'Count') else len(inputs)
+
+ for idx, sname in enumerate(SLIDER_ORDER):
+ if sname not in sliders: continue
+ slider = sliders[sname]
+
+ # Ensure there are enough input params; GHPython auto-expands in ZUI
+ if idx < n_inputs:
+ target_param = inputs[idx]
+ else:
+ break # Can't add inputs externally without ZUI
+
+ # Rename the input param to match the slider
+ try:
+ target_param.NickName = sname
+ target_param.Name = sname
+ except: pass
+
+ # Wire: slider output[0] → python input[idx]
+ try:
+ source = slider.Params.Output[0]
+ target_param.AddSource(source)
+ n_wired += 1
+ except Exception as e:
+ pass # Some params don't allow AddSource externally
+
+ print("Wires connected: %d / %d" % (n_wired, len(SLIDER_ORDER)))
+ except Exception as wire_err:
+ print("Wiring note: %s" % str(wire_err))
+ print(" Connect sliders manually by dragging wires in GH canvas.")
+
+# =============================================================================
+# ANNOTATION PANEL
+# =============================================================================
+add_panel(
+ "OMEGA TOWER — AEC Omni-Bridge\n"
+ "Squircle-twisted parametric skyscraper\n"
+ "Adjust any slider and press TAB to update.\n"
+ "\n"
+ "Systems:\n"
+ " A Tower form squircle + twist loft\n"
+ " B Diagrid variable section depth\n"
+ " C Corten base solid cladding zone\n"
+ " D Glass mid high-perf IGU panels\n"
+ " E Open crown structural expression\n"
+ " F Solar fins sun-responsive louvers\n"
+ " G Floor slabs concrete edge plates\n"
+ " H Branch cols recursive tree columns\n"
+ " I Crown spire tapered steel needle",
+ PY_X + 240, PY_Y
+)
+
+# =============================================================================
+# RE-ENABLE + REFRESH
+# =============================================================================
+gd.Enabled = True
+try:
+ gd.ExpireSolution()
+except: pass
+canvas.Refresh()
+
+print("")
+print("GH definition built:")
+print(" Sliders : %d" % total_sliders)
+print(" Groups : 6 colour-coded")
+print(" Python : 1 component (%s)" % ("code embedded" if py_proxy else "add manually"))
+print("")
+print("Tip: In GH canvas, press Ctrl+A, then Ctrl+Shift+P to arrange layout")
diff --git a/scratch/omega_gh_builder2.py b/scratch/omega_gh_builder2.py
new file mode 100644
index 0000000..9ac8f55
--- /dev/null
+++ b/scratch/omega_gh_builder2.py
@@ -0,0 +1,196 @@
+import clr, System, System.Drawing as sd
+import System.Reflection as rf
+clr.AddReference("Grasshopper")
+import Grasshopper as gh
+from Grasshopper.Kernel import GH_Document
+from Grasshopper.Kernel.Special import GH_NumberSlider, GH_Group, GH_Panel
+
+# ── Document ──────────────────────────────────────────────────────────────────
+canvas = gh.Instances.ActiveCanvas
+gd = canvas.Document
+if gd is None:
+ gd = GH_Document()
+ canvas.Document = gd
+gd.Objects.Clear()
+gd.Enabled = False
+print("Canvas ready — cleared")
+
+# ── Helpers ───────────────────────────────────────────────────────────────────
+def sl(name, mn, mx, val, x, y, dec=2):
+ s = GH_NumberSlider()
+ s.CreateAttributes()
+ s.Name = name; s.NickName = name
+ s.Slider.Minimum = System.Decimal(mn)
+ s.Slider.Maximum = System.Decimal(mx)
+ s.Slider.Value = System.Decimal(val)
+ s.Slider.DecimalPlaces = dec
+ s.Attributes.Pivot = sd.PointF(float(x), float(y))
+ gd.AddObject(s, False)
+ return s
+
+def grp(title, rgba, objs):
+ g = GH_Group(); g.NickName = title
+ g.Colour = sd.Color.FromArgb(*rgba)
+ for o in objs: g.AddObject(o.InstanceGuid)
+ gd.AddObject(g, False)
+ return g
+
+def pan(text, x, y):
+ p = GH_Panel(); p.CreateAttributes()
+ p.UserText = text
+ p.Attributes.Pivot = sd.PointF(float(x), float(y))
+ gd.AddObject(p, False)
+ return p
+
+# ── Slider layout (6 groups, 28 sliders) ─────────────────────────────────────
+A = 80; B = 290; H = 32; GP = 24
+sliders = {}; y = 60
+
+specs = [
+ # (group_title, rgba, [ (name, min, max, val, col, rel_row, dec), ... ])
+ ("A TOWER FORM", (45, 80, 135, 55), [
+ ("base_r", 5., 60., 26., A, 0, 1),
+ ("waist_r", 3., 50., 14.5, B, 0, 1),
+ ("top_r", 5., 55., 21., A, 1, 1),
+ ("height", 50., 600., 272., B, 1, 1),
+ ("squircle_n", 2., 8., 3.5, A, 2, 2),
+ ("twist_deg", 0., 180., 72., B, 2, 1),
+ ]),
+ ("B DIAGRID SYSTEM", (135, 80, 45, 55), [
+ ("u_divs", 20, 80, 52, A, 0, 0),
+ ("v_divs", 12, 48, 24, B, 0, 0),
+ ("mul_w_base", 0.1, 0.8, 0.30, A, 1, 3),
+ ("mul_w_top", 0.05,0.4, 0.12, B, 1, 3),
+ ("mul_d_base", 0.15,1.2, 0.52, A, 2, 3),
+ ("mul_d_top", 0.08,0.6, 0.20, B, 2, 3),
+ ]),
+ ("C/D FACADE ZONES", (45, 135, 80, 55), [
+ ("zone_solid", 0., 0.5, 0.22, A, 0, 3),
+ ("zone_glass", 0.5, 1.0, 0.80, B, 0, 3),
+ ("glass_t", 0.01,0.06,0.028,A, 1, 3),
+ ("glass_inset", 0.02,0.2, 0.09, B, 1, 3),
+ ]),
+ ("F SOLAR FINS", (135, 120, 40, 55), [
+ ("sun_azimuth", 0., 360., 195., A, 0, 1),
+ ("sun_altitude", 5., 85., 40., B, 0, 1),
+ ("fin_len", 0.2, 3.0, 1.1, A, 1, 2),
+ ("fin_thick", 0.02,0.2, 0.055,B,1, 3),
+ ("fin_step", 1, 6, 2, A, 2, 0),
+ ]),
+ ("G FLOOR PLATES", (80, 80, 80, 55), [
+ ("floor_h", 2.5, 6.5, 4.3, A, 0, 2),
+ ("slab_t", 0.15,0.6, 0.30, B, 0, 3),
+ ("slab_in", 0.05,0.4, 0.14, A, 1, 3),
+ ]),
+]
+
+for grp_title, grp_rgba, items in specs:
+ g_objs = []
+ rows = max(r for _, _, _, _, _, r, _ in items)
+ for name, mn, mx, val, col, row, dec in items:
+ s = sl(name, mn, mx, val, col, y + row * H, dec)
+ g_objs.append(s); sliders[name] = s
+ grp(grp_title, grp_rgba, g_objs)
+ y += (rows + 1) * H + GP
+
+print("Sliders: %d" % len(sliders))
+
+# ── Python Script component ───────────────────────────────────────────────────
+PX = 580; PY_COMP_Y = 60
+GHPY_GUID = System.Guid("410755b1-224a-4c1e-a407-bf32fb45ea7e")
+
+server = gh.Instances.ComponentServer
+py_proxy = None
+for proxy in server.ObjectProxies:
+ try:
+ if proxy.Guid == GHPY_GUID:
+ py_proxy = proxy
+ break
+ except: pass
+if py_proxy is None:
+ for proxy in server.ObjectProxies:
+ try:
+ nm = proxy.Desc.Name.lower()
+ if "ghpython" in nm or "ironpython 2" in nm:
+ py_proxy = proxy
+ break
+ except: pass
+
+if py_proxy:
+ py_comp = py_proxy.CreateInstance()
+ py_comp.CreateAttributes()
+ py_comp.Attributes.Pivot = sd.PointF(float(PX), float(PY_COMP_Y))
+ gd.AddObject(py_comp, False)
+ print("Python component: %s" % py_proxy.Desc.Name)
+
+ # Wire available inputs (typically 2 default: x, y)
+ SLIDER_ORDER = [
+ "base_r","waist_r","top_r","height","squircle_n","twist_deg",
+ "u_divs","v_divs","mul_w_base","mul_w_top","mul_d_base","mul_d_top",
+ "zone_solid","zone_glass","glass_t","glass_inset",
+ "sun_azimuth","sun_altitude","fin_len","fin_thick","fin_step",
+ "floor_h","slab_t","slab_in",
+ ]
+
+ # ── Add inputs until we have enough ──────────────────────────────────────
+ from Grasshopper.Kernel import GH_ParameterSide
+ target = len(SLIDER_ORDER)
+ added = 0
+ while py_comp.Params.Input.Count < target:
+ try:
+ idx_new = py_comp.Params.Input.Count
+ param = py_comp.CreateParameter(GH_ParameterSide.Input, idx_new)
+ py_comp.Params.RegisterInputParam(param)
+ added += 1
+ except Exception as e:
+ print(" add input failed at %d: %s" % (py_comp.Params.Input.Count, e))
+ break
+ try:
+ py_comp.VariableParameterMaintenance()
+ py_comp.Params.OnParametersChanged()
+ except: pass
+ print("Inputs after expansion: %d (added %d)" % (py_comp.Params.Input.Count, added))
+
+ # ── Wire sliders → inputs ─────────────────────────────────────────────────
+ # GH_NumberSlider IS an IGH_Param itself — AddSource takes it directly
+ wired = 0
+ for idx, sname in enumerate(SLIDER_ORDER):
+ if sname not in sliders: continue
+ if idx >= py_comp.Params.Input.Count: break
+ try:
+ ip = py_comp.Params.Input[idx]
+ ip.NickName = sname; ip.Name = sname
+ ip.AddSource(sliders[sname])
+ wired += 1
+ except Exception as e:
+ print(" wire[%d] %s: %s" % (idx, sname, e))
+
+ print("Wired: %d / %d" % (wired, target))
+else:
+ print("WARNING: GhPython component not found — add manually from GH toolbar")
+
+# ── Info panel ────────────────────────────────────────────────────────────────
+pan(
+ "OMEGA TOWER | AEC Omni-Bridge MCP\n"
+ "Squircle-twisted performative skyscraper\n\n"
+ "Geometry baked in Rhino (run omega_tower.py):\n"
+ " 2496 diagrid members tapered section base→crown\n"
+ " 260 corten cladding solid base 0-22%\n"
+ " 1508 diamond glass IGU mid zone 22-80%\n"
+ " 360 solar fins sun az=195 alt=40\n"
+ " 61 floor slabs squircle profile\n"
+ " 1 crown spire\n\n"
+ "TO USE GH SLIDERS:\n"
+ "1. Open Python component (double-click)\n"
+ "2. Paste code from omega_tower.py\n"
+ "3. Click the + (ZUI) to add 24 inputs\n"
+ "4. Name them matching the slider NickNames\n"
+ "5. Drag wires slider > input\n"
+ "6. Press TAB to update geometry",
+ PX + 260, PY_COMP_Y
+),
+
+# ── Re-enable ─────────────────────────────────────────────────────────────────
+gd.Enabled = True
+canvas.Refresh()
+print("GH definition complete (objects: %d)" % gd.ObjectCount)
diff --git a/scratch/omega_set_code.py b/scratch/omega_set_code.py
new file mode 100644
index 0000000..d2dd879
--- /dev/null
+++ b/scratch/omega_set_code.py
@@ -0,0 +1,39 @@
+import clr, System, System.Reflection as rf
+clr.AddReference("Grasshopper")
+import Grasshopper as gh
+
+canvas = gh.Instances.ActiveCanvas
+gd = canvas.Document
+GHPY_GUID = System.Guid("410755b1-224a-4c1e-a407-bf32fb45ea7e")
+py_comp = None
+for obj in gd.Objects:
+ try:
+ if hasattr(obj, "ComponentGuid") and obj.ComponentGuid == GHPY_GUID:
+ py_comp = obj; break
+ except: pass
+
+if py_comp is None:
+ print("GhPython component not found in canvas")
+ raise SystemExit
+
+# Read the GH-aware tower code from file (IronPython can open() files normally)
+code_path = r"C:\Users\sammo\OneDrive\Documenten\GitHub\Autodesk-Revit-MCP-Server\scratch\omega_tower_gh.py"
+with open(code_path, "r") as f:
+ code = f.read()
+
+print("Read code: %d chars, %d lines" % (len(code), len(code.splitlines())))
+
+# Set via Code property
+t = py_comp.GetType()
+prop = t.GetProperty("Code", rf.BindingFlags.Public | rf.BindingFlags.Instance)
+if prop and prop.CanWrite:
+ prop.SetValue(py_comp, code, None)
+ print("Code embedded successfully")
+ try:
+ py_comp.ExpireSolution(False)
+ except: pass
+else:
+ print("Code property not settable")
+
+canvas.Refresh()
+print("Done")
diff --git a/scratch/omega_tower.py b/scratch/omega_tower.py
new file mode 100644
index 0000000..3ecce11
--- /dev/null
+++ b/scratch/omega_tower.py
@@ -0,0 +1,622 @@
+# =============================================================================
+# OMEGA TOWER — Adaptive Performative Facade System
+# AEC Omni-Bridge MCP Showcase | Run via bridge or Rhino PythonEdit (F5)
+#
+# Systems:
+# A Squircle-twisted NURBS tower (variable profile, 72° rotation)
+# B Diagrid frame — tapered sections, heavier at base
+# C Facade zone 1: solid weathering steel cladding (base 0-22%)
+# D Facade zone 2: high-performance glass IGU (22-80%)
+# E Facade zone 3: open structural crown (80-100%)
+# F Solar fin system — louvers oriented by sun vector at each node
+# G Floor plates — squircle profile slabs at every 4.3 m
+# H Branching ground columns — recursive binary tree, 3 levels
+# I Crown spire — tapered steel needle
+# J 5 PBR materials + 7 layers
+# =============================================================================
+
+import math
+import Rhino
+import Rhino.Geometry as rg
+import Rhino.DocObjects as rdo
+import Rhino.Display as rdp
+import scriptcontext as sc
+import System.Drawing as sd
+
+sc.doc = Rhino.RhinoDoc.ActiveDoc
+doc = sc.doc
+tol = doc.ModelAbsoluteTolerance
+S = Rhino.RhinoMath.UnitScale(Rhino.UnitSystem.Meters, doc.ModelUnitSystem)
+
+# =============================================================================
+# MASTER PARAMETERS ← These map 1-to-1 with GH sliders
+# =============================================================================
+
+# A. Tower form
+BASE_R = 26.0 # base radius (m)
+WAIST_R = 14.5 # waist radius at ~40% height (m)
+TOP_R = 21.0 # crown radius (m)
+HEIGHT = 272.0 # total height (~63 floors at 4.3 m)
+WAIST_T = 0.42 # fractional height of waist (0.3–0.6)
+SQUIRCLE_N = 3.5 # 2.0 = circle | 4.0 = rounded-square | 8.0 = near-square
+TWIST_DEG = 72.0 # total profile rotation from base to crown (degrees)
+PROFILE_PTS = 64 # points per ring cross-section (smoothness)
+LOFT_RINGS = 22 # loft guide rings (accuracy)
+
+# B. Diagrid
+U_DIVS = 52 # height rows (U = HEIGHT on the loft surface)
+V_DIVS = 24 # circumference columns (V = CIRCUMFERENCE)
+MUL_W_BASE = 0.30 # face width at base (m)
+MUL_W_TOP = 0.12 # face width at crown (m)
+MUL_D_BASE = 0.52 # structural depth at base (m)
+MUL_D_TOP = 0.20 # structural depth at crown (m)
+
+# C/D/E. Facade zones (fractions of total height)
+ZONE_SOLID = 0.22 # solid cladding below this
+ZONE_GLASS = 0.80 # glass panels between solid and this; open crown above
+
+# D. Glass panels
+GLASS_T = 0.028 # IGU depth (m)
+GLASS_SB = 0.030 # setback behind facade plane (m)
+GLASS_INSET = 0.09 # corner reveal fraction (0 = full panel, 0.15 = exposed frame)
+
+# F. Solar fins
+FIN_ON = True
+SUN_AZ = 195.0 # azimuth degrees from North (SW orientation)
+SUN_ALT = 40.0 # solar altitude (degrees above horizon)
+FIN_LEN = 1.10 # projection length (m)
+FIN_THICK = 0.055 # fin thickness (m)
+FIN_STEP = 2 # place fin at every Nth height division
+
+# G. Floor plates
+FLOOR_H = 4.3 # floor-to-floor height (m)
+SLAB_T = 0.30 # concrete slab thickness (m)
+SLAB_IN = 0.14 # inset from facade (m)
+
+
+# I. Crown spire
+SPIRE_H = 38.0 # spire extension above roof (m)
+SPIRE_BASE_R = 1.80 # spire base radius (m)
+SPIRE_TIP_R = 0.08 # spire tip radius (m)
+
+CLEAR_BEFORE = True
+
+# =============================================================================
+# UTILITIES
+# =============================================================================
+
+def smoothstep(a, b, t):
+ t = max(0.0, min(1.0, t))
+ t = t * t * (3.0 - 2.0 * t)
+ return a + (b - a) * t
+
+def tower_r(t):
+ """Radius at normalised height t ∈ [0,1]. Non-symmetric waist."""
+ if t <= WAIST_T:
+ return smoothstep(BASE_R, WAIST_R, t / WAIST_T)
+ return smoothstep(WAIST_R, TOP_R, (t - WAIST_T) / (1.0 - WAIST_T))
+
+def copysign_py(mag, sgn):
+ return abs(mag) if sgn >= 0 else -abs(mag)
+
+def squircle_xy(angle, r, n):
+ """Superellipse point at given angle, radius r, exponent n."""
+ c = math.cos(angle)
+ s = math.sin(angle)
+ x = r * copysign_py(abs(c) ** (2.0 / n), c)
+ y = r * copysign_py(abs(s) ** (2.0 / n), s)
+ return x, y
+
+def make_layer(name, rgb, clear=CLEAR_BEFORE):
+ idx = doc.Layers.FindByFullPath(name, -1)
+ if idx < 0:
+ lyr = rdo.Layer()
+ lyr.Name = name
+ lyr.Color = sd.Color.FromArgb(*rgb)
+ idx = doc.Layers.Add(lyr)
+ else:
+ doc.Layers[idx].Color = sd.Color.FromArgb(*rgb)
+ if clear:
+ objs = doc.Objects.FindByLayer(name)
+ if objs:
+ for o in objs:
+ doc.Objects.Delete(o, True)
+ return idx
+
+def make_attr(layer_idx, mat_idx):
+ a = rdo.ObjectAttributes()
+ a.LayerIndex = layer_idx
+ a.MaterialIndex = mat_idx
+ a.MaterialSource = rdo.ObjectMaterialSource.MaterialFromObject
+ return a
+
+def dot3(a, b):
+ return a.X*b.X + a.Y*b.Y + a.Z*b.Z
+
+def project_to_plane(pt, origin, unit_n):
+ d = (pt.X-origin.X)*unit_n.X + (pt.Y-origin.Y)*unit_n.Y + (pt.Z-origin.Z)*unit_n.Z
+ return rg.Point3d(pt.X - d*unit_n.X, pt.Y - d*unit_n.Y, pt.Z - d*unit_n.Z)
+
+# =============================================================================
+# MATERIALS (PBR first, standard fallback)
+# =============================================================================
+
+def _purge_layer(name):
+ """Delete all objects on a named layer (idempotent)."""
+ idx = doc.Layers.FindByFullPath(name, -1)
+ if idx < 0: return
+ objs = doc.Objects.FindByLayer(name)
+ if objs:
+ for o in objs:
+ doc.Objects.Delete(o, True)
+
+# Purge stale layers left by older script versions
+_purge_layer("Columns")
+
+def add_mat(name, base_c4f, metallic, roughness, diffuse_rgb,
+ transp=0.0, refl=0.0, shine=0.5, opacity=1.0, ior=1.5):
+ # Reuse existing material so colours don't accumulate across re-runs
+ existing = doc.Materials.Find(name, True)
+ if existing >= 0:
+ m = doc.Materials[existing]
+ else:
+ m = rdo.Material()
+ m.Name = name
+ try:
+ m.ToPhysicallyBased()
+ pb = m.PhysicallyBased
+ pb.BaseColor = rdp.Color4f(*base_c4f)
+ pb.Metallic = metallic
+ pb.Roughness = roughness
+ try: pb.Opacity = opacity
+ except: pass
+ try: pb.OpacityIOR = ior
+ except: pass
+ except: pass
+ m.DiffuseColor = sd.Color.FromArgb(*diffuse_rgb)
+ m.Transparency = transp
+ m.Reflectivity = refl
+ m.FresnelReflections = True
+ m.Shine = int(shine * rdo.Material.MaxShine)
+ if existing >= 0:
+ doc.Materials.Modify(m, existing, True)
+ return existing
+ return doc.Materials.Add(m)
+
+mat_frame = add_mat("DarkAluminium",
+ (0.038, 0.040, 0.048, 1.0), 0.94, 0.17, (30, 32, 38),
+ refl=0.87, shine=0.74)
+
+mat_glass = add_mat("PerfGlass_IGU",
+ (0.68, 0.84, 0.94, 1.0), 0.00, 0.02, (170, 210, 240),
+ transp=0.92, refl=0.86, shine=0.98, opacity=0.08, ior=1.52)
+
+mat_corten = add_mat("CortenSteelBase",
+ (0.16, 0.055, 0.018, 1.0), 0.80, 0.48, (105, 48, 18),
+ refl=0.42, shine=0.30)
+
+mat_fin = add_mat("AluminiumFin",
+ (0.52, 0.48, 0.40, 1.0), 0.65, 0.22, (155, 142, 115),
+ refl=0.60, shine=0.55)
+
+mat_slab = add_mat("ExposedConcrete",
+ (0.26, 0.26, 0.24, 1.0), 0.00, 0.82, (132, 130, 122),
+ refl=0.06, shine=0.04)
+
+
+mat_spire = add_mat("BrightStainless",
+ (0.78, 0.76, 0.74, 1.0), 0.96, 0.08, (200, 195, 188),
+ refl=0.92, shine=0.90)
+
+# =============================================================================
+# LAYERS
+# =============================================================================
+
+l_frame = make_layer("Diagrid", (35, 38, 46))
+l_glass = make_layer("Glass", (60, 140, 210))
+l_clad = make_layer("Cladding", (105, 50, 20))
+l_fins = make_layer("SolarFins", (158, 144, 112))
+l_slabs = make_layer("FloorSlabs", (140, 136, 126))
+l_spire = make_layer("Spire", (195, 190, 182))
+
+a_frame = make_attr(l_frame, mat_frame)
+a_glass = make_attr(l_glass, mat_glass)
+a_clad = make_attr(l_clad, mat_corten)
+a_fins = make_attr(l_fins, mat_fin)
+a_slab = make_attr(l_slabs, mat_slab)
+a_spire = make_attr(l_spire, mat_spire)
+
+# =============================================================================
+# A — TOWER SURFACE (squircle twisted loft)
+# =============================================================================
+print("A: Building tower surface...")
+
+loft_crvs = []
+for k in range(LOFT_RINGS + 1):
+ t = float(k) / LOFT_RINGS
+ r = tower_r(t)
+ twist = math.radians(TWIST_DEG * t)
+ z = t * HEIGHT * S
+
+ ring = []
+ for p in range(PROFILE_PTS):
+ angle = 2.0 * math.pi * p / PROFILE_PTS + twist
+ x, y = squircle_xy(angle, r * S, SQUIRCLE_N)
+ ring.append(rg.Point3d(x, y, z))
+
+ crv = rg.NurbsCurve.CreateInterpolatedCurve(
+ ring, 3, rg.CurveKnotStyle.ChordPeriodic)
+ if crv:
+ loft_crvs.append(crv)
+ else:
+ # Fallback: degree-3 through points (close manually)
+ ring.append(ring[0])
+ crv2 = rg.NurbsCurve.CreateInterpolatedCurve(ring, 3)
+ if crv2: loft_crvs.append(crv2)
+
+breps = rg.Brep.CreateFromLoft(loft_crvs, rg.Point3d.Unset, rg.Point3d.Unset,
+ rg.LoftType.Normal, False)
+if not breps:
+ print("ERROR: loft failed"); raise SystemExit
+
+face = breps[0].Faces[0]
+face.SetDomain(0, rg.Interval(0, 1))
+face.SetDomain(1, rg.Interval(0, 1))
+
+# Build UV grid (diagrid node positions)
+pts = []
+for i in range(U_DIVS + 1):
+ row = []
+ u = float(i) / U_DIVS
+ for j in range(V_DIVS + 1):
+ v = float(j) / V_DIVS
+ row.append(face.PointAt(u, v))
+ pts.append(row)
+
+print(" Squircle n=%.1f twist=%.0f deg rings=%d" % (SQUIRCLE_N, TWIST_DEG, LOFT_RINGS))
+
+# Diamond-panel helpers — U=HEIGHT (i), V=CIRCUMFERENCE (j wraps)
+# Use pts array directly so shapes are geometrically correct regardless of
+# surface parameterisation uniformity (squircle curves are chord-length spaced).
+def gpt(hi, ci):
+ return pts[hi][ci % V_DIVS]
+
+def cc_pt(hi, ci):
+ """Geometric centroid of the four surrounding grid corners."""
+ j0 = ci % V_DIVS; j1 = (ci + 1) % V_DIVS
+ p0=pts[hi][j0]; p1=pts[hi][j1]; p2=pts[hi+1][j0]; p3=pts[hi+1][j1]
+ return rg.Point3d((p0.X+p1.X+p2.X+p3.X)*0.25,
+ (p0.Y+p1.Y+p2.Y+p3.Y)*0.25,
+ (p0.Z+p1.Z+p2.Z+p3.Z)*0.25)
+
+# =============================================================================
+# B — DIAGRID FRAME (variable section: deeper + wider at base)
+# =============================================================================
+print("B: Building diagrid frame...")
+
+n_mul = 0
+for i in range(U_DIVS):
+ for j in range(V_DIVS):
+ t_h = (float(i) + 0.5) / U_DIVS # normalised height at cell centre
+ mw = (MUL_W_BASE + (MUL_W_TOP - MUL_W_BASE) * t_h) * S
+ md = (MUL_D_BASE + (MUL_D_TOP - MUL_D_BASE) * t_h) * S
+
+ # Heavier section in solid base zone
+ if t_h < ZONE_SOLID:
+ mw *= 1.35; md *= 1.55
+
+ diags = [
+ (pts[i ][j ], pts[i + 1][j + 1]),
+ (pts[i + 1][j ], pts[i ][j + 1]),
+ ]
+ for p0, p1 in diags:
+ line = rg.LineCurve(p0, p1)
+ ok, fr = line.PerpendicularFrameAt(line.Domain.Min)
+ if not ok: continue
+
+ mid = line.PointAt(line.Domain.Mid)
+ ok2, cu, cv = face.ClosestPoint(mid)
+ if not ok2: continue
+ sn = face.NormalAt(cu, cv)
+ sn.Unitize()
+
+ tang = fr.ZAxis
+ t_n = dot3(tang, sn)
+ depth = rg.Vector3d(sn.X - t_n*tang.X, sn.Y - t_n*tang.Y, sn.Z - t_n*tang.Z)
+ if not depth.Unitize(): continue
+ width = rg.Vector3d.CrossProduct(tang, depth)
+ if not width.Unitize(): continue
+
+ rect = rg.Rectangle3d(rg.Plane.WorldXY,
+ rg.Interval(-mw*0.5, mw*0.5),
+ rg.Interval(-md, 0.0))
+ prof = rect.ToNurbsCurve()
+ sweep_pln = rg.Plane(fr.Origin, width, depth)
+ xf = rg.Transform.PlaneToPlane(rg.Plane.WorldXY, sweep_pln)
+ prof.Transform(xf)
+
+ swept = rg.Brep.CreateFromSweep(line, prof, True, tol)
+ if swept:
+ for b in swept: doc.Objects.AddBrep(b, a_frame)
+ n_mul += 1
+
+print(" Mullion sweeps: %d" % n_mul)
+
+# =============================================================================
+# C/D — FACADE PANELS
+# Solid base (UV quad corten) : 0 → ZONE_SOLID
+# Glass zone (diamond panels) : ZONE_SOLID → ZONE_GLASS
+# Crown (open structural frame) : ZONE_GLASS → 1.0
+#
+# Diamond topology identical to diagrid_tower_glass.py:
+# Type A : cc(i,j)→gpt(i+1,j+1)→cc(i,j+1)→gpt(i,j+1)
+# Type B : cc(i,j)→gpt(i+1,j)→cc(i+1,j)→gpt(i+1,j+1)
+# Bot cap : gpt(i0,j)→gpt(i0,j+1)→cc(i0,j)
+# Top cap : cc(ie-1,j)→gpt(ie,j+1)→gpt(ie,j)
+# =============================================================================
+print("C/D: Building facade panels...")
+
+def _surf_cn(pts_list):
+ """Surface normal + centroid for a list of surface points."""
+ cx = sum(p.X for p in pts_list) / len(pts_list)
+ cy = sum(p.Y for p in pts_list) / len(pts_list)
+ cz = sum(p.Z for p in pts_list) / len(pts_list)
+ c = rg.Point3d(cx, cy, cz)
+ ok, cu, cv = face.ClosestPoint(c)
+ if not ok: return None, None
+ n = face.NormalAt(cu, cv)
+ return (c, n) if n.Unitize() else (None, None)
+
+def _solid_6face(verts_f, verts_b, attr):
+ """Build and bake a 6-face closed solid from front and back quad vertices."""
+ f, b = verts_f, verts_b
+ surfs = [
+ rg.NurbsSurface.CreateFromCorners(f[0],f[1],f[2],f[3]),
+ rg.NurbsSurface.CreateFromCorners(b[0],b[3],b[2],b[1]),
+ rg.NurbsSurface.CreateFromCorners(f[0],f[1],b[1],b[0]),
+ rg.NurbsSurface.CreateFromCorners(f[1],f[2],b[2],b[1]),
+ rg.NurbsSurface.CreateFromCorners(f[2],f[3],b[3],b[2]),
+ rg.NurbsSurface.CreateFromCorners(f[3],f[0],b[0],b[3]),
+ ]
+ faces_b = [s.ToBrep() for s in surfs if s]
+ if len(faces_b) < 6: return False
+ j2 = rg.Brep.JoinBreps(faces_b, tol)
+ if j2: doc.Objects.AddBrep(j2[0], attr)
+ return bool(j2)
+
+def _solid_5face(verts_f, verts_b, attr):
+ """Build and bake a 5-face closed solid from front and back triangle vertices."""
+ f, b = verts_f, verts_b
+ surfs = [
+ rg.NurbsSurface.CreateFromCorners(f[0],f[1],f[2]),
+ rg.NurbsSurface.CreateFromCorners(b[0],b[2],b[1]),
+ rg.NurbsSurface.CreateFromCorners(f[0],f[1],b[1],b[0]),
+ rg.NurbsSurface.CreateFromCorners(f[1],f[2],b[2],b[1]),
+ rg.NurbsSurface.CreateFromCorners(f[2],f[0],b[0],b[2]),
+ ]
+ faces_b = [s.ToBrep() for s in surfs if s]
+ if len(faces_b) < 5: return False
+ j2 = rg.Brep.JoinBreps(faces_b, tol)
+ if j2: doc.Objects.AddBrep(j2[0], attr)
+ return bool(j2)
+
+def diamond_quad(A, B, C, D, thick, setback, attr):
+ """Diamond glass panel: vertices ARE the structural nodes (no corner inset)."""
+ c, n = _surf_cn([A, B, C, D])
+ if c is None: return False
+ off = n * (-setback); tv = n * (-thick)
+ fv = [p + off for p in [A, B, C, D]]
+ bv = [p + tv for p in fv]
+ return _solid_6face(fv, bv, attr)
+
+def diamond_tri(A, B, C, thick, setback, attr):
+ """Triangular glass cap panel."""
+ c, n = _surf_cn([A, B, C])
+ if c is None: return False
+ off = n * (-setback); tv = n * (-thick)
+ fv = [p + off for p in [A, B, C]]
+ bv = [p + tv for p in fv]
+ return _solid_5face(fv, bv, attr)
+
+def rect_corten(p1, p2, p3, p4, thick, setback, inset, attr):
+ """UV-quad solid cladding panel with corner inset."""
+ c, n = _surf_cn([p1, p2, p3, p4])
+ if c is None: return False
+ k = 1.0 - inset
+ gi = [rg.Point3d(c.X+(p.X-c.X)*k, c.Y+(p.Y-c.Y)*k, c.Z+(p.Z-c.Z)*k)
+ for p in [p1, p2, p3, p4]]
+ fp = [project_to_plane(g, c, n) for g in gi]
+ off = n * (-setback); tv = n * (-thick)
+ fv = [rg.Point3d(f.X+off.X, f.Y+off.Y, f.Z+off.Z) for f in fp]
+ bv = [rg.Point3d(f.X+tv.X, f.Y+tv.Y, f.Z+tv.Z ) for f in fv]
+ return _solid_6face(fv, bv, attr)
+
+# ── Solid corten base (UV quads) ──────────────────────────────────────────────
+n_clad = 0
+for i in range(U_DIVS):
+ if (float(i) + 0.5) / U_DIVS >= ZONE_SOLID: break
+ for j in range(V_DIVS):
+ p1=pts[i][j]; p2=pts[i+1][j]; p3=pts[i+1][j+1]; p4=pts[i][j+1]
+ if rect_corten(p1,p2,p3,p4, 0.055*S, 0.018*S, 0.03, a_clad):
+ n_clad += 1
+
+# ── Diamond glass panels ──────────────────────────────────────────────────────
+i_solid = int(round(ZONE_SOLID * U_DIVS))
+i_glass = min(int(round(ZONE_GLASS * U_DIVS)), U_DIVS)
+n_glass = 0
+
+# Bottom-zone transition caps (left-triangle of first glass row)
+for j in range(V_DIVS):
+ if diamond_tri(gpt(i_solid,j), gpt(i_solid,j+1), cc_pt(i_solid,j),
+ GLASS_T*S, GLASS_SB*S, a_glass):
+ n_glass += 1
+
+# Type A: top-tri(i,j) + bottom-tri(i,j+1) merged as rhombus
+for i in range(i_solid, i_glass):
+ for j in range(V_DIVS):
+ if diamond_quad(cc_pt(i,j), gpt(i+1,j+1), cc_pt(i,j+1), gpt(i,j+1),
+ GLASS_T*S, GLASS_SB*S, a_glass):
+ n_glass += 1
+
+# Type B: right-tri(i,j) + left-tri(i+1,j) merged as rhombus
+for i in range(i_solid, i_glass - 1):
+ for j in range(V_DIVS):
+ if diamond_quad(cc_pt(i,j), gpt(i+1,j), cc_pt(i+1,j), gpt(i+1,j+1),
+ GLASS_T*S, GLASS_SB*S, a_glass):
+ n_glass += 1
+
+# Top-zone transition caps (right-triangle of last glass row)
+for j in range(V_DIVS):
+ if diamond_tri(cc_pt(i_glass-1,j), gpt(i_glass,j+1), gpt(i_glass,j),
+ GLASS_T*S, GLASS_SB*S, a_glass):
+ n_glass += 1
+
+print(" Corten panels: %d Diamond glass: %d" % (n_clad, n_glass))
+
+# =============================================================================
+# F — SOLAR FIN SYSTEM (louvers oriented perpendicular to projected sun ray)
+# =============================================================================
+if FIN_ON:
+ print("F: Building solar fins...")
+
+ az_r = math.radians(SUN_AZ)
+ alt_r = math.radians(SUN_ALT)
+ sun_v = rg.Vector3d(math.sin(az_r)*math.cos(alt_r),
+ math.cos(az_r)*math.cos(alt_r),
+ math.sin(alt_r))
+ sun_v.Unitize()
+
+ n_fins = 0
+ for i in range(U_DIVS):
+ for j in range(0, V_DIVS, FIN_STEP):
+ t_h = float(j) / V_DIVS
+ if t_h < ZONE_SOLID or t_h > ZONE_GLASS:
+ continue
+
+ node = pts[i][j]
+ ok_cp, cu, cv = face.ClosestPoint(node)
+ if not ok_cp: continue
+ sn = face.NormalAt(cu, cv)
+ if not sn.Unitize(): continue
+
+ # Project sun vector onto surface tangent plane
+ d_sn = dot3(sun_v, sn)
+ proj = rg.Vector3d(sun_v.X - d_sn*sn.X,
+ sun_v.Y - d_sn*sn.Y,
+ sun_v.Z - d_sn*sn.Z)
+ if proj.Length < 0.01:
+ proj = rg.Vector3d(0, 0, 1)
+ proj.Unitize()
+
+ # Fin faces the sun: width direction is cross(sn, proj_sun)
+ fw = rg.Vector3d.CrossProduct(sn, proj)
+ if not fw.Unitize(): continue
+
+ fl = FIN_LEN * S
+ ft = FIN_THICK * S
+ base_off = sn * (0.02 * S) # tiny lift off facade
+
+ c1 = rg.Point3d(node.X + base_off.X - fw.X*ft*0.5,
+ node.Y + base_off.Y - fw.Y*ft*0.5,
+ node.Z + base_off.Z)
+ c2 = rg.Point3d(c1.X + fw.X*ft, c1.Y + fw.Y*ft, c1.Z)
+ c3 = rg.Point3d(c2.X + sn.X*fl, c2.Y + sn.Y*fl, c2.Z + sn.Z*fl)
+ c4 = rg.Point3d(c1.X + sn.X*fl, c1.Y + sn.Y*fl, c1.Z + sn.Z*fl)
+
+ fin_s = rg.NurbsSurface.CreateFromCorners(c1, c2, c3, c4)
+ if fin_s:
+ doc.Objects.AddSurface(fin_s, a_fins)
+ n_fins += 1
+
+ print(" Solar fins: %d (sun az=%.0f° alt=%.0f°)" % (n_fins, SUN_AZ, SUN_ALT))
+
+# =============================================================================
+# G — FLOOR PLATES (squircle profile follows tower twist + taper)
+# =============================================================================
+print("G: Building floor plates...")
+
+n_floors_actual = int(HEIGHT / FLOOR_H)
+n_slabs = 0
+
+for fl_idx in range(1, n_floors_actual + 1):
+ z_frac = float(fl_idx) * FLOOR_H / HEIGHT
+ if z_frac >= 1.0: break
+ z = z_frac * HEIGHT * S
+
+ twist = math.radians(TWIST_DEG * z_frac)
+ r = tower_r(z_frac) - SLAB_IN
+
+ slab_ring = []
+ for p in range(PROFILE_PTS):
+ angle = 2.0 * math.pi * p / PROFILE_PTS + twist
+ x, y = squircle_xy(angle, r * S, SQUIRCLE_N)
+ slab_ring.append(rg.Point3d(x, y, z))
+
+ slab_crv = rg.NurbsCurve.CreateInterpolatedCurve(
+ slab_ring, 3, rg.CurveKnotStyle.ChordPeriodic)
+ if not slab_crv:
+ slab_ring.append(slab_ring[0])
+ slab_crv = rg.NurbsCurve.CreateInterpolatedCurve(slab_ring, 3)
+ if not slab_crv: continue
+
+ try:
+ extrusion = rg.Extrusion.Create(slab_crv, SLAB_T * S, True)
+ if extrusion:
+ doc.Objects.AddExtrusion(extrusion, a_slab)
+ n_slabs += 1
+ continue
+ except: pass
+ # fallback: planar cap only
+ flat = rg.Brep.CreatePlanarBreps(slab_crv, tol)
+ if flat:
+ for fb in flat:
+ doc.Objects.AddBrep(fb, a_slab)
+ n_slabs += 1
+
+print(" Floor slabs: %d" % n_slabs)
+
+# =============================================================================
+# I — CROWN SPIRE (tapered stainless needle)
+# =============================================================================
+print("I: Building crown spire...")
+
+spire_rings = []
+for k in range(6):
+ t = float(k) / 5.0
+ r_s = (SPIRE_BASE_R + (SPIRE_TIP_R - SPIRE_BASE_R) * (t*t)) * S
+ z_s = (HEIGHT + SPIRE_H * t) * S
+ spire_rings.append(rg.Circle(
+ rg.Plane(rg.Point3d(0, 0, z_s), rg.Vector3d.ZAxis), r_s
+ ).ToNurbsCurve())
+
+sp_brep = rg.Brep.CreateFromLoft(spire_rings, rg.Point3d.Unset, rg.Point3d.Unset,
+ rg.LoftType.Normal, False)
+if sp_brep:
+ for b in sp_brep:
+ b2 = rg.Brep.CapPlanarHoles(b, tol)
+ doc.Objects.AddBrep(b2 if b2 else b, a_spire)
+ print(" Spire: OK")
+
+# =============================================================================
+# DONE
+# =============================================================================
+doc.Views.Redraw()
+
+print("")
+print("=" * 58)
+print("OMEGA TOWER — Complete")
+print(" Diagrid members : %d" % n_mul)
+print(" Corten cladding : %d (zone 0 – %.0f%%)" % (n_clad, ZONE_SOLID*100))
+print(" Glass IGU panels : %d (zone %.0f%% – %.0f%%)" % (n_glass, ZONE_SOLID*100, ZONE_GLASS*100))
+if FIN_ON:
+ print(" Solar fins : %d" % n_fins)
+print(" Floor slabs : %d (@ %.1f m)" % (n_slabs, FLOOR_H))
+print(" Crown spire : 1")
+print("=" * 58)
+print("Next: Rendered display mode + HDRI sky for final image")
+
+# Restore GH scriptcontext if running inside a Grasshopper component
+try:
+ sc.doc = ghdoc
+except NameError:
+ pass
diff --git a/scratch/omega_tower_gh.py b/scratch/omega_tower_gh.py
new file mode 100644
index 0000000..0075e23
--- /dev/null
+++ b/scratch/omega_tower_gh.py
@@ -0,0 +1,267 @@
+# =============================================================================
+# OMEGA TOWER — Grasshopper-aware version
+# All parameters read from GH input ports; defaults used when standalone.
+# Paste this into the GhPython Script component that omega_gh_builder2.py created.
+# =============================================================================
+
+import math
+import Rhino, Rhino.Geometry as rg, Rhino.DocObjects as rdo
+import Rhino.Display as rdp, scriptcontext as sc, System.Drawing as sd
+
+# ── GH input helpers ─────────────────────────────────────────────────────────
+def _f(v, d):
+ try: return float(v) if v is not None else d
+ except: return d
+def _i(v, d):
+ try: return int(float(v)) if v is not None else d
+ except: return d
+
+# ── Parameters (read from wired sliders, fallback to defaults) ───────────────
+BASE_R = _f(base_r, 26.0)
+WAIST_R = _f(waist_r, 14.5)
+TOP_R = _f(top_r, 21.0)
+HEIGHT = _f(height, 272.0)
+SQUIRCLE_N = _f(squircle_n, 3.5)
+TWIST_DEG = _f(twist_deg, 72.0)
+U_DIVS = _i(u_divs, 24)
+V_DIVS = _i(v_divs, 52)
+MUL_W_BASE = _f(mul_w_base, 0.30)
+MUL_W_TOP = _f(mul_w_top, 0.12)
+MUL_D_BASE = _f(mul_d_base, 0.52)
+MUL_D_TOP = _f(mul_d_top, 0.20)
+ZONE_SOLID = _f(zone_solid, 0.22)
+ZONE_GLASS = _f(zone_glass, 0.80)
+GLASS_T = _f(glass_t, 0.028)
+GLASS_INSET = _f(glass_inset, 0.09)
+SUN_AZ = _f(sun_azimuth, 195.0)
+SUN_ALT = _f(sun_altitude,40.0)
+FIN_LEN = _f(fin_len, 1.10)
+FIN_THICK = _f(fin_thick, 0.055)
+FIN_STEP = _i(fin_step, 2)
+FLOOR_H = _f(floor_h, 4.3)
+SLAB_T = _f(slab_t, 0.30)
+SLAB_IN = _f(slab_in, 0.14)
+COL_N = _i(col_n, 8)
+COL_DEPTH = _i(col_depth, 3)
+COL_ANGLE = _f(col_angle, 26.0)
+COL_H = _f(col_h, 15.0)
+
+WAIST_T = 0.42
+PROFILE_PTS = 64
+LOFT_RINGS = 22
+SPIRE_H = 38.0; SPIRE_BASE_R = 1.80; SPIRE_TIP_R = 0.08
+FIN_ON = True; CLEAR_BEFORE = True
+
+doc = sc.doc; tol = doc.ModelAbsoluteTolerance
+S = Rhino.RhinoMath.UnitScale(Rhino.UnitSystem.Meters, doc.ModelUnitSystem)
+
+# ── Utilities ─────────────────────────────────────────────────────────────────
+def smoothstep(a,b,t):
+ t=max(0.0,min(1.0,t)); t=t*t*(3.0-2.0*t); return a+(b-a)*t
+def tower_r(t):
+ if t<=WAIST_T: return smoothstep(BASE_R,WAIST_R,t/WAIST_T)
+ return smoothstep(WAIST_R,TOP_R,(t-WAIST_T)/(1.0-WAIST_T))
+def cs(m,s): return abs(m) if s>=0 else -abs(m)
+def sqxy(ang,r,n):
+ c=math.cos(ang); s=math.sin(ang)
+ return r*cs(abs(c)**(2.0/n),c), r*cs(abs(s)**(2.0/n),s)
+def mk_layer(name,rgb):
+ idx=doc.Layers.FindByFullPath(name,-1)
+ if idx<0:
+ lyr=rdo.Layer(); lyr.Name=name; lyr.Color=sd.Color.FromArgb(*rgb)
+ idx=doc.Layers.Add(lyr)
+ elif CLEAR_BEFORE:
+ objs=doc.Objects.FindByLayer(name)
+ if objs:
+ for o in objs: doc.Objects.Delete(o,True)
+ return idx
+def mk_attr(li,mi):
+ a=rdo.ObjectAttributes(); a.LayerIndex=li; a.MaterialIndex=mi
+ a.MaterialSource=rdo.ObjectMaterialSource.MaterialFromObject; return a
+def d3(a,b): return a.X*b.X+a.Y*b.Y+a.Z*b.Z
+def prj(pt,o,n):
+ d=(pt.X-o.X)*n.X+(pt.Y-o.Y)*n.Y+(pt.Z-o.Z)*n.Z
+ return rg.Point3d(pt.X-d*n.X,pt.Y-d*n.Y,pt.Z-d*n.Z)
+def add_m(nm,bc,me,ro,dif,tr=0.0,re=0.0,sh=0.5,op=1.0):
+ m=rdo.Material(); m.Name=nm
+ try:
+ m.ToPhysicallyBased(); pb=m.PhysicallyBased
+ pb.BaseColor=rdp.Color4f(*bc); pb.Metallic=me; pb.Roughness=ro
+ try: pb.Opacity=op
+ except: pass
+ except: pass
+ m.DiffuseColor=sd.Color.FromArgb(*dif); m.Transparency=tr
+ m.Reflectivity=re; m.FresnelReflections=True
+ m.Shine=int(sh*rdo.Material.MaxShine); return doc.Materials.Add(m)
+
+# ── Materials ─────────────────────────────────────────────────────────────────
+mf =add_m("Frame", (0.038,0.040,0.048,1.0),0.94,0.17,(30,32,38), re=0.87,sh=0.74)
+mg =add_m("Glass", (0.025,0.14,0.09,1.0), 0.00,0.01,(10,58,40), tr=0.88,re=0.94,sh=0.96,op=0.10)
+mc =add_m("Corten", (0.16,0.055,0.018,1.0),0.80,0.48,(105,48,18), re=0.42,sh=0.30)
+mfi=add_m("Fin", (0.52,0.48,0.40,1.0), 0.65,0.22,(155,142,115),re=0.60,sh=0.55)
+ms =add_m("Slab", (0.26,0.26,0.24,1.0), 0.00,0.82,(132,130,122),re=0.06,sh=0.04)
+mco=add_m("Col", (0.20,0.07,0.022,1.0),0.82,0.44,(118,55,22), re=0.40,sh=0.28)
+msp=add_m("Spire", (0.78,0.76,0.74,1.0), 0.96,0.08,(200,195,188),re=0.92,sh=0.90)
+
+# ── Layers ────────────────────────────────────────────────────────────────────
+lf =mk_layer("Diagrid",(35,38,46)); lg =mk_layer("Glass",(12,65,45))
+lc =mk_layer("Cladding",(105,50,20)); lfn=mk_layer("SolarFins",(158,144,112))
+lsl=mk_layer("FloorSlabs",(140,136,126)); lco=mk_layer("Columns",(112,52,20))
+lsp=mk_layer("Spire",(195,190,182))
+af=mk_attr(lf,mf); ag=mk_attr(lg,mg); ac=mk_attr(lc,mc)
+afn=mk_attr(lfn,mfi); asl=mk_attr(lsl,ms); aco=mk_attr(lco,mco); asp=mk_attr(lsp,msp)
+
+# ── A: Tower surface ──────────────────────────────────────────────────────────
+loft=[]
+for k in range(LOFT_RINGS+1):
+ t=float(k)/LOFT_RINGS; r=tower_r(t)
+ twist=math.radians(TWIST_DEG*t); z=t*HEIGHT*S
+ ring=[rg.Point3d(sqxy(2.0*math.pi*p/PROFILE_PTS+twist,r*S,SQUIRCLE_N)[0],
+ sqxy(2.0*math.pi*p/PROFILE_PTS+twist,r*S,SQUIRCLE_N)[1],z)
+ for p in range(PROFILE_PTS)]
+ crv=rg.NurbsCurve.CreateInterpolatedCurve(ring,3,rg.CurveKnotStyle.ChordPeriodic)
+ if not crv: ring.append(ring[0]); crv=rg.NurbsCurve.CreateInterpolatedCurve(ring,3)
+ if crv: loft.append(crv)
+breps=rg.Brep.CreateFromLoft(loft,rg.Point3d.Unset,rg.Point3d.Unset,rg.LoftType.Normal,False)
+if not breps: print("Loft failed"); raise SystemExit
+face=breps[0].Faces[0]
+face.SetDomain(0,rg.Interval(0,1)); face.SetDomain(1,rg.Interval(0,1))
+pts=[[face.PointAt(float(i)/U_DIVS,float(j)/V_DIVS) for j in range(V_DIVS+1)] for i in range(U_DIVS+1)]
+
+# ── B: Diagrid frame ──────────────────────────────────────────────────────────
+nm=0
+for i in range(U_DIVS):
+ for j in range(V_DIVS):
+ th=(float(j)+0.5)/V_DIVS
+ mw=(MUL_W_BASE+(MUL_W_TOP-MUL_W_BASE)*th)*S
+ md=(MUL_D_BASE+(MUL_D_TOP-MUL_D_BASE)*th)*S
+ if th<ZONE_SOLID: mw*=1.35; md*=1.55
+ for p0,p1 in [(pts[i][j],pts[i+1][j+1]),(pts[i+1][j],pts[i][j+1])]:
+ line=rg.LineCurve(p0,p1); ok,fr=line.PerpendicularFrameAt(line.Domain.Min)
+ if not ok: continue
+ mid=line.PointAt(line.Domain.Mid); ok2,cu,cv=face.ClosestPoint(mid)
+ if not ok2: continue
+ sn=face.NormalAt(cu,cv); sn.Unitize(); tang=fr.ZAxis
+ tn=d3(tang,sn); dep=rg.Vector3d(sn.X-tn*tang.X,sn.Y-tn*tang.Y,sn.Z-tn*tang.Z)
+ if not dep.Unitize(): continue
+ wid=rg.Vector3d.CrossProduct(tang,dep)
+ if not wid.Unitize(): continue
+ rect=rg.Rectangle3d(rg.Plane.WorldXY,rg.Interval(-mw*0.5,mw*0.5),rg.Interval(-md,0.0))
+ prof=rect.ToNurbsCurve()
+ spln=rg.Plane(fr.Origin,wid,dep); xf=rg.Transform.PlaneToPlane(rg.Plane.WorldXY,spln)
+ prof.Transform(xf)
+ sw=rg.Brep.CreateFromSweep(line,prof,True,tol)
+ if sw:
+ for b in sw: doc.Objects.AddBrep(b,af)
+ nm+=1
+
+# ── C/D: Facade panels (zone-aware) ──────────────────────────────────────────
+def panel(p1,p2,p3,p4,t,sb,ins,c,n,attr):
+ k=1.0-ins
+ gi=[rg.Point3d(c.X+(p.X-c.X)*k,c.Y+(p.Y-c.Y)*k,c.Z+(p.Z-c.Z)*k) for p in[p1,p2,p3,p4]]
+ fp=[prj(g,c,n) for g in gi]; off=n*(-sb)
+ sp=[rg.Point3d(f.X+off.X,f.Y+off.Y,f.Z+off.Z) for f in fp]; tv=n*(-t)
+ bp=[rg.Point3d(s.X+tv.X,s.Y+tv.Y,s.Z+tv.Z) for s in sp]
+ ss=[rg.NurbsSurface.CreateFromCorners(sp[0],sp[1],sp[2],sp[3]),
+ rg.NurbsSurface.CreateFromCorners(bp[0],bp[3],bp[2],bp[1]),
+ rg.NurbsSurface.CreateFromCorners(sp[0],sp[1],bp[1],bp[0]),
+ rg.NurbsSurface.CreateFromCorners(sp[1],sp[2],bp[2],bp[1]),
+ rg.NurbsSurface.CreateFromCorners(sp[2],sp[3],bp[3],bp[2]),
+ rg.NurbsSurface.CreateFromCorners(sp[3],sp[0],bp[0],bp[3])]
+ fb=[s.ToBrep() for s in ss if s]
+ if len(fb)<6: return
+ j2=rg.Brep.JoinBreps(fb,tol)
+ if j2: doc.Objects.AddBrep(j2[0],attr)
+
+for i in range(U_DIVS):
+ for j in range(V_DIVS):
+ th=(float(j)+0.5)/V_DIVS
+ if th>ZONE_GLASS: continue
+ p1=pts[i][j];p2=pts[i+1][j];p3=pts[i+1][j+1];p4=pts[i][j+1]
+ cx=(p1.X+p2.X+p3.X+p4.X)*0.25;cy=(p1.Y+p2.Y+p3.Y+p4.Y)*0.25;cz=(p1.Z+p2.Z+p3.Z+p4.Z)*0.25
+ c=rg.Point3d(cx,cy,cz); ok,cu,cv=face.ClosestPoint(c)
+ if not ok: continue
+ n=face.NormalAt(cu,cv)
+ if not n.Unitize(): continue
+ if th<ZONE_SOLID: panel(p1,p2,p3,p4,0.055*S,0.018*S,0.03,c,n,ac)
+ else: panel(p1,p2,p3,p4,GLASS_T*S,0.030*S,GLASS_INSET,c,n,ag)
+
+# ── F: Solar fins ─────────────────────────────────────────────────────────────
+if FIN_ON:
+ az=math.radians(SUN_AZ); alt=math.radians(SUN_ALT)
+ sv=rg.Vector3d(math.sin(az)*math.cos(alt),math.cos(az)*math.cos(alt),math.sin(alt)); sv.Unitize()
+ for i in range(U_DIVS):
+ for j in range(0,V_DIVS,FIN_STEP):
+ th=float(j)/V_DIVS
+ if th<ZONE_SOLID or th>ZONE_GLASS: continue
+ nd=pts[i][j]; ok,cu,cv=face.ClosestPoint(nd)
+ if not ok: continue
+ sn=face.NormalAt(cu,cv)
+ if not sn.Unitize(): continue
+ dsn=d3(sv,sn); pj=rg.Vector3d(sv.X-dsn*sn.X,sv.Y-dsn*sn.Y,sv.Z-dsn*sn.Z)
+ if pj.Length<0.01: pj=rg.Vector3d(0,0,1)
+ pj.Unitize(); fw=rg.Vector3d.CrossProduct(sn,pj)
+ if not fw.Unitize(): continue
+ fl=FIN_LEN*S; ft=FIN_THICK*S; bo=sn*(0.02*S)
+ c1=rg.Point3d(nd.X+bo.X-fw.X*ft*0.5,nd.Y+bo.Y-fw.Y*ft*0.5,nd.Z+bo.Z)
+ c2=rg.Point3d(c1.X+fw.X*ft,c1.Y+fw.Y*ft,c1.Z)
+ c3=rg.Point3d(c2.X+sn.X*fl,c2.Y+sn.Y*fl,c2.Z+sn.Z*fl)
+ c4=rg.Point3d(c1.X+sn.X*fl,c1.Y+sn.Y*fl,c1.Z+sn.Z*fl)
+ fs=rg.NurbsSurface.CreateFromCorners(c1,c2,c3,c4)
+ if fs: doc.Objects.AddSurface(fs,afn)
+
+# ── G: Floor slabs ────────────────────────────────────────────────────────────
+nfl=int(HEIGHT/FLOOR_H)
+for fi in range(1,nfl+1):
+ zf=float(fi)*FLOOR_H/HEIGHT
+ if zf>=1.0: break
+ z=zf*HEIGHT*S; tw=math.radians(TWIST_DEG*zf); r=tower_r(zf)-SLAB_IN
+ if r<=0.5: continue
+ sr=[rg.Point3d(sqxy(2.0*math.pi*p/PROFILE_PTS+tw,r*S,SQUIRCLE_N)[0],
+ sqxy(2.0*math.pi*p/PROFILE_PTS+tw,r*S,SQUIRCLE_N)[1],z)
+ for p in range(PROFILE_PTS)]
+ sc2=rg.NurbsCurve.CreateInterpolatedCurve(sr,3,rg.CurveKnotStyle.ChordPeriodic)
+ if not sc2: sr.append(sr[0]); sc2=rg.NurbsCurve.CreateInterpolatedCurve(sr,3)
+ if not sc2: continue
+ try:
+ ex=rg.Extrusion.Create(sc2,SLAB_T*S,True)
+ if ex: doc.Objects.AddExtrusion(ex,asl); continue
+ except: pass
+ flat=rg.Brep.CreatePlanarBreps(sc2,tol)
+ if flat:
+ for fb in flat: doc.Objects.AddBrep(fb,asl)
+
+# ── H: Branching columns ──────────────────────────────────────────────────────
+def grow(st,dr,ln,rad,dep,out):
+ en=rg.Point3d(st.X+dr.X*ln,st.Y+dr.Y*ln,st.Z+dr.Z*ln)
+ pp=rg.Brep.CreatePipe(rg.LineCurve(st,en),rad,True,rg.PipeCapMode.Flat,False,tol,tol)
+ if pp: out.extend(pp)
+ if dep<COL_DEPTH:
+ ar=math.radians(COL_ANGLE); pe=rg.Vector3d(-dr.Y,dr.X,0.0)
+ if pe.Length<1e-6: pe=rg.Vector3d(1,0,0)
+ pe.Unitize()
+ for sg in [1,-1]:
+ rt=rg.Transform.Rotation(sg*ar,pe,en); nd2=rg.Vector3d(dr); nd2.Transform(rt); nd2.Unitize()
+ grow(en,nd2,ln*0.60,rad*0.62,dep+1,out)
+
+cb=[]
+for k in range(COL_N):
+ ang=2.0*math.pi*k/COL_N
+ xb,yb=sqxy(ang,BASE_R*0.85*S,SQUIRCLE_N)
+ grow(rg.Point3d(xb,yb,0.0),rg.Vector3d(0,0,1),COL_H*S,0.44*S,0,cb)
+for b in cb: doc.Objects.AddBrep(b,aco)
+
+# ── I: Crown spire ────────────────────────────────────────────────────────────
+sr2=[]
+for k in range(6):
+ t=float(k)/5.0; rs=(SPIRE_BASE_R+(SPIRE_TIP_R-SPIRE_BASE_R)*(t*t))*S
+ zs=(HEIGHT+SPIRE_H*t)*S
+ sr2.append(rg.Circle(rg.Plane(rg.Point3d(0,0,zs),rg.Vector3d.ZAxis),rs).ToNurbsCurve())
+spb=rg.Brep.CreateFromLoft(sr2,rg.Point3d.Unset,rg.Point3d.Unset,rg.LoftType.Normal,False)
+if spb:
+ for b in spb:
+ b2=rg.Brep.CapPlanarHoles(b,tol)
+ doc.Objects.AddBrep(b2 if b2 else b,asp)
+
+doc.Views.Redraw()
+print("Omega Tower: %d diagrid | BASE_R=%.1f TWIST=%.0f SQUIRCLE=%.1f" % (nm,BASE_R,TWIST_DEG,SQUIRCLE_N))
diff --git a/scratch/rhino_diagrid_tower.py b/scratch/rhino_diagrid_tower.py
new file mode 100644
index 0000000..502ecbd
--- /dev/null
+++ b/scratch/rhino_diagrid_tower.py
@@ -0,0 +1,410 @@
+# =============================================================================
+# rhino_diagrid_tower.py
+# Parametric diagrid skyscraper — run directly in Rhino 8 Python Script Editor
+# or send via the MCP bridge (run_python command).
+#
+# HOW TO RUN IN RHINO:
+# Type "PythonEdit" in Rhino → File > Open this file → press Run (F5)
+# Adjust the PARAMETERS block below and re-run to iterate.
+#
+# HOW TO RUN VIA MCP BRIDGE:
+# python scratch/diagrid_tower_python.py (sends this file to the bridge)
+#
+# BUILDABLE GEOMETRY GUARANTEES:
+# - Glass panels are projected onto a flat plane before extrusion → truly planar IGUs
+# - Mullion depth axis is locked to the outward surface normal at each midpoint
+# - All glass solids are 6-face closed Breps (watertight)
+# - Mullion sweeps are capped closed (CreateFromSweep with closed=True)
+# - Materials: PBR tried first (Rhino 7/8), standard fallback for all display modes
+# =============================================================================
+
+import Rhino
+import Rhino.Geometry as rg
+import Rhino.DocObjects as rdo
+import Rhino.Display as rdp
+import scriptcontext as sc
+import System.Drawing as sd
+
+doc = sc.doc
+tol = doc.ModelAbsoluteTolerance
+
+# =============================================================================
+# PARAMETERS ← edit this block to iterate
+# All dimensions in metres — script converts to document units automatically.
+# =============================================================================
+
+# -- Tower form ---------------------------------------------------------------
+BASE_R = 22.0 # base radius (m) → wider = more imposing ground presence
+WAIST_R = 13.5 # waist radius (m) → smaller = more dramatic hyperboloid pinch
+TOP_R = 19.0 # crown radius (m) → larger than waist = outward flare at top
+HEIGHT = 180.0 # total height (m) → ~45 stories at 4 m/floor
+
+# -- Diagrid density ----------------------------------------------------------
+# Rule of thumb: U_DIVS sets structural bays around the perimeter.
+# Each bay at the base ≈ 2π × BASE_R / U_DIVS = panel width.
+# V_DIVS sets bays up the height. 2 floors per bay is structurally typical.
+U_DIVS = 20 # panels around circumference (20 → ~6.9 m per bay at base)
+V_DIVS = 40 # panels up the height (40 → 4.5 m per bay = 1 floor)
+
+# -- Structural member cross-section (metres) ---------------------------------
+MUL_W = 0.20 # visible face width of each member (200 mm)
+MUL_D = 0.40 # structural depth — goes inward from facade (400 mm)
+
+# -- Glazing (metres) ---------------------------------------------------------
+GLASS_T = 0.028 # IGU thickness — 28 mm = high-performance triple-glazed unit
+INSET = 0.14 # fraction each glass corner is pulled toward panel centre
+ # 0.12–0.18 is realistic for exposed-framing curtain walls
+SETBACK = 0.025 # glass set back behind facade plane (25 mm)
+
+# -- Appearance ---------------------------------------------------------------
+CLEAR_BEFORE = True # delete previous "Mullions" and "Glass" layer objects before running
+
+
+# =============================================================================
+# END OF PARAMETERS
+# =============================================================================
+
+# -- Scale: convert metres to document units ----------------------------------
+S = Rhino.RhinoMath.UnitScale(rg.UnitSystem.Meters, doc.ModelUnitSystem)
+
+BASE_R *= S; WAIST_R *= S; TOP_R *= S; HEIGHT *= S
+MUL_W *= S; MUL_D *= S
+GLASS_T *= S; SETBACK *= S
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# UTILITIES
+# ─────────────────────────────────────────────────────────────────────────────
+
+def smoothstep(a, b, t):
+ """Smooth cubic ease between a and b (no overshoot)."""
+ e = t * t * (3.0 - 2.0 * t)
+ return a + (b - a) * e
+
+def tower_r(t):
+ """Radius at normalised height t ∈ [0,1]: base → waist → crown."""
+ if t <= 0.5:
+ return smoothstep(BASE_R, WAIST_R, t * 2.0)
+ return smoothstep(WAIST_R, TOP_R, (t - 0.5) * 2.0)
+
+def dot3(a, b):
+ return a.X*b.X + a.Y*b.Y + a.Z*b.Z
+
+def vec_scale(v, s):
+ return rg.Vector3d(v.X*s, v.Y*s, v.Z*s)
+
+def pt_shift(p, v):
+ return rg.Point3d(p.X+v.X, p.Y+v.Y, p.Z+v.Z)
+
+def project_onto_plane(pt, origin, unit_normal):
+ """Orthographic projection of pt onto a plane defined by origin and unit normal."""
+ d = (pt.X-origin.X)*unit_normal.X + (pt.Y-origin.Y)*unit_normal.Y + (pt.Z-origin.Z)*unit_normal.Z
+ return rg.Point3d(pt.X - d*unit_normal.X,
+ pt.Y - d*unit_normal.Y,
+ pt.Z - d*unit_normal.Z)
+
+def get_or_make_layer(name, color, clear_objects):
+ if clear_objects:
+ # Remove all objects on this layer before rebuilding
+ for obj in doc.Objects.FindByLayer(name) or []:
+ doc.Objects.Delete(obj, True)
+ for layer in doc.Layers:
+ if layer.Name == name and not layer.IsDeleted:
+ return layer.Index
+ lyr = rdo.Layer()
+ lyr.Name = name
+ lyr.Color = color
+ return doc.Layers.Add(lyr)
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# STEP 1 — TOWER SURFACE
+# Smooth hyperboloid lofted from 13 ring circles.
+# More rings = cleaner normal sampling across the full height.
+# ─────────────────────────────────────────────────────────────────────────────
+RINGS = 13
+loft_crvs = []
+for k in range(RINGS + 1):
+ t = float(k) / RINGS
+ r = tower_r(t)
+ z = t * HEIGHT
+ pln = rg.Plane(rg.Point3d(0, 0, z), rg.Vector3d.ZAxis)
+ loft_crvs.append(rg.Circle(pln, r).ToNurbsCurve())
+
+breps = rg.Brep.CreateFromLoft(
+ loft_crvs, rg.Point3d.Unset, rg.Point3d.Unset, rg.LoftType.Normal, False)
+
+if not breps:
+ print("ERROR: loft failed — check parameters")
+ raise SystemExit
+
+surf = breps[0]
+face = surf.Faces[0]
+face.SetDomain(0, rg.Interval(0, 1)) # u: 0..1 around circumference
+face.SetDomain(1, rg.Interval(0, 1)) # v: 0..1 up the height
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# STEP 2 — UV GRID
+# pts[i][j] = world-space node at (u=i/U_DIVS, v=j/V_DIVS) on the surface.
+# Nodes are the diagrid connection points (structural nodes / curtain-wall corners).
+# ─────────────────────────────────────────────────────────────────────────────
+pts = []
+for i in range(U_DIVS + 1):
+ row = []
+ u = float(i) / U_DIVS
+ for j in range(V_DIVS + 1):
+ v = float(j) / V_DIVS
+ row.append(face.PointAt(u, v))
+ pts.append(row)
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# STEP 3 — MULLION CROSS-SECTION PROFILE
+# Rectangle in WorldXY: width along X (what you see from street), depth along Y.
+# Y=0 is the outward face of the member; Y=-MUL_D is the inward (hidden) back face.
+# This gets re-oriented per-member in Step 4.
+# ─────────────────────────────────────────────────────────────────────────────
+profile_rect = rg.Rectangle3d(
+ rg.Plane.WorldXY,
+ rg.Interval(-MUL_W * 0.5, MUL_W * 0.5),
+ rg.Interval(-MUL_D, 0.0)
+)
+profile_crv = profile_rect.ToNurbsCurve()
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# STEP 4 — DIAGRID MEMBER SWEEPS
+# Two diagonals per UV cell: (i,j)→(i+1,j+1) and (i+1,j)→(i,j+1).
+#
+# ORIENTATION FIX (key for buildability):
+# Standard PerpendicularFrameAt gives an arbitrary roll around the tangent.
+# We lock the roll so the depth axis (Y in the profile) aligns with the
+# outward surface normal at the member's midpoint — the structural depth
+# goes INTO the building, which is the only physically meaningful orientation.
+# ─────────────────────────────────────────────────────────────────────────────
+mullion_breps = []
+
+for i in range(U_DIVS):
+ for j in range(V_DIVS):
+ diagonals = [
+ (pts[i ][j ], pts[i + 1][j + 1]), # up-right
+ (pts[i + 1][j ], pts[i ][j + 1]), # up-left
+ ]
+ for p0, p1 in diagonals:
+ line = rg.LineCurve(p0, p1)
+
+ ok_fr, fr = line.PerpendicularFrameAt(line.Domain.Min)
+ if not ok_fr:
+ continue
+
+ # Outward surface normal at the member midpoint
+ mid = line.PointAt(line.Domain.Mid)
+ ok_cp, cu, cv = face.ClosestPoint(mid)
+ if not ok_cp:
+ continue
+ surf_n = face.NormalAt(cu, cv)
+ surf_n.Unitize()
+
+ tangent = fr.ZAxis # unit tangent of the line
+
+ # Gram-Schmidt orthogonalisation:
+ # Remove the tangent component from surf_n → "depth" direction
+ # that lies in the plane perpendicular to the member.
+ t_dot_n = dot3(tangent, surf_n)
+ depth_dir = rg.Vector3d(surf_n.X - t_dot_n * tangent.X,
+ surf_n.Y - t_dot_n * tangent.Y,
+ surf_n.Z - t_dot_n * tangent.Z)
+ if not depth_dir.Unitize():
+ continue
+
+ # Width direction: tangent × depth_dir
+ # → lies in the surface tangent plane, perpendicular to the member
+ width_dir = rg.Vector3d.CrossProduct(tangent, depth_dir)
+ if not width_dir.Unitize():
+ continue
+
+ # Build sweep frame and map profile
+ sweep_pln = rg.Plane(fr.Origin, width_dir, depth_dir)
+ xf = rg.Transform.PlaneToPlane(rg.Plane.WorldXY, sweep_pln)
+
+ oriented = profile_crv.DuplicateCurve()
+ oriented.Transform(xf)
+
+ swept = rg.Brep.CreateFromSweep(line, oriented, True, tol)
+ if swept:
+ mullion_breps.extend(swept)
+
+print("Mullion sweeps: " + str(len(mullion_breps)))
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# STEP 5 — PLANAR GLASS PANELS
+# For each UV quad cell we create a flat glazed panel.
+#
+# BUILDABILITY LOGIC:
+# a) Compute the 4 node corners of the cell.
+# b) Find the outward surface normal at the cell centroid.
+# c) Pull each corner INSET fraction toward the centroid (creates frame reveal).
+# d) PROJECT all 4 inset corners onto the plane through centroid + outward normal.
+# This is the critical step: it converts the slightly doubly-curved UV quad
+# into a perfectly flat panel — exactly what a standard flat-glass IGU is.
+# e) Step back SETBACK behind the facade plane (glass sits inside the frame).
+# f) Create a 6-face closed solid by building front/back/4 side NurbsSurfaces
+# and joining them. Result: a proper solid glass brick, not a surface.
+# ─────────────────────────────────────────────────────────────────────────────
+glass_breps = []
+
+for i in range(U_DIVS):
+ for j in range(V_DIVS):
+ p1 = pts[i ][j ]; p2 = pts[i + 1][j ]
+ p3 = pts[i + 1][j + 1]; p4 = pts[i ][j + 1]
+
+ # Centroid of the quad
+ cx = (p1.X + p2.X + p3.X + p4.X) * 0.25
+ cy = (p1.Y + p2.Y + p3.Y + p4.Y) * 0.25
+ cz = (p1.Z + p2.Z + p3.Z + p4.Z) * 0.25
+ c = rg.Point3d(cx, cy, cz)
+
+ # Outward surface normal at centroid
+ ok_n, cu, cv = face.ClosestPoint(c)
+ if not ok_n:
+ continue
+ n = face.NormalAt(cu, cv)
+ if not n.Unitize():
+ continue
+
+ # Pull each corner (1 - INSET) of the way from centroid to corner
+ def ins(p):
+ return rg.Point3d(c.X + (p.X - c.X) * (1.0 - INSET),
+ c.Y + (p.Y - c.Y) * (1.0 - INSET),
+ c.Z + (p.Z - c.Z) * (1.0 - INSET))
+
+ gi1 = ins(p1); gi2 = ins(p2); gi3 = ins(p3); gi4 = ins(p4)
+
+ # ── Planarity projection ──────────────────────────────────────────────
+ # Project all 4 inset corners onto the tangent plane at centroid.
+ # After this the 4 corners are exactly co-planar → flat glass panel.
+ fp1 = project_onto_plane(gi1, c, n)
+ fp2 = project_onto_plane(gi2, c, n)
+ fp3 = project_onto_plane(gi3, c, n)
+ fp4 = project_onto_plane(gi4, c, n)
+
+ # Step back behind the facade surface
+ sb = vec_scale(n, -SETBACK)
+ sp1 = pt_shift(fp1, sb); sp2 = pt_shift(fp2, sb)
+ sp3 = pt_shift(fp3, sb); sp4 = pt_shift(fp4, sb)
+
+ # Inner glass face (step inward by IGU thickness)
+ tv = vec_scale(n, -GLASS_T)
+ bp1 = pt_shift(sp1, tv); bp2 = pt_shift(sp2, tv)
+ bp3 = pt_shift(sp3, tv); bp4 = pt_shift(sp4, tv)
+
+ # Build the 6-face closed solid
+ # Normal convention: all outer face-normals point away from the solid.
+ front = rg.NurbsSurface.CreateFromCorners(sp1, sp2, sp3, sp4) # outward face
+ back = rg.NurbsSurface.CreateFromCorners(bp1, bp4, bp3, bp2) # inward face (reversed)
+ s_b = rg.NurbsSurface.CreateFromCorners(sp1, sp2, bp2, bp1) # bottom edge
+ s_r = rg.NurbsSurface.CreateFromCorners(sp2, sp3, bp3, bp2) # right edge
+ s_t = rg.NurbsSurface.CreateFromCorners(sp3, sp4, bp4, bp3) # top edge
+ s_l = rg.NurbsSurface.CreateFromCorners(sp4, sp1, bp1, bp4) # left edge
+
+ faces = [ns.ToBrep() for ns in [front, back, s_b, s_r, s_t, s_l] if ns is not None]
+ if len(faces) < 6:
+ continue
+
+ joined = rg.Brep.JoinBreps(faces, tol)
+ if joined:
+ glass_breps.append(joined[0])
+ else:
+ glass_breps.extend(faces) # fallback: open surfaces still render
+
+print("Glass panels: " + str(len(glass_breps)))
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# STEP 6 — PBR MATERIALS
+# ToPhysicallyBased() is tried first (Rhino 7/8).
+# Standard material properties are always set as a fallback for Shaded mode.
+# ─────────────────────────────────────────────────────────────────────────────
+
+def make_aluminum_mat():
+ m = rdo.Material()
+ m.Name = "DarkAnodizedAluminum"
+ try:
+ m.ToPhysicallyBased()
+ pbr = m.PhysicallyBased
+ pbr.BaseColor = rdp.Color4f(0.035, 0.038, 0.046, 1.0)
+ pbr.Metallic = 0.95
+ pbr.Roughness = 0.20
+ for attr in ("Reflectance", "Specular"): # name differs Rhino 7 vs 8
+ try: setattr(pbr, attr, 0.88); break
+ except: pass
+ except: pass
+ m.DiffuseColor = sd.Color.FromArgb(28, 30, 36)
+ m.SpecularColor = sd.Color.FromArgb(150, 158, 168)
+ m.Reflectivity = 0.88
+ m.FresnelReflections = True
+ m.Shine = int(0.70 * rdo.Material.MaxShine)
+ return m
+
+def make_glass_mat():
+ m = rdo.Material()
+ m.Name = "HighPerformanceGlass"
+ try:
+ m.ToPhysicallyBased()
+ pbr = m.PhysicallyBased
+ pbr.BaseColor = rdp.Color4f(0.025, 0.14, 0.08, 1.0)
+ pbr.Metallic = 0.0
+ pbr.Roughness = 0.01 # near-mirror: maximum reflectivity
+ pbr.Opacity = 0.10 # 90% transparent
+ for attr in ("Reflectance", "Specular"):
+ try: setattr(pbr, attr, 0.95); break
+ except: pass
+ try: pbr.OpacityIOR = 1.52
+ except: pass
+ except: pass
+ m.DiffuseColor = sd.Color.FromArgb(15, 68, 48)
+ m.Transparency = 0.88
+ m.Reflectivity = 0.95
+ m.FresnelReflections = True
+ m.IndexOfRefraction = 1.52
+ return m
+
+al_idx = doc.Materials.Add(make_aluminum_mat())
+gl_idx = doc.Materials.Add(make_glass_mat())
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# STEP 7 — LAYERS + BAKE
+# ─────────────────────────────────────────────────────────────────────────────
+mul_layer = get_or_make_layer("Mullions", sd.Color.FromArgb(35, 38, 46), CLEAR_BEFORE)
+gl_layer = get_or_make_layer("Glass", sd.Color.FromArgb(15, 68, 48), CLEAR_BEFORE)
+
+def make_attr(layer_idx, mat_idx):
+ a = rdo.ObjectAttributes()
+ a.LayerIndex = layer_idx
+ a.MaterialIndex = mat_idx
+ a.MaterialSource = rdo.ObjectMaterialSource.MaterialFromObject
+ return a
+
+mul_attr = make_attr(mul_layer, al_idx)
+gl_attr = make_attr(gl_layer, gl_idx)
+
+for b in mullion_breps:
+ doc.Objects.AddBrep(b, mul_attr)
+
+for b in glass_breps:
+ doc.Objects.AddBrep(b, gl_attr)
+
+doc.Views.Redraw()
+
+print("")
+print("Tower complete.")
+print(" " + str(len(mullion_breps)) + " mullion sweeps (dark anodised aluminium PBR)")
+print(" " + str(len(glass_breps)) + " glass panels (high-performance IGU)")
+print("")
+print("Next steps in Rhino:")
+print(" 1. Set display mode to Rendered (V -> Rendered)")
+print(" 2. Open Rendering panel -> Lighting -> add an HDRI sky")
+print(" 3. Edit the PARAMETERS block at the top and re-run to iterate")
diff --git a/scripts/build-addin.ps1 b/scripts/build-addin.ps1
index e9087f5..ced4071 100644
--- a/scripts/build-addin.ps1
+++ b/scripts/build-addin.ps1
@@ -79,3 +79,49 @@ if (Test-Path $navisworksPath) {
Write-Error "Could not find Navisworks output directory: $nwOutDir"
}
}
+
+# Build Rhino Add-in
+$rhinoPath = "$PSScriptRoot\..\packages\rhino-bridge-addin\RhinoBridge.csproj"
+if (Test-Path $rhinoPath) {
+ Write-Host "Building AEC Model Bridge for Rhino ($Configuration)..." -ForegroundColor Cyan
+
+ & $dotnet.Source build $rhinoPath -c $Configuration -v:minimal
+ if ($LASTEXITCODE -ne 0) {
+ Write-Error "Rhino build failed with exit code $LASTEXITCODE"
+ # Don't exit here so we don't fail the whole build if just Rhino fails
+ } else {
+ Write-Host "Rhino Build succeeded" -ForegroundColor Green
+ }
+}
+
+# Build Power BI Tool
+$pbiPath = "$PSScriptRoot\..\packages\powerbi-bridge-tool\PowerBIBridge.csproj"
+if (Test-Path $pbiPath) {
+ Write-Host "Building AEC Model Bridge for Power BI ($Configuration)..." -ForegroundColor Cyan
+
+ & $dotnet.Source build $pbiPath -c $Configuration -v:minimal
+ if ($LASTEXITCODE -ne 0) {
+ Write-Error "Power BI build failed with exit code $LASTEXITCODE"
+ } else {
+ Write-Host "Power BI Build succeeded" -ForegroundColor Green
+
+ # Setup pbitool.json
+ $pbiOutputDir = Join-Path $PSScriptRoot "..\packages\powerbi-bridge-tool\bin\$Configuration\net8.0-windows"
+ $pbiJsonTemplate = Join-Path $PSScriptRoot "..\packages\powerbi-bridge-tool\AECModelBridge.pbitool.json"
+ if (Test-Path $pbiJsonTemplate) {
+ $jsonContent = Get-Content $pbiJsonTemplate -Raw
+ $jsonContent = $jsonContent -replace "%PBITOOL_PATH%", $pbiOutputDir.Replace("\", "\\")
+
+ $pbiExternalToolsDir = "C:\Program Files (x86)\Common Files\Microsoft Shared\Power BI Desktop\External Tools"
+ if (-not (Test-Path $pbiExternalToolsDir)) {
+ New-Item -ItemType Directory -Force -Path $pbiExternalToolsDir | Out-Null
+ }
+ try {
+ Set-Content -Path (Join-Path $pbiExternalToolsDir "AECModelBridge.pbitool.json") -Value $jsonContent
+ Write-Host "Registered Power BI External Tool." -ForegroundColor Green
+ } catch {
+ Write-Host "Could not register Power BI tool (requires admin rights). The tool was built successfully though." -ForegroundColor Yellow
+ }
+ }
+ }
+}
diff --git a/test_e2e.py b/test_e2e.py
new file mode 100644
index 0000000..bd8a7cd
--- /dev/null
+++ b/test_e2e.py
@@ -0,0 +1,37 @@
+import urllib.request
+import time
+import sys
+import json
+import logging
+
+logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
+
+def poll_endpoint(url, name, max_retries=60):
+ for i in range(max_retries):
+ try:
+ req = urllib.request.Request(url)
+ with urllib.request.urlopen(req, timeout=2) as response:
+ if response.status == 200:
+ data = json.loads(response.read().decode())
+ logging.info(f"{name} is UP! Response: {data}")
+ return True
+ except Exception as e:
+ pass
+ logging.info(f"Waiting for {name} to start... (Attempt {i+1}/{max_retries})")
+ time.sleep(5)
+
+ logging.error(f"{name} failed to start or load the bridge add-in after {max_retries*5} seconds.")
+ return False
+
+if __name__ == '__main__':
+ logging.info("Starting E2E Bridge Polling...")
+
+ revit_up = poll_endpoint('http://127.0.0.1:3000/health', 'Revit Bridge (Port 3000)')
+ navis_up = poll_endpoint('http://127.0.0.1:3002/health', 'Navisworks Bridge (Port 3002)')
+
+ if revit_up and navis_up:
+ logging.info("SUCCESS: Both Revit and Navisworks bridges are actively running and responding to the MCP Hub.")
+ sys.exit(0)
+ else:
+ logging.error("FAILURE: One or both bridges did not come online.")
+ sys.exit(1)