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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
use std::cell::Cell;

use geom::{Bounds, Polygon, Pt2D};

use crate::assets::Assets;
use crate::backend::{GfxCtxInnards, PrerenderInnards};
use crate::{
    Canvas, Color, Drawable, EventCtx, GeomBatch, Key, ScreenDims, ScreenPt, ScreenRectangle,
    Style, Text,
};

// We organize major layers of the app with whole number z values, with lower values being more on
// top.
//
// Within each layer, we must only adjust the z-offset of individual polygons within (-1, 0] to
// avoid traversing layers.
pub(crate) const MAPSPACE_Z: f32 = 1.0;
pub(crate) const SCREENSPACE_Z: f32 = 0.0;
pub(crate) const MENU_Z: f32 = -1.0;
pub(crate) const TOOLTIP_Z: f32 = -2.0;

#[derive(Debug)]
pub struct Uniforms {
    // (cam_x, cam_y, cam_zoom)
    pub transform: [f32; 3],
    // (window_width, window_height, Z values)
    pub window: [f32; 3],
}

impl Uniforms {
    pub fn new(canvas: &Canvas) -> Uniforms {
        Uniforms {
            transform: [
                canvas.cam_x as f32,
                canvas.cam_y as f32,
                canvas.cam_zoom as f32,
            ],
            window: [
                canvas.window_width as f32,
                canvas.window_height as f32,
                MAPSPACE_Z,
            ],
        }
    }
}

pub struct GfxCtx<'a> {
    pub(crate) inner: GfxCtxInnards<'a>,
    uniforms: Uniforms,

    screencap_mode: bool,
    pub(crate) naming_hint: Option<String>,

    // TODO Don't be pub. Delegate everything.
    pub canvas: &'a Canvas,
    pub prerender: &'a Prerender,
    style: &'a Style,

    pub(crate) num_draw_calls: usize,
    pub(crate) num_forks: usize,
}

impl<'a> GfxCtx<'a> {
    pub(crate) fn new(
        prerender: &'a Prerender,
        canvas: &'a Canvas,
        style: &'a Style,
        screencap_mode: bool,
    ) -> GfxCtx<'a> {
        let uniforms = Uniforms::new(canvas);
        GfxCtx {
            inner: prerender.inner.draw_new_frame(),
            uniforms,
            canvas,
            style,
            prerender,
            num_draw_calls: 0,
            num_forks: 0,
            screencap_mode,
            naming_hint: None,
        }
    }

    // Up to the caller to call unfork()!
    // TODO Canvas doesn't understand this change, so things like text drawing that use
    // map_to_screen will just be confusing.
    pub fn fork(
        &mut self,
        top_left_map: Pt2D,
        top_left_screen: ScreenPt,
        zoom: f64,
        z: Option<f32>,
    ) {
        // map_to_screen of top_left_map should be top_left_screen
        let cam_x = (top_left_map.x() * zoom) - top_left_screen.x;
        let cam_y = (top_left_map.y() * zoom) - top_left_screen.y;

        self.uniforms.transform = [cam_x as f32, cam_y as f32, zoom as f32];
        self.uniforms.window = [
            self.canvas.window_width as f32,
            self.canvas.window_height as f32,
            z.unwrap_or(SCREENSPACE_Z),
        ];
        self.num_forks += 1;
    }

    pub fn fork_screenspace(&mut self) {
        self.uniforms.transform = [0.0, 0.0, 1.0];
        self.uniforms.window = [
            self.canvas.window_width as f32,
            self.canvas.window_height as f32,
            SCREENSPACE_Z,
        ];
        self.num_forks += 1;
    }

    pub fn unfork(&mut self) {
        self.uniforms = Uniforms::new(self.canvas);
        self.num_forks += 1;

        // println!("{:?}", backtrace::Backtrace::new());
    }

    pub fn clear(&mut self, color: Color) {
        self.inner.clear(color);
    }

    // Doesn't take &Polygon, because this is inherently inefficient. If performance matters,
    // upload, cache, and redraw.
    pub fn draw_polygon(&mut self, color: Color, poly: Polygon) {
        GeomBatch::from(vec![(color, poly)]).draw(self);
    }

    pub fn redraw(&mut self, obj: &Drawable) {
        self.inner
            .redraw(obj, &self.uniforms, &self.prerender.inner);
        self.num_draw_calls += 1;

        // println!("{:?}", backtrace::Backtrace::new());
    }

    pub fn redraw_at(&mut self, top_left: ScreenPt, obj: &Drawable) {
        self.fork(Pt2D::new(0.0, 0.0), top_left, 1.0, None);
        self.redraw(obj);
        self.unfork();
    }

    // TODO Stateful API :(
    pub fn enable_clipping(&mut self, rect: ScreenRectangle) {
        let scale_factor = self.prerender.get_scale_factor();
        self.inner.enable_clipping(rect, scale_factor, self.canvas);
    }

    pub fn disable_clipping(&mut self) {
        let scale_factor = self.prerender.get_scale_factor();
        self.inner.disable_clipping(scale_factor, self.canvas);
    }

    // Canvas stuff.

    /// Draw a tooltip where the mouse is
    pub fn draw_mouse_tooltip(&mut self, txt: Text) {
        self.draw_tooltip_at(
            txt,
            ScreenPt::new(self.canvas.cursor.x, self.canvas.cursor.y + 20.0),
        )
    }

    /// Draw a tooltip somewhere on the screen
    pub fn draw_tooltip_at(&mut self, txt: Text, center: ScreenPt) {
        if txt.is_empty() {
            return;
        }

        // Add some padding
        let pad = 5.0;
        let txt = txt.default_fg(self.style.text_tooltip_color);
        let txt_batch = txt.render(self);
        let raw_dims = txt_batch.get_dims();
        let dims = ScreenDims::new(raw_dims.width + 2.0 * pad, raw_dims.height + 2.0 * pad);

        // TODO Maybe also consider the cursor as a valid center
        let pt = dims.top_left_for_corner(center, self.canvas);
        let mut batch = GeomBatch::new();
        // TODO Outline?
        batch.push(
            Color::BLACK,
            Polygon::rectangle(dims.width, dims.height).translate(pt.x, pt.y),
        );
        batch.append(txt_batch.translate(pt.x + pad, pt.y + pad));

        // fork_screenspace, but with an even more prominent Z
        self.uniforms.transform = [0.0, 0.0, 1.0];
        self.uniforms.window = [
            self.canvas.window_width as f32,
            self.canvas.window_height as f32,
            TOOLTIP_Z,
        ];
        self.num_forks += 1;
        // Temporarily disable clipping if needed.
        let clip = self
            .inner
            .take_clip(self.prerender.get_scale_factor(), self.canvas);
        batch.draw(self);
        self.unfork();
        self.inner.restore_clip(clip);
    }

    pub fn get_screen_bounds(&self) -> Bounds {
        self.canvas.get_screen_bounds()
    }

    pub fn screen_to_map(&self, pt: ScreenPt) -> Pt2D {
        self.canvas.screen_to_map(pt)
    }

    pub fn get_cursor_in_map_space(&self) -> Option<Pt2D> {
        self.canvas.get_cursor_in_map_space()
    }

    pub(crate) fn get_num_uploads(&self) -> usize {
        self.prerender.num_uploads.get()
    }

    pub fn is_screencap(&self) -> bool {
        self.screencap_mode
    }

    pub fn set_screencap_naming_hint(&mut self, hint: String) {
        assert!(self.screencap_mode);
        assert!(self.naming_hint.is_none());
        self.naming_hint = Some(hint);
    }

    pub fn upload(&mut self, batch: GeomBatch) -> Drawable {
        self.prerender.upload(batch)
    }

    // Delegation to assets
    pub fn default_line_height(&self) -> f64 {
        *self.prerender.assets.default_line_height.borrow()
    }

    pub fn style(&self) -> &Style {
        self.style
    }

    pub fn is_key_down(&self, key: Key) -> bool {
        self.canvas.keys_held.contains(&key)
    }
}

// TODO Don't expose this directly
// TODO Rename or something maybe. This actually owns all the permanent state of everything.
pub struct Prerender {
    pub(crate) inner: PrerenderInnards,
    pub(crate) assets: Assets,
    pub(crate) num_uploads: Cell<usize>,
    pub(crate) scale_factor: f64,
}

impl Prerender {
    pub fn upload(&self, batch: GeomBatch) -> Drawable {
        self.actually_upload(true, batch)
    }

    pub(crate) fn upload_temporary(&self, batch: GeomBatch) -> Drawable {
        self.actually_upload(false, batch)
    }

    pub fn get_total_bytes_uploaded(&self) -> usize {
        self.inner.total_bytes_uploaded.get()
    }

    fn actually_upload(&self, permanent: bool, batch: GeomBatch) -> Drawable {
        self.num_uploads.set(self.num_uploads.get() + 1);
        self.inner.actually_upload(permanent, batch)

        // println!("{:?}", backtrace::Backtrace::new());
    }

    pub(crate) fn request_redraw(&self) {
        self.inner.request_redraw()
    }

    pub(crate) fn get_scale_factor(&self) -> f64 {
        self.scale_factor
    }

    pub(crate) fn window_size(&self) -> ScreenDims {
        self.inner.window_size(self.get_scale_factor())
    }

    pub(crate) fn window_resized(&self, new_size: ScreenDims) {
        self.inner.window_resized(new_size, self.get_scale_factor())
    }

    pub fn assets_base_url(&self) -> Option<&str> {
        self.assets.base_url()
    }

    pub fn assets_are_gzipped(&self) -> bool {
        self.assets.are_gzipped()
    }
}

impl std::convert::AsRef<Prerender> for GfxCtx<'_> {
    fn as_ref(&self) -> &Prerender {
        self.prerender
    }
}

impl std::convert::AsRef<Prerender> for EventCtx<'_> {
    fn as_ref(&self) -> &Prerender {
        self.prerender
    }
}

impl std::convert::AsRef<Prerender> for Prerender {
    fn as_ref(&self) -> &Prerender {
        self
    }
}