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
//! Parent module around code that puts stuff on the screen.
//!
//! This covers an HTML canvas with WebGL (implemented in Paddle itself), as well as HTML display through the crate `div`.
//! While `Display` covers the full screen, `DisplayArea` are views into parts of tje display, used for light-weight window management.
//!
//! In Paddle, drawing an object to the WebGL canvas consists of two separate phases on the CPU, tesselation + rendering.
//! The display accepts pre-tessellated and raw objects, using either `draw_mesh()` or `draw()` (on DisplayArea).

mod canvas;
mod display_area;
mod gpu;
mod render;
mod text;

pub use canvas::*;
pub use display_area::*;
use div::DivHandle;
pub use gpu::{GpuConfig, GpuMesh, GpuTriangle, GpuVertex};
pub use render::*;
pub use text::*;

use crate::quicksilver_compat::Background;
use crate::*;
use crate::{graphics::AbstractMesh, Vector};
use crate::{graphics::ImageLoader, graphics::TextureConfig, quicksilver_compat::Color};
use wasm_bindgen::{JsCast, JsValue};
use web_sys::{Element, HtmlCanvasElement};

/// An object to manage the *full* display area for your game inside the browser.
///
/// The `Display` object is responsible for putting stuff to see in front of the user and nothing else.
/// It also includes configuration options, such as GPU settings.
pub struct Display {
    /// Position relative to browser page (in browser coordinates)
    browser_region: Rectangle,
    /// Game / World coordinates. Used to refer to game objects and UI elements independently of resolution or size in the browser.
    game_coordinates: Vector,
    /// A canvas with WebGL capabilities (covering the full display area)
    canvas: WebGLCanvas,
    /// Screen background color. A clear to this color is invoked every frame.
    background_color: Option<Color>,
    /// Div element covering the full screen. (could be used for html elements outside of any frames)
    div: DivHandle,
    /// Buffer for on-the-fly tessellation
    tessellation_buffer: AbstractMesh,
}

pub struct DisplayConfig {
    pub canvas: CanvasConfig,
    pub pixels: Vector,
    pub texture_config: TextureConfig,
    pub gpu_config: GpuConfig,
    pub update_delay_ms: i32,
    pub background: Option<Color>,
    pub capture_touch: bool,
}
impl Default for DisplayConfig {
    fn default() -> Self {
        Self {
            canvas: CanvasConfig::HtmlId("paddle-canvas"),
            pixels: Vector::new(1280, 720),
            update_delay_ms: 8,
            texture_config: Default::default(),
            gpu_config: Default::default(),
            background: None,
            capture_touch: true,
        }
    }
}

pub enum CanvasConfig {
    HtmlId(&'static str),
    HtmlElement(HtmlCanvasElement),
}

use crate::{NutsCheck, PaddleResult, Rectangle, Transform};

impl Display {
    pub(super) fn new(config: DisplayConfig) -> PaddleResult<Self> {
        let canvas = match config.canvas {
            CanvasConfig::HtmlElement(el) => el,
            CanvasConfig::HtmlId(id) => canvas_by_id(id)?,
        };
        let parent_element = canvas.parent_element().expect("Canvas has no parent");
        if config.capture_touch {
            let parent_html = parent_element
                .clone()
                .dyn_into::<web_sys::HtmlElement>()
                .expect("Canvas parent is not an HTML element");
            parent_html
                .style()
                .set_property("touch-action", "none")
                .expect("Setting CSS failed");
        }

        // For now the only option is game_coordinates = pixels
        let game_coordinates = config.pixels;

        let canvas = WebGLCanvas::new(canvas, config.pixels, &config.gpu_config)?;
        // Browser region is relative to window and needs to be known to handle input
        let browser_region = find_browser_region(canvas.html_element())?;

        // Initialize with game coordinates, which allows using them again for later calls
        let size = (game_coordinates.x as u32, game_coordinates.y as u32);
        div::init_ex_with_element(parent_element, (0, 0), Some(size))
            .expect("Div initialization failed");

        div::resize(
            browser_region.width() as u32,
            browser_region.height() as u32,
        )
        .expect("Div initialization failed");

        // For binding textures as they arrive
        ImageLoader::register(canvas.clone_webgl(), config.texture_config);

        let background_color = config.background;

        let div = div::new_styled::<_, _, &'static str, _, _>(
            0,
            0,
            size.0,
            size.1,
            "",
            &[],
            &[("pointer-events", "None")],
        )?;
        div.set_css("z-index", &(-1).to_string())?;

        Ok(Self {
            canvas,
            browser_region,
            game_coordinates,
            background_color,
            div,
            tessellation_buffer: AbstractMesh::new(),
        })
    }
    pub(crate) fn canvas_mut(&mut self) -> &mut WebGLCanvas {
        &mut self.canvas
    }

    /// Position relative to browser page and size in browser pixels
    pub fn browser_region(&self) -> Rectangle {
        self.browser_region
    }
    /// How many pixels are rendered in the Canvas
    pub fn resolution(&self) -> Vector {
        self.canvas.resolution()
    }

    pub fn clear(&mut self) {
        if let Some(col) = self.background_color {
            self.canvas.clear(col);
        }
    }

    /// Transforms from coordinates used inside the game (aka world coordinates) to browser coordinates (as used by e.g. CSS pixels)
    pub fn game_to_browser_coordinates(&self) -> Transform {
        Transform::scale(
            self.browser_region
                .size
                .times(self.game_coordinates.recip()),
        ) * Transform::translate(self.browser_region.pos)
    }

    /// Gives result for x axis (assuming y is the same)
    pub fn browser_to_game_pixel_ratio(&self) -> f32 {
        self.browser_region.width() / self.game_coordinates.x
    }

    /// Fixed to 16:9 ratio for now
    pub fn fit_to_visible_area(&mut self, margin: f64) -> PaddleResult<()> {
        let web_window = web_sys::window().unwrap();

        let w = web_window
            .inner_width()
            .map_err(JsError::from_js_value)?
            .as_f64()
            .unwrap();
        let h = web_window
            .inner_height()
            .map_err(JsError::from_js_value)?
            .as_f64()
            .unwrap();

        let (w, h) = scale_16_to_9(
            w - self.browser_region.x() as f64 - margin,
            h - self.browser_region.y() as f64 - margin,
        );

        self.canvas.set_size((w as f32, h as f32));

        // Resizing might change position (How exactly can be completely unpredictable due to CSS, media-queries etc.)
        self.adjust_display()?;
        Ok(())
    }
    /// Look up size and position of canvas in the browser and update input and drawing transformations accordingly.
    /// This should be called after the canvas size has changed, for example when the window is resized.
    /// When calling `fit_to_visible_area()`, the display is adjusted automatically (no need to call `adjust_display()` manually).
    pub fn adjust_display(&mut self) -> PaddleResult<()> {
        self.update_browser_region();

        let (x, y) = self.div_offset()?;
        div::reposition(x, y)?;
        div::resize(
            self.browser_region.size.x as u32,
            self.browser_region.size.y as u32,
        )?;
        Ok(())
    }

    fn update_browser_region(&mut self) {
        if let Some(br) = find_browser_region(self.canvas.html_element()).nuts_check() {
            self.browser_region = br;
        }
    }
    /// Offset to ancestor with respect to which absolute positioned elements will be placed. (in browser coordinates)
    fn div_offset(&self) -> PaddleResult<(u32, u32)> {
        find_div_offset(
            self.canvas.html_element().clone().into(),
            &self.browser_region,
        )
    }

    pub fn draw_ex<'a>(
        &'a mut self,
        draw: &impl Tessellate,
        bkg: impl Into<Background<'a>>,
        trans: Transform,
        z: i16,
    ) {
        // TODO: Keep tesselation for frame and apply transformation once per frame (potentially on GPU)
        draw.tessellate(&mut self.tessellation_buffer, bkg.into());
        self.canvas.render(&self.tessellation_buffer, trans, z);
        self.tessellation_buffer.clear();
    }
    // Insert triangles to buffer with a transform and z value
    pub fn draw_mesh_ex(&mut self, mesh: &AbstractMesh, t: Transform, z: i16) {
        self.canvas.render(mesh, t, z);
    }
}

fn find_browser_region(canvas: &HtmlCanvasElement) -> PaddleResult<Rectangle> {
    let web_window = web_sys::window().unwrap();
    let dom_rect = canvas.get_bounding_client_rect();

    let page_x_offset = web_window.page_x_offset().map_err(JsError::from_js_value)?;
    let page_y_offset = web_window.page_y_offset().map_err(JsError::from_js_value)?;
    let x = dom_rect.x() + page_x_offset;
    let y = dom_rect.y() + page_y_offset;
    let w = dom_rect.width();
    let h = dom_rect.height();
    let browser_region = Rectangle::new((x as f32, y as f32), (w as f32, h as f32));
    Ok(browser_region)
}
fn find_div_offset(canvas: Element, browser_region: &Rectangle) -> PaddleResult<(u32, u32)> {
    let npa = nearest_positioned_ancestor(canvas).map_err(JsError::from_js_value)?;
    let npa_rect = npa.get_bounding_client_rect();
    let npa_pos = Vector::new(npa_rect.x(), npa_rect.y());
    let offset = browser_region.pos - npa_pos;
    Ok((offset.x as u32, offset.y as u32))
}
fn nearest_positioned_ancestor(element: Element) -> Result<Element, JsValue> {
    let web_window = web_sys::window().unwrap();
    let mut npa = element;
    loop {
        if let Some(property) = &web_window.get_computed_style(&npa)? {
            match property.get_property_value("position")?.as_str() {
                "" | "static" => {
                    // go to parent
                }
                "absolute" | "relative" | "fixed" | "sticky" => {
                    return Ok(npa);
                }
                _ => {
                    return Err("Unexpected position attribute".into());
                }
            }
        }
        if let Some(parent) = npa.parent_element() {
            npa = parent;
        } else {
            return Ok(npa);
        }
    }
}

fn canvas_by_id(id: &str) -> PaddleResult<HtmlCanvasElement> {
    let document = web_sys::window().unwrap().document().unwrap();
    let canvas = document
        .get_element_by_id(id)
        .ok_or_else(|| ErrorMessage::technical(format!("No canvas with id {}", id)))?;
    canvas.dyn_into::<HtmlCanvasElement>().map_err(|e| {
        ErrorMessage::technical(format!(
            "Not a canvas. Err: {}",
            e.to_string().as_string().unwrap()
        ))
    })
}

fn scale_16_to_9(w: f64, h: f64) -> (f64, f64) {
    if w * 9.0 > h * 16.0 {
        (h * 16.0 / 9.0, h)
    } else {
        (w, w * 9.0 / 16.0)
    }
}