# Copyright (C) 2026 Mattia Zatelli # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . """ Visualize intent plugin — 3D visualization, color mapping, section boxes, camera controls. Manages color mapping rules, section box clipping, 3D snapshot generation, camera positioning, and element highlighting for the BIM viewer. """ import logging import math import uuid from typing import Dict, Optional, List, Any from datetime import datetime from sqlalchemy.ext.asyncio import AsyncSession from app.models import Project, Element from app.schemas.intent import SingleQueryPlan, SingleQueryResult, MainIntent from app.core.intent_system.base_plugin import BaseIntentPlugin from app.core.intent_system.decorators import sub_intent logger = logging.getLogger(__name__) class VisualizeIntentPlugin(BaseIntentPlugin): """Plugin for the VISUALIZE intent — 3D visualization and color mapping.""" def __init__(self): super().__init__() self.intent_type = MainIntent.VISUALIZE self.supported_sub_intents = [ "visualize.color_map", "visualize.section_box", "visualize.snapshot", "visualize.camera", "visualize.highlight", ] # Color schemes self.color_schemes = { "by_type": { "name": "By IFC Type", "description": "Color elements by their IFC classification", }, "by_level": { "name": "By Level", "description": "Color elements by building level/storey", }, "by_material": { "name": "By Material", "description": "Color elements by material assignment", }, "by_phase": { "name": "By Phase", "description": "Color by construction phase", }, "by_status": { "name": "By Status", "description": "Color by element status/health", }, "heatmap_area": { "name": "Area Heatmap", "description": "Heatmap based on element area", }, "heatmap_volume": { "name": "Volume Heatmap", "description": "Heatmap based on element volume", }, } # Predefined color palettes self.color_palettes = { "default": { "colors": [ "#3498db", "#e74c3c", "#2ecc71", "#f39c12", "#9b59b6", "#1abc9c", "#34495e", "#e67e22", ], "description": "Balanced color palette for general use", }, "warm": { "colors": [ "#ff6b6b", "#feca57", "#ee5a6f", "#ff7979", "#fa8231", "#ff9ff3", "#ffd93d", ], "description": "Warm color palette", }, "cool": { "colors": [ "#54a0ff", "#48dbfb", "#0abde3", "#00d2d3", "#5f27cd", "#00a8ff", "#0097e6", ], "description": "Cool color palette", }, "earth": { "colors": [ "#8b4513", "#d2691e", "#cd853f", "#daa520", "#b8860b", "#a0522d", "#d2b48c", ], "description": "Earth tones palette", }, "pastel": { "colors": [ "#ffeaa7", "#dfe6e9", "#fab1a0", "#74b9ff", "#a29bfe", "#fd79a8", "#fdcb6e", ], "description": "Soft pastel colors", }, } # Camera presets self.camera_presets = { "isometric": { "name": "Isometric", "angles": {"azimuth": 45, "elevation": 35}, }, "top": { "name": "Top View", "angles": {"azimuth": 0, "elevation": 90}, }, "front": { "name": "Front View", "angles": {"azimuth": 0, "elevation": 0}, }, "right": { "name": "Right View", "angles": {"azimuth": 90, "elevation": 0}, }, "perspective": { "name": "Perspective", "angles": {"azimuth": 30, "elevation": 25}, }, } # Rendering presets self.rendering_presets = { "draft": { "quality": "draft", "shadows": False, "ambient_occlusion": False, "anti_aliasing": 1, "render_time_estimate": "fast", }, "standard": { "quality": "standard", "shadows": True, "ambient_occlusion": False, "anti_aliasing": 2, "render_time_estimate": "medium", }, "high": { "quality": "high", "shadows": True, "ambient_occlusion": True, "anti_aliasing": 4, "render_time_estimate": "slow", }, } # ------------------------------------------------------------------ # Sub-intent handlers # ------------------------------------------------------------------ @sub_intent("visualize.color_map") async def handle_color_map( self, query_plan: SingleQueryPlan, project: Project, session: AsyncSession, context: Optional[Dict] = None, ) -> SingleQueryResult: """Apply color mapping rules to elements.""" start_time = datetime.now() # Get elements query = await self.build_base_query( session=session, project=project, filter_groups=query_plan.filter_groups, scope=query_plan.scope, ) result = await session.execute(query) elements = result.scalars().all() # Determine color scheme (default to by_type) scheme = "by_type" # Could be extracted from filters/context palette_name = "default" # Generate color map color_map = await self._generate_color_map(elements, scheme, palette_name) explanation = ( f"Color map generated for {len(elements)} elements using '{scheme}' scheme. " f"{color_map['unique_categories']} unique categories identified. " f"Palette: {palette_name}." ) return self.create_result( query_plan=query_plan, result_text=f"Color map: {len(elements)} elements, {color_map['unique_categories']} categories", explanation=explanation, result_data=color_map, provenance=["database_query", "color_mapping"], elements_processed=len(elements), processing_time_ms=int( (datetime.now() - start_time).total_seconds() * 1000 ), ) @sub_intent("visualize.section_box") async def handle_section_box( self, query_plan: SingleQueryPlan, project: Project, session: AsyncSession, context: Optional[Dict] = None, ) -> SingleQueryResult: """Define section box for 3D clipping.""" start_time = datetime.now() # Get elements query = await self.build_base_query( session=session, project=project, filter_groups=query_plan.filter_groups, scope=query_plan.scope, ) result = await session.execute(query) elements = result.scalars().all() # Calculate section box bounds section_box = await self._calculate_section_box(elements) volume = ( section_box["dimensions"]["width"] * section_box["dimensions"]["depth"] * section_box["dimensions"]["height"] ) explanation = ( f"Section box calculated for {len(elements)} elements. " f"Dimensions: {section_box['dimensions']['width']:.1f} x " f"{section_box['dimensions']['depth']:.1f} x " f"{section_box['dimensions']['height']:.1f} m. " f"Volume: {volume:.1f} m3." ) return self.create_result( query_plan=query_plan, result_text=( f"Section box: " f"{section_box['dimensions']['width']:.1f}x" f"{section_box['dimensions']['depth']:.1f}x" f"{section_box['dimensions']['height']:.1f}m" ), explanation=explanation, result_data=section_box, provenance=["database_query", "geometry_calculation"], elements_processed=len(elements), processing_time_ms=int( (datetime.now() - start_time).total_seconds() * 1000 ), ) @sub_intent("visualize.snapshot") async def handle_snapshot( self, query_plan: SingleQueryPlan, project: Project, session: AsyncSession, context: Optional[Dict] = None, ) -> SingleQueryResult: """Generate 3D snapshot configuration.""" start_time = datetime.now() # Get elements query = await self.build_base_query( session=session, project=project, filter_groups=query_plan.filter_groups, scope=query_plan.scope, ) result = await session.execute(query) elements = result.scalars().all() # Generate snapshot configuration snapshot = await self._generate_snapshot_config(elements, project) explanation = ( f"Snapshot configuration generated for {len(elements)} elements. " f"Resolution: {snapshot['resolution']['width']}x{snapshot['resolution']['height']}. " f"Camera preset: {snapshot['camera_preset']}. " f"Rendering quality: {snapshot['rendering']['quality']}." ) return self.create_result( query_plan=query_plan, result_text=( f"Snapshot: {snapshot['resolution']['width']}x" f"{snapshot['resolution']['height']} " f"({snapshot['rendering']['quality']})" ), explanation=explanation, result_data=snapshot, provenance=["database_query", "snapshot_generation"], elements_processed=len(elements), processing_time_ms=int( (datetime.now() - start_time).total_seconds() * 1000 ), ) @sub_intent("visualize.camera") async def handle_camera( self, query_plan: SingleQueryPlan, project: Project, session: AsyncSession, context: Optional[Dict] = None, ) -> SingleQueryResult: """Calculate optimal camera positioning.""" start_time = datetime.now() # Get elements query = await self.build_base_query( session=session, project=project, filter_groups=query_plan.filter_groups, scope=query_plan.scope, ) result = await session.execute(query) elements = result.scalars().all() # Calculate camera position camera = await self._calculate_camera_position(elements, preset="isometric") distance = self._calculate_distance(camera["position"], camera["target"]) explanation = ( f"Camera positioned for optimal view of {len(elements)} elements. " f"Preset: {camera['preset']}. " f"Distance from target: {distance:.1f}m. " f"Field of view: {camera['fov']}." ) return self.create_result( query_plan=query_plan, result_text=f"Camera: {camera['preset']} view, {distance:.1f}m from target", explanation=explanation, result_data=camera, provenance=["database_query", "camera_calculation"], elements_processed=len(elements), processing_time_ms=int( (datetime.now() - start_time).total_seconds() * 1000 ), ) @sub_intent("visualize.highlight") async def handle_highlight( self, query_plan: SingleQueryPlan, project: Project, session: AsyncSession, context: Optional[Dict] = None, ) -> SingleQueryResult: """Generate highlight configuration for specific elements.""" start_time = datetime.now() # Get elements to highlight query = await self.build_base_query( session=session, project=project, filter_groups=query_plan.filter_groups, scope=query_plan.scope, ) result = await session.execute(query) elements = result.scalars().all() # Generate highlight configuration highlight = await self._generate_highlight_config(elements) explanation = ( f"Highlighting {len(elements)} elements. " f"Highlight color: {highlight['highlight_color']}. " f"Opacity: {highlight['opacity'] * 100}%. " f"Outline: {'enabled' if highlight['outline'] else 'disabled'}." ) return self.create_result( query_plan=query_plan, result_text=f"Highlighting {len(elements)} elements with {highlight['effect_type']} effect", explanation=explanation, result_data=highlight, provenance=["database_query", "highlight_generation"], elements_processed=len(elements), processing_time_ms=int( (datetime.now() - start_time).total_seconds() * 1000 ), ) # ------------------------------------------------------------------ # Helper methods # ------------------------------------------------------------------ async def _generate_color_map( self, elements: List[Element], scheme: str, palette_name: str, ) -> Dict[str, Any]: """Generate color mapping for elements.""" palette = self.color_palettes.get(palette_name, self.color_palettes["default"]) colors = palette["colors"] category_colors: Dict[str, str] = {} element_colors: List[Dict[str, Any]] = [] category_counts: Dict[str, int] = {} if scheme == "by_type": # Group by IFC type unique_types = sorted(set(e.ifc_type for e in elements if e.ifc_type)) for i, ifc_type in enumerate(unique_types): category_colors[ifc_type] = colors[i % len(colors)] category_counts[ifc_type] = sum( 1 for e in elements if e.ifc_type == ifc_type ) for element in elements[:100]: # Sample first 100 for visualization element_colors.append( { "element_id": element.ifc_global_id, "element_name": element.name, "category": element.ifc_type, "color": category_colors.get(element.ifc_type, "#cccccc"), } ) elif scheme == "by_level": # Group by level unique_levels = sorted( set(e.level_name for e in elements if e.level_name) ) for i, level in enumerate(unique_levels): category_colors[level] = colors[i % len(colors)] category_counts[level] = sum( 1 for e in elements if e.level_name == level ) for element in elements[:100]: element_colors.append( { "element_id": element.ifc_global_id, "element_name": element.name, "category": element.level_name or "Unassigned", "color": category_colors.get(element.level_name, "#cccccc"), } ) elif scheme == "by_material": # Group by material unique_materials = sorted( set(e.material_name for e in elements if e.material_name) ) for i, material in enumerate(unique_materials): category_colors[material] = colors[i % len(colors)] category_counts[material] = sum( 1 for e in elements if e.material_name == material ) for element in elements[:100]: element_colors.append( { "element_id": element.ifc_global_id, "element_name": element.name, "category": element.material_name or "No Material", "color": category_colors.get( element.material_name, "#cccccc" ), } ) elif scheme == "heatmap_area": # Heatmap by area areas = [float(e.area) for e in elements if e.area] if areas: min_area, max_area = min(areas), max(areas) for element in elements[:100]: if element.area: normalized = ( (float(element.area) - min_area) / (max_area - min_area) if max_area > min_area else 0 ) color = self._get_heatmap_color(normalized) else: color = "#cccccc" element_colors.append( { "element_id": element.ifc_global_id, "element_name": element.name, "value": float(element.area) if element.area else None, "color": color, } ) return { "project_id": elements[0].project_id if elements else None, "scheme": scheme, "scheme_name": self.color_schemes[scheme]["name"], "palette": palette_name, "palette_description": palette["description"], "unique_categories": len(category_colors), "category_colors": category_colors, "category_counts": category_counts, "element_colors": element_colors, "total_elements": len(elements), "sampled_elements": len(element_colors), "legend": [ { "category": cat, "color": col, "count": category_counts.get(cat, 0), } for cat, col in category_colors.items() ], } def _get_heatmap_color(self, value: float) -> str: """Get color for heatmap value (0-1). Blue (cold) to Red (hot) gradient.""" if value < 0.25: return f"#00{int(value * 4 * 255):02x}ff" # Blue to cyan elif value < 0.5: return f"#00ff{int((0.5 - value) * 4 * 255):02x}" # Cyan to green elif value < 0.75: return f"#{int((value - 0.5) * 4 * 255):02x}ff00" # Green to yellow else: return f"#ff{int((1 - value) * 4 * 255):02x}00" # Yellow to red async def _calculate_section_box( self, elements: List[Element] ) -> Dict[str, Any]: """Calculate bounding box for section.""" # Mock calculation (in real implementation, would calculate from actual geometry) min_coords = {"x": 0, "y": 0, "z": 0} max_coords = {"x": 100, "y": 50, "z": 30} center = { "x": (min_coords["x"] + max_coords["x"]) / 2, "y": (min_coords["y"] + max_coords["y"]) / 2, "z": (min_coords["z"] + max_coords["z"]) / 2, } dimensions = { "width": max_coords["x"] - min_coords["x"], "depth": max_coords["y"] - min_coords["y"], "height": max_coords["z"] - min_coords["z"], } return { "min": min_coords, "max": max_coords, "center": center, "dimensions": dimensions, "clip_planes": [ {"normal": {"x": 1, "y": 0, "z": 0}, "distance": min_coords["x"], "enabled": True}, {"normal": {"x": -1, "y": 0, "z": 0}, "distance": -max_coords["x"], "enabled": True}, {"normal": {"x": 0, "y": 1, "z": 0}, "distance": min_coords["y"], "enabled": True}, {"normal": {"x": 0, "y": -1, "z": 0}, "distance": -max_coords["y"], "enabled": True}, {"normal": {"x": 0, "y": 0, "z": 1}, "distance": min_coords["z"], "enabled": True}, {"normal": {"x": 0, "y": 0, "z": -1}, "distance": -max_coords["z"], "enabled": True}, ], "element_count": len(elements), } async def _generate_snapshot_config( self, elements: List[Element], project: Project ) -> Dict[str, Any]: """Generate snapshot configuration.""" camera_preset = "isometric" rendering_preset = "standard" camera = await self._calculate_camera_position(elements, camera_preset) rendering = self.rendering_presets[rendering_preset] return { "project_id": project.id, "project_name": project.name, "camera_preset": camera_preset, "camera": camera, "resolution": { "width": 1920, "height": 1080, "aspect_ratio": 16 / 9, }, "format": "png", "quality": 95, "rendering": rendering, "rendering_preset": rendering_preset, "element_count": len(elements), "background": { "type": "gradient", "top_color": "#e0f2f7", "bottom_color": "#ffffff", }, "lighting": { "ambient": {"intensity": 0.3, "color": "#ffffff"}, "directional": [ { "direction": {"x": 1, "y": 1, "z": -1}, "intensity": 0.7, "color": "#ffffff", }, ], }, "timestamp": datetime.now().isoformat(), } async def _calculate_camera_position( self, elements: List[Element], preset: str = "isometric" ) -> Dict[str, Any]: """Calculate optimal camera position.""" # Calculate center of model (from section box) section_box = await self._calculate_section_box(elements) center = section_box["center"] # Get preset angles preset_config = self.camera_presets.get( preset, self.camera_presets["isometric"] ) azimuth = preset_config["angles"]["azimuth"] elevation = preset_config["angles"]["elevation"] # Calculate camera distance based on model size max_dimension = max( section_box["dimensions"]["width"], section_box["dimensions"]["depth"], section_box["dimensions"]["height"], ) distance = max_dimension * 1.5 # 1.5x the largest dimension # Calculate camera position from angles azimuth_rad = math.radians(azimuth) elevation_rad = math.radians(elevation) position = { "x": center["x"] + distance * math.cos(elevation_rad) * math.cos(azimuth_rad), "y": center["y"] + distance * math.cos(elevation_rad) * math.sin(azimuth_rad), "z": center["z"] + distance * math.sin(elevation_rad), } return { "preset": preset, "preset_name": preset_config["name"], "position": position, "target": center, "up": {"x": 0, "y": 0, "z": 1}, # Z-up convention "fov": 60, # Field of view in degrees "near": 0.1, # Near clipping plane "far": distance * 5, # Far clipping plane "distance": distance, "azimuth": azimuth, "elevation": elevation, } def _calculate_distance( self, pos1: Dict[str, float], pos2: Dict[str, float] ) -> float: """Calculate Euclidean distance between two points.""" return math.sqrt( (pos1["x"] - pos2["x"]) ** 2 + (pos1["y"] - pos2["y"]) ** 2 + (pos1["z"] - pos2["z"]) ** 2 ) async def _generate_highlight_config( self, elements: List[Element] ) -> Dict[str, Any]: """Generate highlight configuration for elements.""" highlighted_elements = [] for element in elements[:50]: # Sample first 50 for performance highlighted_elements.append( { "element_id": element.ifc_global_id, "element_name": element.name, "element_type": element.ifc_type, "level": element.level_name, } ) return { "highlight_id": str(uuid.uuid4()), "highlighted_elements": highlighted_elements, "total_highlighted": len(elements), "sampled_count": len(highlighted_elements), "highlight_color": "#ff6b6b", "opacity": 1.0, "effect_type": "glow", "outline": True, "outline_width": 2, "outline_color": "#ffffff", "animation": { "enabled": True, "type": "pulse", "duration": 1.5, "loop": True, }, "isolation": { "isolate_highlighted": False, "dim_others": True, "dim_opacity": 0.3, }, "timestamp": datetime.now().isoformat(), }