```python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Hammer Editor Source Map GENERATOR 2D
Generates a map with rooms and corridors, visualizes it, and exports it in VMF format for the Hammer Editor.
"""

import argparse
import math
import random
from dataclasses import dataclass
from typing import List, Tuple, Optional, Set

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import networkx as nx


@dataclass
class Config:
    num_rooms: int = 20
    map_width: int = 200
    map_height: int = 200
    room_min_size: int = 5
    room_max_size: int = 20
    passageway_width: int = 3
    extra_connections_factor: float = 0.4
    max_attempts_multiplier: int = 10
    # Seed for reproducible results
    random_seed: Optional[int] = None


@dataclass
class Room:
    x: int
    y: int
    width: int
    height: int

    def center(self) -> Tuple[float, float]:
        """Calculate the center coordinates of the room."""
        center_x = self.x + self.width / 2
        center_y = self.y + self.height / 2
        return center_x, center_y

    def intersects(self, other: 'Room') -> bool:
        """Check if this room intersects with another room."""
        return not (
            self.x + self.width <= other.x or
            self.x >= other.x + other.width or
            self.y + self.height <= other.y or
            self.y >= other.y + other.height
        )


class SpatialGrid:
    """Spatial grid for efficient room collision detection."""

    def __init__(self, map_width: int, map_height: int, cell_size: int):
        self.cell_size = cell_size
        self.cols = math.ceil(map_width / cell_size)
        self.rows = math.ceil(map_height / cell_size)
        self.grid = [[[] for _ in range(self.rows)] for _ in range(self.cols)]

    def _get_cells_for_room(self, room: Room) -> Set[Tuple[int, int]]:
        """Determine which grid cells the room occupies."""
        start_col = room.x // self.cell_size
        end_col = (room.x + room.width) // self.cell_size
        start_row = room.y // self.cell_size
        end_row = (room.y + room.height) // self.cell_size
        cells = set()
        for col in range(start_col, end_col + 1):
            for row in range(start_row, end_row + 1):
                if 0 <= col < self.cols and 0 <= row < self.rows:
                    cells.add((col, row))
        return cells

    def add_room(self, room: Room):
        """Add a room to the grid."""
        cells = self._get_cells_for_room(room)
        for col, row in cells:
            self.grid[col][row].append(room)

    def has_intersection(self, room: Room) -> bool:
        """Check if the room intersects with any existing rooms in relevant grid cells."""
        cells = self._get_cells_for_room(room)
        for col, row in cells:
            for existing_room in self.grid[col][row]:
                if room.intersects(existing_room):
                    return True
        return False


class MapGenerator:
    def __init__(self, config: Config):
        self.config = config
        if config.random_seed is not None:
            random.seed(config.random_seed)
        # Initialize spatial grid with cell size equal to the max room size
        self.spatial_grid = SpatialGrid(
            config.map_width,
            config.map_height,
            config.room_max_size
        )

    def generate_rooms(self) -> List[Room]:
        """Generate non-overlapping rooms within the map boundaries."""
        rooms = []
        max_attempts = self.config.num_rooms * self.config.max_attempts_multiplier
        attempts = 0

        while len(rooms) < self.config.num_rooms and attempts < max_attempts:
            width = random.randint(
                self.config.room_min_size, self.config.room_max_size)
            height = random.randint(
                self.config.room_min_size, self.config.room_max_size)
            x = random.randint(0, self.config.map_width - width)
            y = random.randint(0, self.config.map_height - height)
            new_room = Room(x, y, width, height)

            if not self.spatial_grid.has_intersection(new_room):
                rooms.append(new_room)
                self.spatial_grid.add_room(new_room)
                print(f"Placed room {len(rooms)} at ({x}, {y}) size ({width}x{height})")
            attempts += 1

        if len(rooms) < self.config.num_rooms:
            print(
                f"Warning: Only {len(rooms)} out of {self.config.num_rooms} rooms were placed "
                f"after {attempts} attempts."
            )
        return rooms

    def connect_rooms(self, rooms: List[Room]) -> nx.Graph:
        """Connect rooms using Minimum Spanning Tree and add extra connections."""
        G = nx.Graph()

        # Add nodes with positions
        for idx, room in enumerate(rooms):
            G.add_node(idx, pos=room.center())

        # Add all possible edges with Euclidean distance as weight
        for i in range(len(rooms)):
            for j in range(i + 1, len(rooms)):
                pos_i = rooms[i].center()
                pos_j = rooms[j].center()
                distance = math.hypot(pos_i[0] - pos_j[0], pos_i[1] - pos_j[1])
                G.add_edge(i, j, weight=distance)

        # Compute Minimum Spanning Tree (MST)
        mst = nx.minimum_spanning_tree(G)

        # Determine number of additional connections
        extra_connections = int(
            self.config.extra_connections_factor * len(rooms))
        potential_extra = set(G.edges()) - set(mst.edges())

        if potential_extra:
            # Sort potential extras by weight (can also shuffle for randomness)
            sorted_extra = sorted(
                potential_extra,
                key=lambda edge: G.edges[edge]['weight']
            )
            num_extra = min(extra_connections, len(sorted_extra))
            extra_edges = sorted_extra[:num_extra]
            mst.add_edges_from(extra_edges)
            print(f"Added {len(extra_edges)} extra connections.")
        else:
            print("No extra connections available.")

        return mst


class MapVisualizer:
    def __init__(self, config: Config):
        self.config = config

    def draw_map_2d(self, rooms: List[Room], connections: nx.Graph) -> None:
        """Render the map in 2D using matplotlib."""
        fig, ax = plt.subplots(figsize=(15, 15))

        # Draw rooms
        for idx, room in enumerate(rooms):
            rect = patches.Rectangle(
                (room.x, room.y),
                room.width,
                room.height,
                linewidth=1,
                edgecolor='black',
                facecolor='cyan',
                alpha=0.8
            )
            ax.add_patch(rect)

            cx, cy = room.center()
            ax.plot(cx, cy, 'ro')  # Red dot at center
            ax.text(
                cx, cy, str(idx + 1),
                color='white', ha='center', va='center',
                fontsize=8, fontweight='bold'
            )

        # Draw corridors as orthogonal corridors
        for edge in connections.edges():
            self._draw_corridor_2d(ax, rooms[edge[0]], rooms[edge[1]])

        # Configure plot
        ax.set_xlim(-10, self.config.map_width + 10)
        ax.set_ylim(-10, self.config.map_height + 10)
        ax.set_aspect('equal')
        ax.set_title(
            'Hammer Editor - Randomly Generated Rooms',
            fontsize=16
        )
        ax.set_xlabel('X', fontsize=12)
        ax.set_ylabel('Y', fontsize=12)
        ax.grid(True, which='both', linestyle='--', linewidth=0.5, alpha=0.7)
        plt.show()

    def _draw_corridor_2d(self, ax, room_a: Room, room_b: Room) -> None:
        """Draw an orthogonal corridor between two rooms in 2D."""
        ax_center = room_a.center()
        bx_center = room_b.center()

        # Randomly decide whether to go horizontal first or vertical
        horizontal_first = random.choice([True, False])

        if horizontal_first:
            intermediate_point = (bx_center[0], ax_center[1])
            self._draw_rectangle_corridor(
                ax,
                start=ax_center,
                end=intermediate_point,
                orientation='horizontal'
            )
            self._draw_rectangle_corridor(
                ax,
                start=intermediate_point,
                end=bx_center,
                orientation='vertical'
            )
        else:
            intermediate_point = (ax_center[0], bx_center[1])
            self._draw_rectangle_corridor(
                ax,
                start=ax_center,
                end=intermediate_point,
                orientation='vertical'
            )
            self._draw_rectangle_corridor(
                ax,
                start=intermediate_point,
                end=bx_center,
                orientation='horizontal'
            )

    def _draw_rectangle_corridor(self, ax, start: Tuple[float, float], end: Tuple[float, float], orientation: str) -> None:
        """Helper method to draw a rectangular corridor."""
        if orientation == 'horizontal':
            corridor_length = abs(end[0] - start[0])
            corridor_x = min(start[0], end[0])
            corridor_y = start[1] - self.config.passageway_width / 2
            rectangle = patches.Rectangle(
                (corridor_x, corridor_y),
                corridor_length,
                self.config.passageway_width,
                linewidth=0,
                edgecolor=None,
                facecolor='blue',
                alpha=0.6
            )
        else:
            corridor_length = abs(end[1] - start[1])
            corridor_x = start[0] - self.config.passageway_width / 2
            corridor_y = min(start[1], end[1])
            rectangle = patches.Rectangle(
                (corridor_x, corridor_y),
                self.config.passageway_width,
                corridor_length,
                linewidth=0,
                edgecolor=None,
                facecolor='blue',
                alpha=0.6
            )
        ax.add_patch(rectangle)


class VMFGenerator:
    """Class to generate VMF file from rooms and corridors."""

    def __init__(self, config: Config, rooms: List[Room], connections: nx.Graph):
        self.config = config
        self.rooms = rooms
        self.connections = connections
        self.vmf = []
        self.brush_id = 1
        self.side_id = 1  # Each side of a brush needs a unique ID

    def generate_vmf(self) -> str:
        """Generate the content of the VMF file."""
        self._add_versioninfo()
        self._add_visgroups()
        self._add_viewsettings()
        self._add_palette_plus()
        self._add_colorcorrection_plus()
        self._add_light_plus()
        self._add_postprocess_plus()
        self._add_bgimages_plus()
        self._add_world()
        self._add_entities()
        return '\n'.join(self.vmf)

    def _add_versioninfo(self):
        """Add the versioninfo block."""
        self.vmf.append('versioninfo')
        self.vmf.append('{')
        self.vmf.append('    "editorversion" "400"')
        self.vmf.append('    "editorbuild" "8868"')
        self.vmf.append('    "mapversion" "0"')
        self.vmf.append('    "formatversion" "100"')
        self.vmf.append('    "prefab" "0"')
        self.vmf.append('}')

    def _add_visgroups(self):
        """Add the visgroups block."""
        self.vmf.append('visgroups')
        self.vmf.append('{')
        self.vmf.append('}')

    def _add_viewsettings(self):
        """Add the viewsettings block."""
        self.vmf.append('viewsettings')
        self.vmf.append('{')
        self.vmf.append('    "bSnapToGrid" "1"')
        self.vmf.append('    "bShowGrid" "1"')
        self.vmf.append('    "bShowLogicalGrid" "0"')
        self.vmf.append('    "nGridSpacing" "64"')
        self.vmf.append('}')

    def _add_palette_plus(self):
        """Add the palette_plus block with default colors."""
        self.vmf.append('palette_plus')
        self.vmf.append('{')
        for i in range(16):
            self.vmf.append(f'    "color{i}" "255 255 255"')
        self.vmf.append('}')

    def _add_colorcorrection_plus(self):
        """Add the colorcorrection_plus block."""
        self.vmf.append('colorcorrection_plus')
        self.vmf.append('{')
        for i in range(4):
            self.vmf.append(f'    "name{i}" ""')
            self.vmf.append(f'    "weight{i}" "1"')
        self.vmf.append('}')

    def _add_light_plus(self):
        """Add the light_plus block."""
        self.vmf.append('light_plus')
        self.vmf.append('{')
        self.vmf.append('    "samples_sun" "6"')
        self.vmf.append('    "samples_ambient" "40"')
        self.vmf.append('    "samples_vis" "256"')
        self.vmf.append('    "texlight" ""')
        self.vmf.append('    "incremental_delay" "0"')
        self.vmf.append('    "bake_dist" "1024"')
        self.vmf.append('    "radius_scale" "1"')
        self.vmf.append('    "brightness_scale" "1"')
        self.vmf.append('    "ao_scale" "0"')
        self.vmf.append('    "bounced" "1"')
        self.vmf.append('    "incremental" "1"')
        self.vmf.append('    "supersample" "0"')
        self.vmf.append('    "bleed_hack" "1"')
        self.vmf.append('    "soften_cosine" "0"')
        self.vmf.append('    "debug" "0"')
        self.vmf.append('    "cubemap" "1"')
        self.vmf.append('}')

    def _add_postprocess_plus(self):
        """Add the postprocess_plus block."""
        self.vmf.append('postprocess_plus')
        self.vmf.append('{')
        self.vmf.append('    "enable" "1"')
        self.vmf.append('    "copied_from_controller" "0"')
        self.vmf.append('    "bloom_scale" "1"')
        self.vmf.append('    "bloom_exponent" "2.5"')
        self.vmf.append('    "bloom_saturation" "1"')
        self.vmf.append('    "auto_exposure_min" "0.5"')
        self.vmf.append('    "auto_exposure_max" "2"')
        self.vmf.append('    "tonemap_percent_target" "60"')
        self.vmf.append('    "tonemap_percent_bright_pixels" "2"')
        self.vmf.append('    "tonemap_min_avg_luminance" "3"')
        self.vmf.append('    "tonemap_rate" "1"')
        self.vmf.append('    "vignette_enable" "0"')
        self.vmf.append('    "vignette_start" "1"')
        self.vmf.append('    "vignette_end" "2"')
        self.vmf.append('    "vignette_blur" "0"')
        self.vmf.append('}')

    def _add_bgimages_plus(self):
        """Add the bgimages_plus block."""
        self.vmf.append('bgimages_plus')
        self.vmf.append('{')
        self.vmf.append('}')

    def _add_world(self):
        """Add the world block with brushes."""
        self.vmf.append('world')
        self.vmf.append('{')
        self.vmf.append('    "id" "1"')
        self.vmf.append('    "classname" "worldspawn"')
        self.vmf.append('    "detailmaterial" "detail/detailsprites"')
        self.vmf.append('    "detailvbsp" "detail.vbsp"')
        self.vmf.append('    "maxpropscreenwidth" "-1"')
        self.vmf.append('    "skyname" "sky_day01_01"')

        # Add outer boundary
        self._add_outer_boundary()

        # Generate rooms
        for idx, room in enumerate(self.rooms):
            print(f"Creating room brush ID {self.brush_id} from ({room.x}, {room.y}, 0) to ({room.x + room.width}, {room.y + room.height}, 64)")
            self.vmf.append('    solid')
            self.vmf.append('    {')
            self.vmf.append(f'        "id" "{self.brush_id}"')
            min_x = room.x
            min_y = room.y
            min_z = 0
            max_x = room.x + room.width
            max_y = room.y + room.height
            max_z = 64  # Height of the room

            # Define the six sides of the room
            # Floor (normal up)
            self.vmf.extend(self._create_side(
                a=(min_x, min_y, min_z),
                b=(max_x, min_y, min_z),
                c=(max_x, max_y, min_z),
                material='"tools/toolsfloor"',
                scale_u='[1 0 0 0] [0 1 0 0]',
                scale_v='[0 1 0 0] [0 0 1 0]',
                reverse=False
            ))

            # Ceiling (normal down)
            self.vmf.extend(self._create_side(
                a=(min_x, min_y, max_z),
                b=(max_x, min_y, max_z),
                c=(max_x, max_y, max_z),
                material='"tools/toolsroof"',
                scale_u='[1 0 0 0] [0 1 0 0]',
                scale_v='[0 1 0 0] [0 0 1 0]',
                reverse=True
            ))

            # Front Wall (normal outward)
            self.vmf.extend(self._create_side(
                a=(min_x, min_y, min_z),
                b=(max_x, min_y, min_z),
                c=(max_x, min_y, max_z),
                material='"tools/toolsside"',
                scale_u='[1 0 0 0] [0 1 0 0]',
                scale_v='[0 1 0 0] [0 0 1 0]',
                reverse=False
            ))

            # Back Wall (normal outward)
            self.vmf.extend(self._create_side(
                a=(min_x, max_y, min_z),
                b=(max_x, max_y, min_z),
                c=(max_x, max_y, max_z),
                material='"tools/toolsside"',
                scale_u='[1 0 0 0] [0 1 0 0]',
                scale_v='[0 1 0 0] [0 0 1 0]',
                reverse=True
            ))

            # Left Wall (normal outward)
            self.vmf.extend(self._create_side(
                a=(min_x, min_y, min_z),
                b=(min_x, max_y, min_z),
                c=(min_x, max_y, max_z),
                material='"tools/toolsside"',
                scale_u='[1 0 0 0] [0 1 0 0]',
                scale_v='[0 1 0 0] [0 0 1 0]',
                reverse=False
            ))

            # Right Wall (normal outward)
            self.vmf.extend(self._create_side(
                a=(max_x, min_y, min_z),
                b=(max_x, max_y, min_z),
                c=(max_x, max_y, max_z),
                material='"tools/toolsside"',
                scale_u='[1 0 0 0] [0 1 0 0]',
                scale_v='[0 1 0 0] [0 0 1 0]',
                reverse=True
            ))

            # Debugging: Ensure exactly six sides are added
            if len([line for line in self.vmf if 'side' in line]) < (self.brush_id * 6):
                print(f"Warning: Solid ID {self.brush_id} has fewer than 6 sides.")

            self.vmf.append('    }')  # Close solid
            self.brush_id += 1

        self.vmf.append('}')  # Close world

    def _add_outer_boundary(self):
        """Add the outer boundary of the map."""
        boundary_margin = 0  # No margin, boundary exactly at map borders
        min_x = 0
        min_y = 0
        max_x = self.config.map_width
        max_y = self.config.map_height
        min_z = 0
        max_z = 64  # Height of the boundary

        print(f"Creating outer boundary brush ID {self.brush_id} from ({min_x}, {min_y}, {min_z}) to ({max_x}, {max_y}, {max_z})")

        self.vmf.append('    solid')
        self.vmf.append('    {')
        self.vmf.append(f'        "id" "{self.brush_id}"')

        # Floor
        self.vmf.extend(self._create_side(
            a=(min_x, min_y, min_z),
            b=(max_x, min_y, min_z),
            c=(max_x, max_y, min_z),
            material='"tools/toolsfloor"',
            scale_u='[1 0 0 0] [0 1 0 0]',
            scale_v='[0 1 0 0] [0 0 1 0]',
            reverse=False
        ))

        # Ceiling
        self.vmf.extend(self._create_side(
            a=(min_x, min_y, max_z),
            b=(max_x, min_y, max_z),
            c=(max_x, max_y, max_z),
            material='"tools/toolsroof"',
            scale_u='[1 0 0 0] [0 1 0 0]',
            scale_v='[0 1 0 0] [0 0 1 0]',
            reverse=True
        ))

        # Front Wall (normal outward)
        self.vmf.extend(self._create_side(
            a=(min_x, min_y, min_z),
            b=(max_x, min_y, min_z),
            c=(max_x, min_y, max_z),
            material='"tools/toolsside"',
            scale_u='[1 0 0 0] [0 1 0 0]',
            scale_v='[0 1 0 0] [0 0 1 0]',
            reverse=False
        ))

        # Back Wall (normal outward)
        self.vmf.extend(self._create_side(
            a=(min_x, max_y, min_z),
            b=(max_x, max_y, min_z),
            c=(max_x, max_y, max_z),
            material='"tools/toolsside"',
            scale_u='[1 0 0 0] [0 1 0 0]',
            scale_v='[0 1 0 0] [0 0 1 0]',
            reverse=True
        ))

        # Left Wall (normal outward)
        self.vmf.extend(self._create_side(
            a=(min_x, min_y, min_z),
            b=(min_x, max_y, min_z),
            c=(min_x, max_y, max_z),
            material='"tools/toolsside"',
            scale_u='[1 0 0 0] [0 1 0 0]',
            scale_v='[0 1 0 0] [0 0 1 0]',
            reverse=False
        ))

        # Right Wall (normal outward)
        self.vmf.extend(self._create_side(
            a=(max_x, min_y, min_z),
            b=(max_x, max_y, min_z),
            c=(max_x, max_y, max_z),
            material='"tools/toolsside"',
            scale_u='[1 0 0 0] [0 1 0 0]',
            scale_v='[0 1 0 0] [0 0 1 0]',
            reverse=True
        ))

        # Debugging: Ensure exactly six sides are added
        if len([line for line in self.vmf if 'side' in line]) < (self.brush_id * 6):
            print(f"Warning: Solid ID {self.brush_id} has fewer than 6 sides.")

        self.vmf.append('    }')  # Close solid
        self.brush_id += 1

    def _create_side(self, a: Tuple[float, float, float], b: Tuple[float, float, float],
                    c: Tuple[float, float, float], material: str,
                    scale_u: str, scale_v: str, reverse: bool = False) -> List[str]:
        """Create a side (face) string for a brush."""
        side = []
        side.append('        side')
        side.append('        {')
        side.append(f'            "id" "{self.side_id}"')
        # Format coordinates with one decimal place
        if reverse:
            side.append(f'            "plane" "({c[0]:.1f} {c[1]:.1f} {c[2]:.1f}) ({b[0]:.1f} {b[1]:.1f} {b[2]:.1f}) ({a[0]:.1f} {a[1]:.1f} {a[2]:.1f})"')
        else:
            side.append(f'            "plane" "({a[0]:.1f} {a[1]:.1f} {a[2]:.1f}) ({b[0]:.1f} {b[1]:.1f} {b[2]:.1f}) ({c[0]:.1f} {c[1]:.1f} {c[2]:.1f})"')
        side.append(f'            "material" {material}')
        side.append(f'            "uaxis" "{scale_u} 0.0"')
        side.append(f'            "vaxis" "{scale_v} 0.0"')
        side.append('            "rotation" "0"')
        side.append('            "lightmapscale" "16"')
        side.append('            "smoothing_groups" "0"')
        side.append('        }')
        self.side_id += 1
        return side

    def _add_entities(self):
        """Add entities to the VMF file (if any)."""
        self.vmf.append('    entities')
        self.vmf.append('    {')
        # Here you can add entities as needed. For now, it's left empty.
        self.vmf.append('    }')  # Close entities

    def save_vmf(self, filename: str):
        """Save the VMF file."""
        vmf_content = self.generate_vmf()
        with open(filename, 'w', encoding='utf-8') as file:
            file.write(vmf_content)
        print(f"VMF file successfully saved as '{filename}'.")


def parse_arguments() -> argparse.Namespace:
    """Parse command-line arguments."""
    parser = argparse.ArgumentParser(
        description="Hammer Editor Source Map GENERATOR 2D - Generate and visualize maps with rooms and corridors."
    )
    parser.add_argument(
        '--view', type=str, default='2d',
        choices=['2d'],
        help="Type of visualization: '2d'. Default is '2d'."
    )
    parser.add_argument(
        '--seed', type=int, default=None,
        help="Random seed for reproducibility."
    )
    # Placeholder for future configuration file support
    parser.add_argument(
        '--config', type=str, default=None,
        help="Path to a configuration file (optional)."
    )
    return parser.parse_args()


def main():
    args = parse_arguments()

    # Initialize configuration
    config = Config(
        num_rooms=20,
        map_width=200,
        map_height=200,
        room_min_size=5,
        room_max_size=20,
        passageway_width=3,
        extra_connections_factor=0.4,
        max_attempts_multiplier=10,
        random_seed=args.seed
    )

    # Generate map
    generator = MapGenerator(config)
    rooms = generator.generate_rooms()
    connections = generator.connect_rooms(rooms)

    # Visualize map
    visualizer = MapVisualizer(config)
    if args.view == '2d':
        visualizer.draw_map_2d(rooms, connections)

    # Generate and save VMF
    vmf_generator = VMFGenerator(config, rooms, connections)
    vmf_filename = "generated_map.vmf"
    vmf_generator.save_vmf(vmf_filename)


if __name__ == "__main__":
    main()
```
Убери из кода все что связано с генерацией VMF