easel3d_wasm.rs 1.85 KB
use std::sync::mpsc;

use easel3d::easel::canvas::{Canvas, Vertex};
use easel3d::easel::drawable::Drawable;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Color(u8, u8, u8, u8);

pub struct WasmCanvas { width       :u16
                      , height      :u16
                      , size        :usize
                      , zbuf        :Vec<f64>
                      , image       :Vec<Color> }

impl WasmCanvas {
    pub fn new(width :u16, height :u16) -> Self {
        let size = width as usize * height as usize;

        Self { width:       width
             , height:      height
             , size:        size
             , zbuf:        vec!(0.0; size)
             , image:       vec!(Color(0, 0, 0, 0xFF); size) }
    }

    pub fn image(&self) -> *const Color {
        self.image.as_ptr()
    }
}

impl Canvas<f64> for WasmCanvas {
    #[inline]
    fn width(&self) -> u16 {
        self.width
    }

    #[inline]
    fn height(&self) -> u16 {
        self.height
    }

    fn clear(&mut self) {
        self.zbuf  = vec!(0.0; self.size);
        self.image = vec!(Color(0, 0, 0, 0xFF); self.size);
    }

    fn set_pixel(&mut self, c :Vertex<f64>, color :u32) {
        let (x, y, zr) = c.as_tuple();
        let idx :usize = (y * (self.width as i32) + x) as usize;

        let r = ((color >> 16) & 0xFF) as u8;
        let g = ((color >>  8) & 0xFF) as u8;
        let b = (        color & 0xFF) as u8;

        if self.zbuf[idx] < zr {
            self.zbuf[idx]  = zr;
            self.image[idx] = Color(r, g, b, 0xFF);
        }
    }

    // Empty implementations for now… mostly not needed because it is
    // done from JavaScript…
    fn init_events(&self) {}
    fn start_events(&self, _ :mpsc::Sender<i32>) {}
    fn draw(&mut self, _ :&dyn Drawable<f64>, _ :u32) {}
    fn put_text(&self, _ :Vertex<f64>, _ :&str) {}
    fn show(&self) {}
}