diff --git a/examples/game_of_life.rs b/examples/game_of_life.rs index 8868345..d569cbc 100644 --- a/examples/game_of_life.rs +++ b/examples/game_of_life.rs @@ -4,7 +4,6 @@ use mini_gl_fb::{Config, BufferFormat}; use mini_gl_fb::glutin::{MouseButton, VirtualKeyCode}; use std::time::SystemTime; -use std::cmp; const WIDTH: usize = 200; const HEIGHT: usize = 200; @@ -46,9 +45,9 @@ fn main() { if input.mouse_is_down(MouseButton::Left) { // Mouse was pressed - let (mut x, mut y) = input.mouse_pos; - x = cmp::min(x, WIDTH - 1); - y = cmp::min(y, HEIGHT - 1); + let (x, y) = input.mouse_pos; + let x = x.min(WIDTH as f64 - 0.0001).max(0.0).floor() as usize; + let y = y.min(HEIGHT as f64 - 0.0001).max(0.0).floor() as usize; cells[y * WIDTH + x] = true; fb.update_buffer(&cells); // Give the user extra time to make something pretty each time they click diff --git a/src/breakout.rs b/src/breakout.rs index ff9069f..172784a 100644 --- a/src/breakout.rs +++ b/src/breakout.rs @@ -18,8 +18,13 @@ pub struct GlutinBreakout { pub struct BasicInput { /// The mouse position in buffer coordinates. /// - /// The bottom left of the window is (0, 0). - pub mouse_pos: (usize, usize), + /// The bottom left of the window is (0, 0). Pixel centers are at multiples of (0.5, 0.5). If + /// you want to use this to index into your buffer, in general the following is sufficient: + /// + /// - clamp each coordinate to the half-open range [0.0, buffer_size) + /// - take the floor of each component + /// - cast to usize and compute an index: `let index = y * WIDTH + x` + pub mouse_pos: (f64, f64), /// Stores whether a mouse button was down and is down, in that order. /// /// If a button has not been pressed yet it will not be in the map. diff --git a/src/core.rs b/src/core.rs index f8bd4ec..6319cf8 100644 --- a/src/core.rs +++ b/src/core.rs @@ -250,7 +250,7 @@ impl Internal { let mut running = true; let mut input = BasicInput { // Not sure how to set mouse pos at start - mouse_pos: (0, 0), + mouse_pos: (0.0, 0.0), mouse: HashMap::new(), keys: HashMap::new(), modifiers: Default::default(), @@ -307,10 +307,10 @@ impl Internal { let (x, y): (f64, f64) = pos.to_physical(dpi_factor).into(); let x_scale = self.fb.buffer_width as f64 / (self.fb.vp_width as f64); let y_scale = self.fb.buffer_height as f64 / (self.fb.vp_height as f64); - let mut mouse_pos = ( - (x * x_scale).floor() as usize, + let mouse_pos = ( + x * x_scale, // use the OpenGL texture coordinate system instead of window coordinates - (self.fb.buffer_height as f64 - y * y_scale).floor() as usize + self.fb.buffer_height as f64 - y * y_scale ); input.mouse_pos = mouse_pos; }