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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
use egui::{widgets::*, *};
use kdtree::KdTree;
use kdtree::distance::squared_euclidean;
use std::collections::HashMap;
use rand::thread_rng;
use rand::distributions::{Alphanumeric,Distribution};
use crate::map::objects::*;


pub mod objects;

// This can by any object or point with its associated metadata
/// Struct that contains coordinates to help calculate nearest point in space

pub struct Map {
    pub zoom: f32,
    previous_zoom: f32,
    points: Option<HashMap<usize,MapPoint>>,
    lines: Vec<MapLine>,
    labels: Vec<MapLabel>,
    styles: HashMap<String ,MapStyle>,
    tree: Option<KdTree<f64,usize,[f64;2]>>,
    visible_points: Option<Vec<usize>>,
    map_area: Option<Rect>,
    initialized: bool,
    reference: MapBounds,
    current: MapBounds,
}

impl Default for Map {
    fn default() -> Self {
        Map::new()
    }
}

impl Widget for &mut Map {
    fn ui(self, ui_obj: &mut egui::Ui) -> Response {
        if self.initialized == false {
            let mut rng = thread_rng();
            let component_id: String = Alphanumeric
                .sample_iter(&mut rng)
                .take(15)
                .map(char::from)
                .collect();
            let idx = egui::Id::new(component_id);
            ui_obj.make_persistent_id(idx);
            self.map_area = Some(ui_obj.available_rect_before_wrap());
        } else {
            self.map_area = Some(ui_obj.ctx().used_rect());
        }
        if self.zoom != self.previous_zoom {
            self.adjust_bounds();
            self.calculate_visible_points();
            self.previous_zoom = self.zoom;
        }

        let style = egui::style::Style::default();
        let canvas = egui::Frame::canvas(&style)
            .stroke(egui::Stroke{width:2.0f32, color:Color32::DARK_GRAY});
        
        let inner_response = canvas.show(ui_obj, |ui_obj| {
            let (resp,paint) = ui_obj.allocate_painter(self.map_area.unwrap().size(), egui::Sense::click_and_drag());
            let vec = resp.drag_delta();
            if vec.length() != 0.0 {
                let coords = (vec.to_pos2().x,  vec.to_pos2().y);
                self.set_pos(self.current.pos.x - coords.0, self.current.pos.y -coords.1);
                self.calculate_visible_points();
            }
            let map_style = self.styles.get("default").unwrap().clone() * self.zoom;
            if self.zoom > 0.2 {
                for line in &self.lines{
                    paint.line_segment(line.points, map_style.line.unwrap());
                }
            }
            if self.zoom < 1.5 {
                for label in &self.labels{
                    paint.text(label.center,Align2::CENTER_CENTER,label.text.as_str(),map_style.font.clone().unwrap(),map_style.text_color);
                }
            } 
            // Drawing Mappoints
            for temp_vec_point in &self.visible_points {
                if let Some(hashm) = self.points.as_mut() {
                    let factor = (self.map_area.unwrap().center().x  + self.map_area.unwrap().min.x,self.map_area.unwrap().center().y  + self.map_area.unwrap().min.y);
                    let min_point = Pos2::new(self.current.pos.x-factor.0, self.current.pos.y-factor.1);
                    // Drawing Lines
                    if self.zoom > 0.2 {
                        for temp_point in temp_vec_point{
                            if let Some(system) = hashm.get(&temp_point) {
                                let center = Pos2::new(system.coords[0] as f32 * self.zoom,system.coords[1] as f32 * self.zoom);
                                let a_point = Pos2::new(center.x-min_point.x,center.y-min_point.y);
                                for line in &system.lines {
                                    let b_point = Pos2::new((line[0] as f32 * self.zoom)-min_point.x,(line[1] as f32 * self.zoom)-min_point.y);
                                    paint.line_segment([a_point, b_point], map_style.line.unwrap());
                                }
                            }
                        } 
                    }
                    // Drawing Points
                    for temp_point in temp_vec_point{
                        if let Some(system) = hashm.get(&temp_point) { 
                            let center = Pos2::new(system.coords[0] as f32 * self.zoom,system.coords[1] as f32 * self.zoom);
                            let viewport_point = Pos2::new(center.x-min_point.x,center.y-min_point.y);
                            let mut viewport_text = viewport_point.clone();
                            viewport_text.x += 3.0 * self.zoom;
                            viewport_text.y -= 3.0 * self.zoom;
                            if self.zoom > 0.58 {
                                paint.text(viewport_text,Align2::LEFT_BOTTOM,system.name.to_string(),FontId::new(12.00 * self.zoom,FontFamily::Proportional),Color32::LIGHT_GREEN);
                            }
                            paint.circle(viewport_point, 4.00 * self.zoom, map_style.fill_color, map_style.border.unwrap());
                        }
                    }
                }
            }
            if let Some(rect) = self.map_area{
                let zoom_slider = egui::Slider::new(&mut self.zoom, 0.1..=2.0)
                    .show_value(false)
                    //.step_by(0.1)
                    .orientation(SliderOrientation::Vertical);
                let mut pos1 = rect.right_top();
                let mut pos2 = rect.right_top();
                pos1.x -= 80.0;
                pos1.y += 120.0;
                pos2.x -= 50.0;
                pos2.y += 240.0;
                let sub_rect = egui::Rect::from_two_pos(pos1, pos2);
                ui_obj.allocate_ui_at_rect(sub_rect,|ui_obj|{
                    ui_obj.add(zoom_slider);
                });
            }
            if cfg!(debug_assertions) {
                let mut init_pos = Pos2::new(self.map_area.unwrap().left_top().x + 10.00, self.map_area.unwrap().left_top().y + 10.00);
                let mut msg = String::from("MIN:".to_string() + self.current.min.x.to_string().as_str() + "," + self.current.min.y.to_string().as_str());
                paint.debug_text(init_pos, Align2::LEFT_TOP, Color32::LIGHT_GREEN, msg);
                init_pos.y += 15.0;
                msg = "MAX:".to_string() + self.current.max.x.to_string().as_str() + "," + self.current.max.y.to_string().as_str();
                paint.debug_text(init_pos, Align2::LEFT_TOP, Color32::LIGHT_GREEN, msg);
                init_pos.y += 15.0;
                msg = "CUR:(".to_string() + self.current.pos.x.to_string().as_str() + "," + self.current.pos.y.to_string().as_str() +")";
                paint.debug_text(init_pos, Align2::LEFT_TOP, Color32::LIGHT_GREEN, msg);
                init_pos.y += 15.0;
                msg = "DST:".to_string() + self.current.dist.to_string().as_str();
                paint.debug_text(init_pos, Align2::LEFT_TOP, Color32::LIGHT_GREEN, msg);
                init_pos.y += 15.0;
                msg = "ZOM:".to_string() + self.zoom.to_string().as_str();
                paint.debug_text(init_pos, Align2::LEFT_TOP, Color32::GREEN, msg);
                if let Some(rectz) = self.map_area {
                    init_pos.y += 15.0;
                    msg = "REC:(".to_string() + rectz.left_top().x.to_string().as_str() + "," + rectz.left_top().y.to_string().as_str() + "),(" + rectz.right_bottom().x.to_string().as_str() + "," + rectz.right_bottom().y.to_string().as_str() + ")";
                    paint.debug_text(init_pos, Align2::LEFT_TOP, Color32::LIGHT_GREEN, msg);
                }
                if let Some(points) = &self.points {
                    init_pos.y += 15.0;
                    msg = "NUM:".to_string() + points.len().to_string().as_str();
                    paint.debug_text(init_pos, Align2::LEFT_TOP, Color32::LIGHT_GREEN, msg);
                }
                if let Some(vec_k) = self.visible_points.as_ref(){
                    init_pos.y += 15.0;
                    msg = "VIS:".to_string() + vec_k.len().to_string().as_str();
                    paint.debug_text(init_pos, Align2::LEFT_TOP, Color32::LIGHT_GREEN, msg);
                }
                if let Some(pointer_pos) = resp.hover_pos() {
                    init_pos.y += 15.0;
                    msg = "HVR:".to_string() + pointer_pos.x.to_string().as_str() + "," + pointer_pos.y.to_string().as_str();
                    paint.debug_text(init_pos, Align2::LEFT_TOP, Color32::LIGHT_BLUE, msg);
                }
                let vec = resp.drag_delta();
                if vec.length() != 0.0 {
                    init_pos.y += 15.0;
                    msg = "DRG:".to_string() + vec.to_pos2().x.to_string().as_str() + "," + vec.to_pos2().y.to_string().as_str();
                    paint.debug_text(init_pos, Align2::LEFT_TOP, Color32::GOLD, msg);
                }
            }
        }); 
        inner_response.response
    }

}

impl Map {
    pub fn new() -> Self {
        let mut obj = Map {
            zoom: 1.0,
            previous_zoom: 1.0,
            map_area: None,
            tree: None,
            points: None,
            lines: Vec::new(),
            labels: Vec::new(),
            styles: HashMap::new(),
            visible_points: None,
            initialized: false,
            current: MapBounds::default(),
            reference: MapBounds::default(),
        };
        obj.styles.insert("default".to_string(), MapStyle::default());
        obj
    }

    fn calculate_visible_points(&mut self) -> () {
        if self.current.dist > 0.0 {
            if let Some(tree) = &self.tree{
                let center = [(self.current.pos.x / self.zoom) as f64,(self.current.pos.y / self.zoom) as f64];
                let radius = self.current.dist.powi(2);
                let vis_pos = tree.within(&center, radius, &squared_euclidean).unwrap();
                let mut visible_points = vec![];
                for point in vis_pos {
                    visible_points.push(*point.1);
                }
                self.visible_points = Some(visible_points);
            }
        }
    }

    pub fn add_points(&mut self, points: Vec<MapPoint>) -> (){
        let mut hmap = HashMap::new();
        let mut min = (f64::INFINITY,f64::INFINITY);
        let mut max = (f64::NEG_INFINITY,f64::NEG_INFINITY);
        let mut tree = KdTree::<f64,usize,[f64;2]>::new(2);
        for mut point in points{
            point.coords[0] *= -1.0;
            point.coords[1] *= -1.0;
            if point.coords[0] < min.0 {
                min.0 = point.coords[0];
            }
            if point.coords[1] < min.1 {
                min.1 = point.coords[1];
            }
            if point.coords[0] > max.0 {
                max.0 = point.coords[0];
            }
            if point.coords[1] > max.1 {
                max.1 = point.coords[1];
            }
            let _result = tree.add([point.coords[0],point.coords[1]],point.id);
            for line in &mut point.lines {
                line[0] *= -1.0;
                line[1] *= -1.0;
                line[2] *= -1.0;
            }
            hmap.entry(point.id).or_insert(point);
        }
        self.reference.min = Pos2::new(min.0 as f32,min.1 as f32);
        self.reference.max = Pos2::new(max.0 as f32,max.1 as f32);
        self.points = Some(hmap);
        self.tree = Some(tree);
        let rect = Rect::from_min_max(self.reference.min, self.reference.max);
        self.reference.pos = rect.center();
        let dist_x = (self.map_area.unwrap().right_bottom().x as f64 - self.map_area.unwrap().left_top().x as f64)/2.0;
        let dist_y = (self.map_area.unwrap().right_bottom().y as f64 - self.map_area.unwrap().left_top().y as f64)/2.0;
        self.reference.dist = (dist_x.powi(2) + dist_y.powi(2)/2.0).sqrt() as f64;
        self.current = self.reference.clone();
        self.calculate_visible_points();
    } 

    pub fn set_pos(&mut self, x: f32, y:f32) -> () {
        if x <= self.current.max.x && x >= self.current.min.x && y <= self.current.max.y && y >= self.current.min.y{
            self.current.pos = Pos2::new(x ,y);
            self.reference.pos = Pos2::new(x/self.zoom,y/self.zoom);
        }
    }

    pub fn add_labels(mut self, labels: Vec<MapLabel>) -> () {
        self.labels = labels;
    }

    pub fn add_lines(mut self, lines: Vec<MapLine>) -> () {
         self.lines = lines
    } 

    fn adjust_bounds(&mut self) -> () {
        self.current.max.x = self.reference.max.x * self.zoom;
        self.current.max.y = self.reference.max.y * self.zoom;
        self.current.min.x = self.reference.min.x * self.zoom;
        self.current.min.y = self.reference.min.y * self.zoom;
        self.current.dist = self.reference.dist / self.zoom as f64;
        self.set_pos(self.reference.pos.x * self.zoom, self.reference.pos.y * self.zoom);
    }
    
}