Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clickable area according to bitmap #24

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
215 changes: 215 additions & 0 deletions examples/clickable.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
use conifer::canvas::*;
use conifer::point::*;
use conifer::prelude::*;
use conifer::util::*;
use std::path::Path;

use env_logger;
use log::debug;

trait Render {
fn render(&self, canvas: &mut Canvas) -> Result<(), &'static str>;
}

trait InteractiveObject<T> {
/// Test whether coordinates `x` `y` activate the object.
fn poke(&self, x: usize, y: usize) -> bool;
/// Compute interaction when it makes contact.
fn trigger(&mut self, x: usize, y: usize) -> Option<T>;
}

enum Directions {
Left,
Right,
Top,
Bottom,
}

struct ClickableImage<T> {
origin: (usize, usize),
image: Canvas,
bmap: BlitMap,
callback: Box<dyn FnMut() -> T>,
}

impl<T> ClickableImage<T> {
fn new<P: AsRef<Path>>(
path: P,
origin: (usize, usize),
callback: impl FnMut() -> T + 'static,
) -> Result<Self, Box<dyn Error>> {
let image = load_image(path)?;
let bmap = BlitMap::from_canvas_with_bg_color(&image, 255, 0, 255);
Ok(ClickableImage {
origin,
image,
bmap,
callback: Box::new(callback),
})
}
}

impl<T> InteractiveObject<T> for ClickableImage<T> {
fn poke(&self, x: usize, y: usize) -> bool {
if coord_in_area(x, y, 0, 0, self.image.width, self.image.height) {
if let Ok(b) = self.bmap.get_bool(x, y) {
b
} else {
false
}
} else {
false
}
}

fn trigger(&mut self, x: usize, y: usize) -> Option<T> {
if self.poke(x, y) {
Some((self.callback)())
} else {
None
}
}
}

/// Non empty.
struct ComposedClickableImage<T> {
components: Vec<ClickableImage<T>>,
}

impl<T> ComposedClickableImage<T> {
fn new(image: ClickableImage<T>) -> Self {
ComposedClickableImage {
components: vec![image],
}
}

fn push(&mut self, image: ClickableImage<T>) {
self.components.push(image);
}
}

impl<T> InteractiveObject<T> for ComposedClickableImage<T> {
fn poke(&self, x: usize, y: usize) -> bool {
self.components.iter().any(|c| c.poke(x, y))
}

fn trigger(&mut self, x: usize, y: usize) -> Option<T> {
self.components
.iter_mut()
.fold(None, |acc, c| acc.or_else(|| c.trigger(x, y)))
}
}

impl<T> Render for ClickableImage<T> {
fn render(&self, canvas: &mut Canvas) -> Result<(), &'static str> {
canvas.blit_canvas(
&self.image,
self.origin.0 as isize,
self.origin.1 as isize,
&self.bmap,
)
}
}

impl<T> Render for ComposedClickableImage<T> {
fn render(&self, canvas: &mut Canvas) -> Result<(), &'static str> {
self.components
.iter()
.fold(Ok(()), |acc, c| acc.and(c.render(canvas)))
}
}

fn main() -> Result<(), Box<dyn Error>> {
env_logger::init();
let mut c = Config::auto()?;

let mut dpad_left = ClickableImage::new("examples/images/d-pad-left.png", (50, 50), || {
Directions::Left
})?;
let mut dpad_right = ClickableImage::new("examples/images/d-pad-right.png", (50, 50), || {
Directions::Right
})?;
let mut dpad_top = ClickableImage::new("examples/images/d-pad-top.png", (50, 50), || {
Directions::Top
})?;
let mut dpad_bottom =
ClickableImage::new("examples/images/d-pad-bottom.png", (50, 50), || {
Directions::Bottom
})?;

let mut dpad = ComposedClickableImage::new(dpad_left);
dpad.push(dpad_right);
dpad.push(dpad_top);
dpad.push(dpad_bottom);

let img_pine = load_image("examples/images/pine.png")?;

// create a blit mask from any alpha > 0
let img_pine_blit_map = BlitMap::from_canvas_with_alpha(&img_pine);

let background = Canvas::from_color(c.screen_width(), c.screen_height(), 0, 100, 0);

let (mut x0, mut y0) = (0, 0);

c.run(move |canvas, event| {
canvas.copy_from_canvas(&background);

canvas.blit_canvas(&img_pine, x0, y0, &img_pine_blit_map)?;

dpad.render(canvas)?;

if let Event::Timer(_, _) = event {
return Ok(RunResponse::Draw);
}

debug!("Non-timer event");
debug!("x0:{},y0:{}", x0, y0);

if let Event::Swipe(swipe) = event {
debug!("Swipe {:?}", swipe);
if let Some(Gesture::Tap(Point { x, y, time })) = swipe.tap(10) {
debug!("Tap x:{},y:{}", x, y);
let poke = dpad.poke(
isize::max(0, x - 50) as usize,
isize::max(0, y - 50) as usize,
);
debug!("Poke? {}", poke);
if let Some(dir) = dpad.trigger(
isize::max(0, x - 50) as usize,
isize::max(0, y - 50) as usize,
) {
match dir {
Directions::Left => {
x0 = isize::max(0, x0 - 10);
debug!("x0:{},y0:{}", x0, y0);
}
Directions::Right => {
x0 = isize::min(
x0 + 10,
canvas.width as isize - img_pine.width as isize,
);
debug!("x0:{},y0:{}", x0, y0);
}
Directions::Top => {
y0 = isize::max(0, y0 - 10);
debug!("x0:{},y0:{}", x0, y0);
}
Directions::Bottom => {
y0 = isize::min(
y0 + 10,
canvas.height as isize - img_pine.height as isize,
);
debug!("x0:{},y0:{}", x0, y0);
}
}
}
} else if swipe.finished {
debug!("Exit canvas");
return Ok(RunResponse::Exit);
}
}
debug!("Draw canvas");
Ok(RunResponse::Draw)
})?;
Ok(())
}
Binary file added examples/images/d-pad-bottom.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/images/d-pad-left.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/images/d-pad-right.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/images/d-pad-top.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/images/d-pad.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
43 changes: 41 additions & 2 deletions src/blit_map.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,30 @@
use crate::canvas::Canvas;
use std::error::Error;
use crate::util::*;

pub struct BlitMap {
pub width: usize,
pub height: usize,
pub map: Vec<bool>,
}

impl BlitMap {
pub fn bound_check(&self, x: usize, y:usize) -> bool {
(x >= 0 && x < self.width && y >= 0 && y < self.height)
}

pub fn get_bool(&self, x: usize, y: usize) -> Result<bool, Box<dyn Error>> {
if self.bound_check(x,y) {
Ok(self.map[y * self.width + x])
} else {
Err("Out of bonds.".into())
}
}

pub fn from_canvas(canvas: &Canvas) -> BlitMap {
return BlitMap {
width: canvas.width,
height: canvas.height,
map: vec![true; canvas.width * canvas.height],
};
}
Expand All @@ -17,11 +35,32 @@ impl BlitMap {
for y in 0..canvas.height {
let b_index = (y * canvas.width) + x;
let cur_index = b_index;
if canvas.pixels[cur_index + 3] > 0 {
if canvas.pixels[cur_index] & 4278190080 > 0 {
b[b_index] = true;
}
}
}
BlitMap { map: b }
BlitMap {
width: canvas.width,
height: canvas.height,
map: b }
}

pub fn from_canvas_with_bg_color(canvas: &Canvas, r: u8, g: u8, b: u8) -> BlitMap {
let mut bmap = vec![false; canvas.width * canvas.height];
for x in 0..canvas.width {
for y in 0..canvas.height {
let b_index = (y * canvas.width) + x;
let cur_index = b_index;
let (_, pix_r, pix_g, pix_b) = rgba_from_color(canvas.pixels[cur_index]);
if (pix_r, pix_g, pix_b) != (r,g,b) {
bmap[b_index] = true;
}
}
}
BlitMap {
width: canvas.width,
height: canvas.height,
map: bmap }
}
}
2 changes: 0 additions & 2 deletions src/canvas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,6 @@ impl Canvas {
let cur_index = ((ry * self.width as isize + rx) as isize) as usize;
let r_index = b_index;
self.pixels[cur_index] = canvas.pixels[r_index];
self.pixels[cur_index + 1] = canvas.pixels[r_index + 1];
self.pixels[cur_index + 2] = canvas.pixels[r_index + 2];
}
}
}
Expand Down
17 changes: 17 additions & 0 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,20 @@ pub fn load_image<P: AsRef<Path>>(path: P) -> Result<Canvas, Box<dyn Error>> {
pub fn color_from_rgb(r: u8, g: u8, b: u8) -> u32 {
255 << 24 | (r as u32) << 16 | (g as u32) << 8 | b as u32
}

pub fn color_from_rgba(r: u8, g: u8, b: u8, a: u8) -> u32 {
(a as u32) << 24 | (r as u32) << 16 | (g as u32) << 8 | b as u32
}

pub fn rgba_from_color(color: u32) -> (u8, u8, u8, u8) {
// assuming it's encoded as argb
(((color & 4278190080) >> 24) as u8,
((color & 16711680) >> 16) as u8,
((color & 65280) >> 8) as u8,
(color & 255) as u8
)
}

pub fn coord_in_area(x: usize, y: usize, x0: usize, y0: usize, xm: usize, ym: usize) -> bool {
x >= x0 && x <= xm && y >= y0 && y <= ym
}