summaryrefslogtreecommitdiff
path: root/DungeonSystem/scripts/DungeonGenerator.cs
blob: dd596980d2adce22c9bb5001ad582d62fd37f71f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
using Godot;
using Godot.Collections;

namespace DungeonSystem;

public partial class DungeonGenerator : Node2D
{
    [Export] public PackedScene StartRoomScene { get; set; } = null!;
    [Export] public Array<PackedScene> CombatRoomScenes { get; set; } = new();
    [Export] public PackedScene ShopRoomScene { get; set; } = null!;
    [Export] public PackedScene TreasureRoomScene { get; set; } = null!;
    [Export] public PackedScene BossRoomScene { get; set; } = null!;
    [Export] public PackedScene DoorScene { get; set; } = null!;

    [Export] public int TargetRoomCount { get; set; } = 10;
    [Export] public int MaxAttempts { get; set; } = 100;

    // --- ADD THESE TWO LINES ---
    private readonly Array<Room> _placedRooms = new();
    private readonly Array<Marker2D> _openDoors = new();
    // ---------------------------

    public override void _Ready()
    {
        GenerateDungeon();
    }

    public void GenerateDungeon()
    {
        // 1. Instantiate Start Room
        if (StartRoomScene.Instantiate() is not Room startRoom) return;

        AddChild(startRoom);
        startRoom.GlobalPosition = Vector2.Zero;
        _placedRooms.Add(startRoom);
        _openDoors.AddRange(startRoom.GetOpenDoors());

        // 2. Main Generation Loop
        int attempts = 0;
        while (_openDoors.Count > 0 && _placedRooms.Count < TargetRoomCount && attempts < MaxAttempts)
        {
            attempts++;
            Marker2D targetDoor = _openDoors[(int)(GD.Randi() % (uint)_openDoors.Count)];
            _TryAttachRoom(targetDoor);
        }

        // 3. Post-Process Doors
        SpawnDoorsAndSealUnconnected();
    }

    private bool _TryAttachRoom(Marker2D targetDoor)
    {
        if (CombatRoomScenes.Count == 0) return false;

        PackedScene candidateScene = CombatRoomScenes[(int)(GD.Randi() % (uint)CombatRoomScenes.Count)];
        if (candidateScene.Instantiate() is not Room candidate) return false;

        AddChild(candidate);

        Array<Marker2D> candidateDoors = candidate.GetOpenDoors();
        if (candidateDoors.Count == 0)
        {
            RemoveChild(candidate);
            candidate.QueueFree();
            return false;
        }

        Marker2D entryDoor = candidateDoors[(int)(GD.Randi() % (uint)candidateDoors.Count)];

        // Align candidate entry door directly to target door position
        Vector2 offset = targetDoor.GlobalPosition - entryDoor.GlobalPosition;
        candidate.GlobalPosition += offset;

        if (CheckOverlap(candidate))
        {
            RemoveChild(candidate);
            candidate.QueueFree();
            return false;
        }

        _placedRooms.Add(candidate);

        targetDoor.SetMeta("connected", true);
        entryDoor.SetMeta("connected", true);

        _openDoors.Remove(targetDoor);
        _openDoors.AddRange(candidate.GetOpenDoors());

        return true;
    }
    private bool CheckOverlap(Room candidate)
    {
        Rect2 candidateRect = candidate.GetRoomRect().Grow(-2.0f);

        foreach (Room room in _placedRooms)
        {
            if (candidateRect.Intersects(room.GetRoomRect().Grow(-2.0f)))
            {
                return true;
            }
        }

        return false;
    }

    private void SpawnDoorsAndSealUnconnected()
    {
        foreach (Room room in _placedRooms)
        {
            var doorsContainer = room.DoorsContainer;
            if (doorsContainer == null) continue;

            foreach (Node child in doorsContainer.GetChildren())
            {
                if (child is not Marker2D marker) continue;
                if (!marker.Visible) continue;
                bool isConnected = marker.HasMeta("connected") && marker.GetMeta("connected").AsBool();

                if (isConnected)
                {
                    if (marker.HasMeta("door_spawned")) continue;
                    _InstantiateDoorAtMarker(room, marker);
                }
                else
                {
                    _SealDoorwayWithWall(room, marker);
                }
            }
        }
    }

    private void _InstantiateDoorAtMarker(Room room, Marker2D marker)
    {
        if (DoorScene == null) return;

        Door doorInstance = DoorScene.Instantiate<Door>();
        
        // Add to DungeonGenerator parent directly so it isn't affected by individual room deletion
        AddChild(doorInstance); 
        doorInstance.GlobalPosition = marker.GlobalPosition;
        doorInstance.ZIndex = 1; // Ensure it renders above tilemaps

        if (marker.HasMeta("direction"))
        {
            Vector2 dir = marker.GetMeta("direction").AsVector2();
            if (dir.X != 0)
            {
                doorInstance.RotationDegrees = 90;
            }
        }

        marker.SetMeta("door_spawned", true);
    }

	private void _SealDoorwayWithWall(Room room, Marker2D marker)
    {
        var tileMapLayer = room.GetNodeOrNull<TileMapLayer>("TileMapLayer");
        if (tileMapLayer == null) return;

        // Use Vector2I (Capital I)
        Vector2I cellPos = tileMapLayer.LocalToMap(tileMapLayer.ToLocal(marker.GlobalPosition));

        int sourceId = 0;
        Vector2I wallAtlasCoords = new Vector2I(1, 0); 
        
        tileMapLayer.SetCell(cellPos, sourceId, wallAtlasCoords);
    }
}