renderbug/src/render.rs

123 lines
2.8 KiB
Rust
Raw Normal View History

use std::rc::Rc;
use std::cell::RefCell;
use std::io;
#[cfg(feature="threads")]
use std::sync::{Arc, Mutex};
use crate::lib8::RGB8;
use crate::geometry::*;
pub trait Shader: Send {
fn draw(&self, surface_coords: VirtualCoordinates) -> RGB8;
}
pub trait Surface: Default + Clone {
fn with_shader<F: FnMut(&dyn Shader)>(&self, f: F);
fn set_shader(&mut self, shader: Box<dyn Shader>);
fn clear_shader(&mut self);
}
pub trait Surfaces<T: Surface> {
fn new_surface(&mut self) -> Result<T, io::Error>;
}
pub trait Display<T: Surface>: Surfaces<T> {
fn start_frame(&mut self) {}
fn end_frame(&mut self) {}
fn render_frame(&mut self);
}
pub struct ShaderBinding {
shader: Option<Box<dyn Shader>>,
}
#[derive(Clone)]
pub struct BoundSurface<T> {
pub binding: T
}
pub type SimpleSurface = BoundSurface<Rc<RefCell<ShaderBinding>>>;
impl Default for BoundSurface<Rc<RefCell<ShaderBinding>>>{
fn default() -> Self {
Self {
binding: Rc::new(RefCell::new(ShaderBinding {
shader: None,
})),
}
}
}
impl Surface for BoundSurface<Rc<RefCell<ShaderBinding>>> {
fn with_shader<F: FnMut(&dyn Shader)>(&self, mut f: F) {
if let Some(ref shader) = self.binding.borrow().shader {
f(shader.as_ref());
}
}
fn set_shader(&mut self, shader: Box<dyn Shader>) {
self.binding.borrow_mut().shader = Some(shader);
}
fn clear_shader(&mut self) {
self.binding.borrow_mut().shader = None;
}
}
#[cfg(feature="threads")]
pub type SharedSurface = BoundSurface<Arc<Mutex<ShaderBinding>>>;
#[cfg(feature="threads")]
impl Default for BoundSurface<Arc<Mutex<ShaderBinding>>> {
fn default() -> Self {
Self {
binding: Arc::new(Mutex::new(ShaderBinding {
shader: None,
})),
}
}
}
#[cfg(feature="threads")]
impl Surface for BoundSurface<Arc<Mutex<ShaderBinding>>> {
fn with_shader<F: FnMut(&dyn Shader)>(&self, mut f: F) {
if let Some(ref shader) = self.binding.lock().unwrap().shader {
f(shader.as_ref());
}
}
fn set_shader(&mut self, shader: Box<dyn Shader>) {
self.binding.lock().unwrap().shader = Some(shader);
}
fn clear_shader(&mut self) {
self.binding.lock().unwrap().shader = None;
}
}
pub struct SurfacePool<S: Surface + Default> {
surfaces: Vec<S>
}
impl<S: Surface + Default> SurfacePool<S> {
pub const fn new() -> Self {
Self {
surfaces: Vec::new()
}
}
pub fn iter(&self) -> std::slice::Iter<S> {
self.surfaces.iter()
}
}
impl<S: Surface + Default + Clone> Surfaces<S> for SurfacePool<S> {
fn new_surface(&mut self) -> Result<S, io::Error> {
let surface = S::default();
self.surfaces.push(surface.clone());
return Ok(surface);
}
}