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.

Scaffold 2, Task 2.1: Implement bounding box intersection checker

sammohammad5783c4332a3051e
diff --git a/packages/model-checker/src/model_checker/clash_detection.py b/packages/model-checker/src/model_checker/clash_detection.py
new file mode 100644
index 0000000..a9b2d91
--- /dev/null
+++ b/packages/model-checker/src/model_checker/clash_detection.py
@@ -0,0 +1,277 @@
+"""Clash detection functionality for geometric conflicts."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+
+@dataclass
+class BoundingBox:
+ """3D bounding box representation."""
+
+ min_x: float
+ min_y: float
+ min_z: float
+ max_x: float
+ max_y: float
+ max_z: float
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> BoundingBox:
+ """Create BoundingBox from dictionary.
+
+ Args:
+ data: Dictionary with min/max coordinates
+
+ Returns:
+ BoundingBox instance
+ """
+ return cls(
+ min_x=data["min"]["x"],
+ min_y=data["min"]["y"],
+ min_z=data["min"]["z"],
+ max_x=data["max"]["x"],
+ max_y=data["max"]["y"],
+ max_z=data["max"]["z"],
+ )
+
+ def intersects(self, other: BoundingBox) -> bool:
+ """Check if this bounding box intersects with another.
+
+ Uses Separating Axis Theorem (SAT) for axis-aligned bounding boxes.
+ Boxes intersect if they overlap on all three axes.
+
+ Args:
+ other: Another bounding box to check intersection with
+
+ Returns:
+ True if boxes intersect, False otherwise
+ """
+ # Check for separation on each axis (use <= to exclude touching boxes)
+ if self.max_x <= other.min_x or other.max_x <= self.min_x:
+ return False
+ if self.max_y <= other.min_y or other.max_y <= self.min_y:
+ return False
+ if self.max_z <= other.min_z or other.max_z <= self.min_z:
+ return False
+
+ return True
+
+ def get_volume(self) -> float:
+ """Calculate the volume of the bounding box.
+
+ Returns:
+ Volume in cubic units
+ """
+ return (
+ (self.max_x - self.min_x)
+ * (self.max_y - self.min_y)
+ * (self.max_z - self.min_z)
+ )
+
+ def get_intersection_volume(self, other: BoundingBox) -> float:
+ """Calculate the volume of intersection with another box.
+
+ Args:
+ other: Another bounding box
+
+ Returns:
+ Volume of intersection, or 0 if no intersection
+ """
+ if not self.intersects(other):
+ return 0.0
+
+ overlap_x = min(self.max_x, other.max_x) - max(self.min_x, other.min_x)
+ overlap_y = min(self.max_y, other.max_y) - max(self.min_y, other.min_y)
+ overlap_z = min(self.max_z, other.max_z) - max(self.min_z, other.min_z)
+
+ return overlap_x * overlap_y * overlap_z
+
+ def get_center(self) -> tuple[float, float, float]:
+ """Get the center point of the bounding box.
+
+ Returns:
+ Tuple of (x, y, z) coordinates
+ """
+ return (
+ (self.min_x + self.max_x) / 2,
+ (self.min_y + self.max_y) / 2,
+ (self.min_z + self.max_z) / 2,
+ )
+
+
+@dataclass
+class ClashResult:
+ """Result of a clash detection between two elements."""
+
+ element_id_1: str | int
+ element_id_2: str | int
+ clash_type: str
+ intersection_volume: float = 0.0
+ location: dict[str, float] | None = None
+ severity: str = "medium"
+
+ def to_dict(self) -> dict[str, Any]:
+ """Convert clash result to dictionary.
+
+ Returns:
+ Dictionary representation
+ """
+ return {
+ "element_id_1": self.element_id_1,
+ "element_id_2": self.element_id_2,
+ "clash_type": self.clash_type,
+ "intersection_volume": self.intersection_volume,
+ "location": self.location,
+ "severity": self.severity,
+ }
+
+
+class ClashDetector:
+ """Detector for geometric clashes between elements."""
+
+ def __init__(self, tolerance: float = 0.0) -> None:
+ """Initialize clash detector.
+
+ Args:
+ tolerance: Tolerance distance for clash detection (mm)
+ """
+ self.tolerance = tolerance
+ self.clashes: list[ClashResult] = []
+
+ def check_bounding_box_clash(
+ self,
+ element_id_1: str | int,
+ bbox_1: BoundingBox,
+ element_id_2: str | int,
+ bbox_2: BoundingBox,
+ ) -> ClashResult | None:
+ """Check for clash between two bounding boxes.
+
+ Args:
+ element_id_1: ID of first element
+ bbox_1: Bounding box of first element
+ element_id_2: ID of second element
+ bbox_2: Bounding box of second element
+
+ Returns:
+ ClashResult if clash detected, None otherwise
+ """
+ if bbox_1.intersects(bbox_2):
+ intersection_volume = bbox_1.get_intersection_volume(bbox_2)
+ center_1 = bbox_1.get_center()
+ center_2 = bbox_2.get_center()
+
+ location = {
+ "x": (center_1[0] + center_2[0]) / 2,
+ "y": (center_1[1] + center_2[1]) / 2,
+ "z": (center_1[2] + center_2[2]) / 2,
+ }
+
+ # Determine severity based on intersection volume
+ severity = self._calculate_severity(intersection_volume)
+
+ clash = ClashResult(
+ element_id_1=element_id_1,
+ element_id_2=element_id_2,
+ clash_type="bounding_box",
+ intersection_volume=intersection_volume,
+ location=location,
+ severity=severity,
+ )
+
+ self.clashes.append(clash)
+ return clash
+
+ return None
+
+ def check_multiple_elements(
+ self,
+ elements: list[dict[str, Any]],
+ ) -> list[ClashResult]:
+ """Check for clashes between multiple elements.
+
+ Args:
+ elements: List of element dicts with 'id' and 'bounding_box' keys
+
+ Returns:
+ List of detected clashes
+ """
+ clashes = []
+ n = len(elements)
+
+ for i in range(n):
+ elem_1 = elements[i]
+ bbox_1 = elem_1["bounding_box"]
+ if isinstance(bbox_1, dict):
+ bbox_1 = BoundingBox.from_dict(bbox_1)
+
+ for j in range(i + 1, n):
+ elem_2 = elements[j]
+ bbox_2 = elem_2["bounding_box"]
+ if isinstance(bbox_2, dict):
+ bbox_2 = BoundingBox.from_dict(bbox_2)
+
+ clash = self.check_bounding_box_clash(
+ elem_1["id"],
+ bbox_1,
+ elem_2["id"],
+ bbox_2,
+ )
+
+ if clash:
+ clashes.append(clash)
+
+ return clashes
+
+ def _calculate_severity(self, intersection_volume: float) -> str:
+ """Calculate clash severity based on intersection volume.
+
+ Args:
+ intersection_volume: Volume of intersection in cubic mm
+
+ Returns:
+ Severity level: "critical", "high", "medium", or "low"
+ """
+ # Convert mm³ to m³ for easier thresholds
+ volume_m3 = intersection_volume / 1_000_000_000
+
+ if volume_m3 >= 1.0:
+ return "critical"
+ if volume_m3 >= 0.1:
+ return "high"
+ if volume_m3 >= 0.01:
+ return "medium"
+ return "low"
+
+ def get_clashes_by_severity(self, severity: str) -> list[ClashResult]:
+ """Get all clashes of a specific severity.
+
+ Args:
+ severity: Severity level to filter by
+
+ Returns:
+ List of clashes with specified severity
+ """
+ return [clash for clash in self.clashes if clash.severity == severity]
+
+ def get_critical_clashes(self) -> list[ClashResult]:
+ """Get all critical clashes.
+
+ Returns:
+ List of critical clashes
+ """
+ return self.get_clashes_by_severity("critical")
+
+ def get_total_clashes(self) -> int:
+ """Get total number of clashes detected.
+
+ Returns:
+ Number of clashes
+ """
+ return len(self.clashes)
+
+ def clear_clashes(self) -> None:
+ """Clear all stored clashes."""
+ self.clashes = []
diff --git a/packages/model-checker/tests/test_clash_detection.py b/packages/model-checker/tests/test_clash_detection.py
new file mode 100644
index 0000000..3fff4de
--- /dev/null
+++ b/packages/model-checker/tests/test_clash_detection.py
@@ -0,0 +1,335 @@
+"""Test clash detection functionality."""
+
+import pytest
+
+from model_checker.clash_detection import BoundingBox, ClashDetector, ClashResult
+
+
+def test_create_bounding_box():
+ """Test creating a bounding box."""
+ bbox = BoundingBox(
+ min_x=0.0, min_y=0.0, min_z=0.0, max_x=1000.0, max_y=1000.0, max_z=3000.0
+ )
+
+ assert bbox.min_x == 0.0
+ assert bbox.max_z == 3000.0
+
+
+def test_bounding_box_from_dict():
+ """Test creating bounding box from dictionary."""
+ data = {
+ "min": {"x": 100.0, "y": 200.0, "z": 0.0},
+ "max": {"x": 500.0, "y": 600.0, "z": 3000.0},
+ }
+
+ bbox = BoundingBox.from_dict(data)
+
+ assert bbox.min_x == 100.0
+ assert bbox.min_y == 200.0
+ assert bbox.min_z == 0.0
+ assert bbox.max_x == 500.0
+ assert bbox.max_y == 600.0
+ assert bbox.max_z == 3000.0
+
+
+def test_bounding_box_intersects():
+ """Test bounding box intersection detection."""
+ bbox1 = BoundingBox(
+ min_x=0.0, min_y=0.0, min_z=0.0, max_x=1000.0, max_y=1000.0, max_z=3000.0
+ )
+
+ # Overlapping box
+ bbox2 = BoundingBox(
+ min_x=500.0, min_y=500.0, min_z=1000.0, max_x=1500.0, max_y=1500.0, max_z=4000.0
+ )
+
+ assert bbox1.intersects(bbox2) is True
+ assert bbox2.intersects(bbox1) is True
+
+
+def test_bounding_box_no_intersection():
+ """Test bounding boxes that don't intersect."""
+ bbox1 = BoundingBox(
+ min_x=0.0, min_y=0.0, min_z=0.0, max_x=1000.0, max_y=1000.0, max_z=3000.0
+ )
+
+ # Separated box
+ bbox2 = BoundingBox(
+ min_x=2000.0, min_y=2000.0, min_z=0.0, max_x=3000.0, max_y=3000.0, max_z=3000.0
+ )
+
+ assert bbox1.intersects(bbox2) is False
+ assert bbox2.intersects(bbox1) is False
+
+
+def test_bounding_box_volume():
+ """Test bounding box volume calculation."""
+ bbox = BoundingBox(
+ min_x=0.0, min_y=0.0, min_z=0.0, max_x=1000.0, max_y=2000.0, max_z=3000.0
+ )
+
+ volume = bbox.get_volume()
+ assert volume == 1000.0 * 2000.0 * 3000.0
+
+
+def test_intersection_volume():
+ """Test intersection volume calculation."""
+ bbox1 = BoundingBox(
+ min_x=0.0, min_y=0.0, min_z=0.0, max_x=1000.0, max_y=1000.0, max_z=1000.0
+ )
+
+ bbox2 = BoundingBox(
+ min_x=500.0, min_y=500.0, min_z=500.0, max_x=1500.0, max_y=1500.0, max_z=1500.0
+ )
+
+ # Overlap is 500x500x500
+ volume = bbox1.get_intersection_volume(bbox2)
+ assert volume == 500.0 * 500.0 * 500.0
+
+
+def test_no_intersection_volume():
+ """Test intersection volume when boxes don't intersect."""
+ bbox1 = BoundingBox(
+ min_x=0.0, min_y=0.0, min_z=0.0, max_x=1000.0, max_y=1000.0, max_z=1000.0
+ )
+
+ bbox2 = BoundingBox(
+ min_x=2000.0, min_y=2000.0, min_z=2000.0, max_x=3000.0, max_y=3000.0, max_z=3000.0
+ )
+
+ volume = bbox1.get_intersection_volume(bbox2)
+ assert volume == 0.0
+
+
+def test_bounding_box_center():
+ """Test getting center point of bounding box."""
+ bbox = BoundingBox(
+ min_x=0.0, min_y=0.0, min_z=0.0, max_x=1000.0, max_y=2000.0, max_z=3000.0
+ )
+
+ center = bbox.get_center()
+ assert center == (500.0, 1000.0, 1500.0)
+
+
+def test_create_clash_result():
+ """Test creating a clash result."""
+ clash = ClashResult(
+ element_id_1="wall_1",
+ element_id_2="beam_1",
+ clash_type="bounding_box",
+ intersection_volume=125000.0,
+ location={"x": 500.0, "y": 500.0, "z": 1500.0},
+ severity="high",
+ )
+
+ assert clash.element_id_1 == "wall_1"
+ assert clash.element_id_2 == "beam_1"
+ assert clash.clash_type == "bounding_box"
+ assert clash.severity == "high"
+
+
+def test_clash_result_to_dict():
+ """Test converting clash result to dictionary."""
+ clash = ClashResult(
+ element_id_1=123,
+ element_id_2=456,
+ clash_type="precise",
+ intersection_volume=50000.0,
+ location={"x": 100.0, "y": 200.0, "z": 300.0},
+ severity="medium",
+ )
+
+ data = clash.to_dict()
+
+ assert data["element_id_1"] == 123
+ assert data["element_id_2"] == 456
+ assert data["clash_type"] == "precise"
+ assert data["intersection_volume"] == 50000.0
+ assert data["location"] == {"x": 100.0, "y": 200.0, "z": 300.0}
+ assert data["severity"] == "medium"
+
+
+def test_create_clash_detector():
+ """Test creating a clash detector."""
+ detector = ClashDetector()
+ assert detector.tolerance == 0.0
+ assert len(detector.clashes) == 0
+
+
+def test_detect_clash():
+ """Test detecting a clash between two bounding boxes."""
+ detector = ClashDetector()
+
+ bbox1 = BoundingBox(
+ min_x=0.0, min_y=0.0, min_z=0.0, max_x=1000.0, max_y=1000.0, max_z=3000.0
+ )
+
+ bbox2 = BoundingBox(
+ min_x=500.0, min_y=500.0, min_z=1000.0, max_x=1500.0, max_y=1500.0, max_z=4000.0
+ )
+
+ clash = detector.check_bounding_box_clash("elem_1", bbox1, "elem_2", bbox2)
+
+ assert clash is not None
+ assert clash.element_id_1 == "elem_1"
+ assert clash.element_id_2 == "elem_2"
+ assert clash.clash_type == "bounding_box"
+ assert clash.intersection_volume > 0
+ assert clash.location is not None
+
+
+def test_no_clash_detected():
+ """Test when no clash is detected."""
+ detector = ClashDetector()
+
+ bbox1 = BoundingBox(
+ min_x=0.0, min_y=0.0, min_z=0.0, max_x=1000.0, max_y=1000.0, max_z=3000.0
+ )
+
+ bbox2 = BoundingBox(
+ min_x=2000.0, min_y=2000.0, min_z=0.0, max_x=3000.0, max_y=3000.0, max_z=3000.0
+ )
+
+ clash = detector.check_bounding_box_clash("elem_1", bbox1, "elem_2", bbox2)
+
+ assert clash is None
+ assert len(detector.clashes) == 0
+
+
+def test_check_multiple_elements():
+ """Test checking clashes between multiple elements."""
+ detector = ClashDetector()
+
+ elements = [
+ {
+ "id": "wall_1",
+ "bounding_box": {
+ "min": {"x": 0.0, "y": 0.0, "z": 0.0},
+ "max": {"x": 1000.0, "y": 1000.0, "z": 3000.0},
+ },
+ },
+ {
+ "id": "beam_1",
+ "bounding_box": {
+ "min": {"x": 500.0, "y": 500.0, "z": 1000.0},
+ "max": {"x": 1500.0, "y": 1500.0, "z": 4000.0},
+ },
+ },
+ {
+ "id": "column_1",
+ "bounding_box": {
+ "min": {"x": 5000.0, "y": 5000.0, "z": 0.0},
+ "max": {"x": 5500.0, "y": 5500.0, "z": 3000.0},
+ },
+ },
+ ]
+
+ clashes = detector.check_multiple_elements(elements)
+
+ # Should find 1 clash (wall_1 and beam_1)
+ assert len(clashes) == 1
+ assert clashes[0].element_id_1 == "wall_1"
+ assert clashes[0].element_id_2 == "beam_1"
+
+
+def test_severity_calculation():
+ """Test clash severity calculation."""
+ detector = ClashDetector()
+
+ # Critical: > 1 m³ = 1,000,000,000 mm³
+ bbox1 = BoundingBox(
+ min_x=0.0, min_y=0.0, min_z=0.0, max_x=2000.0, max_y=2000.0, max_z=2000.0
+ )
+ bbox2 = BoundingBox(
+ min_x=1000.0, min_y=1000.0, min_z=1000.0, max_x=3000.0, max_y=3000.0, max_z=3000.0
+ )
+
+ clash = detector.check_bounding_box_clash("e1", bbox1, "e2", bbox2)
+ assert clash.severity == "critical"
+
+
+def test_get_clashes_by_severity():
+ """Test filtering clashes by severity."""
+ detector = ClashDetector()
+
+ # Create clashes with different severities
+ bbox_critical_1 = BoundingBox(
+ min_x=0.0, min_y=0.0, min_z=0.0, max_x=2000.0, max_y=2000.0, max_z=2000.0
+ )
+ bbox_critical_2 = BoundingBox(
+ min_x=1000.0, min_y=1000.0, min_z=1000.0, max_x=3000.0, max_y=3000.0, max_z=3000.0
+ )
+
+ bbox_low_1 = BoundingBox(
+ min_x=0.0, min_y=0.0, min_z=0.0, max_x=100.0, max_y=100.0, max_z=100.0
+ )
+ bbox_low_2 = BoundingBox(
+ min_x=50.0, min_y=50.0, min_z=50.0, max_x=150.0, max_y=150.0, max_z=150.0
+ )
+
+ detector.check_bounding_box_clash("e1", bbox_critical_1, "e2", bbox_critical_2)
+ detector.check_bounding_box_clash("e3", bbox_low_1, "e4", bbox_low_2)
+
+ critical = detector.get_clashes_by_severity("critical")
+ low = detector.get_clashes_by_severity("low")
+
+ assert len(critical) == 1
+ assert len(low) == 1
+
+
+def test_get_critical_clashes():
+ """Test getting only critical clashes."""
+ detector = ClashDetector()
+
+ bbox1 = BoundingBox(
+ min_x=0.0, min_y=0.0, min_z=0.0, max_x=2000.0, max_y=2000.0, max_z=2000.0
+ )
+ bbox2 = BoundingBox(
+ min_x=1000.0, min_y=1000.0, min_z=1000.0, max_x=3000.0, max_y=3000.0, max_z=3000.0
+ )
+
+ detector.check_bounding_box_clash("e1", bbox1, "e2", bbox2)
+
+ critical = detector.get_critical_clashes()
+ assert len(critical) == 1
+ assert critical[0].severity == "critical"
+
+
+def test_get_total_clashes():
+ """Test getting total clash count."""
+ detector = ClashDetector()
+
+ elements = [
+ {
+ "id": f"elem_{i}",
+ "bounding_box": {
+ "min": {"x": float(i * 500), "y": 0.0, "z": 0.0},
+ "max": {"x": float(i * 500 + 1000), "y": 1000.0, "z": 3000.0},
+ },
+ }
+ for i in range(5)
+ ]
+
+ detector.check_multiple_elements(elements)
+ total = detector.get_total_clashes()
+
+ # Elements 0-1, 1-2, 2-3, 3-4 overlap (4 clashes)
+ assert total == 4
+
+
+def test_clear_clashes():
+ """Test clearing stored clashes."""
+ detector = ClashDetector()
+
+ bbox1 = BoundingBox(
+ min_x=0.0, min_y=0.0, min_z=0.0, max_x=1000.0, max_y=1000.0, max_z=3000.0
+ )
+ bbox2 = BoundingBox(
+ min_x=500.0, min_y=500.0, min_z=1000.0, max_x=1500.0, max_y=1500.0, max_z=4000.0
+ )
+
+ detector.check_bounding_box_clash("e1", bbox1, "e2", bbox2)
+ assert len(detector.clashes) == 1
+
+ detector.clear_clashes()
+ assert len(detector.clashes) == 0