aboutsummaryrefslogtreecommitdiff
path: root/src/tool/polygon_room_tool.rs
blob: 58f326fcd1049f3f15a5e31dca0449199553e10d (plain) (blame)
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
use super::Tool;
use crate::button::Button;
use crate::config::{PolygonRoomToolKeybindings, ToolKeybindings};
use crate::dimension_indicator::DimensionIndicator;
use crate::grid::{snap_to_grid, SNAP_SIZE};
use crate::map_data::MapData;
use crate::math::{self, Polygon, PolygonError, Vec2};
use crate::transform::Transform;
use raylib::core::drawing::{RaylibDraw, RaylibDrawHandle};
use raylib::ffi::Color;
use raylib::RaylibHandle;

struct UnfinishedPolygon {
    pub corners: Vec<Vec2<f32>>,
    pub working_corner: Vec2<f32>,
}

pub struct PolygonRoomTool {
    keybindings: PolygonRoomToolKeybindings,
    unfinished_polygon: Option<UnfinishedPolygon>,
    dimension_indicator: DimensionIndicator,
}

impl UnfinishedPolygon {
    // Check the validity of the already completed corners only
    pub fn check_validity_completed(&self) -> Result<(), PolygonError<f32>> {
        Polygon::check_validity(&self.corners)
    }

    // Check the validity of the already completed corners, but with the working corner wedged
    // between the last and first corner (making it the new last corner).
    pub fn check_validity_all(&self) -> Result<(), PolygonError<f32>> {
        // TODO: Is this possible without changing the mutability of self and without reallocation?
        let mut corners = self.corners.clone();
        corners.push(self.working_corner);
        let res = Polygon::check_validity(&corners);

        res
    }

    pub fn try_into_completed(&mut self) -> Option<Polygon<f32>> {
        match self.check_validity_completed() {
            Ok(()) => Some(Polygon::new_unchecked(self.corners.drain(..).collect())),
            Err(e) => {
                warn!("Cannot turn placed corners into a polygon: {}", e);
                None
            }
        }
    }

    pub fn try_into_all(&mut self) -> Option<Polygon<f32>> {
        match self.check_validity_all() {
            Ok(()) => {
                self.corners.push(self.working_corner);
                Some(Polygon::new_unchecked(self.corners.drain(..).collect()))
            }
            Err(e) => {
                warn!(
                    "Cannot turn corners with newest corner into a polygon: {}",
                    e
                );
                None
            }
        }
    }

    pub fn try_push_working(&mut self) -> Result<(), PolygonError<f32>> {
        assert!(self.corners.len() >= 1);

        if self.corners.len() == 1 {
            return if self.corners[0] != self.working_corner {
                self.corners.push(self.working_corner);
                Ok(())
            } else {
                Err(PolygonError::VertexDoubling(self.corners[0], 0))
            };
        }

        self.check_validity_all()?;
        self.corners.push(self.working_corner);

        Ok(())
    }
}

impl PolygonRoomTool {
    pub fn new(keybindings: PolygonRoomToolKeybindings) -> Self {
        Self {
            keybindings,
            unfinished_polygon: None,
            dimension_indicator: DimensionIndicator::new(),
        }
    }
}

impl Tool for PolygonRoomTool {
    fn activate(&mut self) {}

    fn deactivate(&mut self) {
        self.unfinished_polygon = None;
    }

    fn active_update(
        &mut self,
        map: &mut MapData,
        rl: &RaylibHandle,
        transform: &Transform,
        mouse_blocked: bool,
    ) {
        let mouse_pos_m = transform.point_px_to_m(rl.get_mouse_position().into());
        let snapped_mouse_pos_m = snap_to_grid(mouse_pos_m, SNAP_SIZE);

        // Update the position of the node that would be placed into the polygon next.
        if let Some(ref mut polygon) = &mut self.unfinished_polygon {
            polygon.working_corner = snapped_mouse_pos_m;

            polygon.corners.push(polygon.working_corner);
            self.dimension_indicator.update_dimensions(&polygon.corners);
            polygon.working_corner = polygon.corners.pop().unwrap();
        }

        /* Check if the finishing keybinding has been pressed. If so, try to turn the part of the
         * polygon that is already completed into a proper polygon and push it into the map data.
         */
        if self.keybindings.finish.is_pressed(rl, mouse_blocked) {
            if let Some(ref mut polygon) = self.unfinished_polygon {
                if let Some(polygon) = polygon.try_into_completed() {
                    self.dimension_indicator.clear_dimensions();
                    map.polygons_mut().push(polygon);
                    self.unfinished_polygon = None;
                }
            }
        }

        /* Handle placing a new corner of the polygon. If the corner is placed on the first node,
         * the polygon will be created.
         */
        if self.keybindings.place_node.is_pressed(rl, mouse_blocked) {
            if let Some(ref mut polygon) = &mut self.unfinished_polygon {
                if polygon.working_corner == polygon.corners[0] {
                    /* The working corner will be ignored, since it would double the vertex at the
                     * polygon starting position.
                     */
                    if let Some(polygon) = polygon.try_into_completed() {
                        self.dimension_indicator.clear_dimensions();
                        map.polygons_mut().push(polygon);
                        self.unfinished_polygon = None;
                    }
                } else {
                    // Check if we can add the corner to the polygon without ruining it.
                    if let Err(e) = polygon.try_push_working() {
                        error!("Cannot add corner to polygon: {}", e);
                    }
                }
            } else {
                // Start a new unfinished polygon
                self.unfinished_polygon = Some(UnfinishedPolygon {
                    corners: vec![snapped_mouse_pos_m],
                    working_corner: snapped_mouse_pos_m,
                });
            }
        }

        if self.keybindings.abort.is_pressed(rl, false) {
            self.unfinished_polygon = None;
        }
    }

    fn draw(&self, map: &MapData, rld: &mut RaylibDrawHandle, transform: &Transform) {
        // TODO: Buffer triangles so the polygons don't always have to be retriangulated.
        for polygon in map.polygons() {
            let triangles = math::triangulate(polygon.clone());
            for triangle in triangles {
                let triangle: [Vec2<f32>; 3] = triangle.into();
                rld.draw_triangle(
                    transform.point_m_to_px(triangle[0]),
                    transform.point_m_to_px(triangle[1]),
                    transform.point_m_to_px(triangle[2]),
                    Color {
                        r: 180,
                        g: 180,
                        b: 180,
                        a: 255,
                    },
                )
            }
        }

        if let Some(polygon) = &self.unfinished_polygon {
            // The first corner is guaranteed to be set, so we can at least draw a line.
            if polygon.corners.len() == 1 {
                rld.draw_line_ex(
                    transform.point_m_to_px(polygon.corners[0]),
                    transform.point_m_to_px(polygon.working_corner),
                    transform.length_m_to_px(0.1),
                    Color {
                        r: 150,
                        g: 200,
                        b: 150,
                        a: 255,
                    },
                );
            } else if polygon.corners.len() == 2 {
                // We have three valid corners, so we can draw a triangle.
                rld.draw_triangle(
                    transform.point_m_to_px(polygon.corners[0]),
                    transform.point_m_to_px(polygon.corners[1]),
                    transform.point_m_to_px(polygon.working_corner),
                    Color {
                        r: 150,
                        g: 200,
                        b: 150,
                        a: 255,
                    },
                )
            } else {
                // A proper polygon can be drawn.
                if polygon.check_validity_all().is_ok() {
                    let mut corners = polygon.corners.clone();
                    corners.push(polygon.working_corner);
                    let polygon = Polygon::new_unchecked(corners);
                    let triangles = math::triangulate(polygon);
                    for triangle in triangles {
                        let triangle: [Vec2<f32>; 3] = triangle.into();
                        rld.draw_triangle(
                            transform.point_m_to_px(triangle[0]),
                            transform.point_m_to_px(triangle[1]),
                            transform.point_m_to_px(triangle[2]),
                            Color {
                                r: 150,
                                g: 200,
                                b: 150,
                                a: 255,
                            },
                        )
                    }
                } else if polygon.check_validity_completed().is_ok() {
                    let polygon = Polygon::new_unchecked(polygon.corners.clone());
                    let triangles = math::triangulate(polygon);
                    for triangle in triangles {
                        let triangle: [Vec2<f32>; 3] = triangle.into();
                        rld.draw_triangle(
                            transform.point_m_to_px(triangle[0]),
                            transform.point_m_to_px(triangle[1]),
                            transform.point_m_to_px(triangle[2]),
                            Color {
                                r: 150,
                                g: 200,
                                b: 150,
                                a: 255,
                            },
                        )
                    }
                }
            }

            self.dimension_indicator.draw(rld, transform);
        }
    }

    fn activation_key(&self) -> Button {
        self.keybindings.activation_key()
    }
}