use crate::geometry::*; use crate::render::{Surface, Shader, Surfaces}; use std::fmt::{Debug, Formatter}; use std::rc::Rc; use std::cell::RefCell; use std::io; #[cfg(feature="threads")] use std::sync::{Arc, Mutex}; #[derive(Debug)] pub struct ShaderBinding { shader: Option>, rect: Rectangle, opacity: u8 } #[derive(Clone)] pub struct BoundSurface { pub binding: T } impl Debug for BoundSurface>> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("BoundSurface") .field("shader", &self.binding.borrow().shader) .field("opacity", &self.binding.borrow().opacity) .finish() } } pub type SimpleSurface = BoundSurface>>; impl Default for BoundSurface>>{ fn default() -> Self { Self { binding: Rc::new(RefCell::new(ShaderBinding { shader: None, rect: Rectangle::everything(), opacity: 255 })), } } } impl Surface for BoundSurface>> { fn rect(&self) -> Rectangle { self.binding.borrow().rect.clone() } fn with_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) { self.binding.borrow_mut().shader = Some(shader); } fn clear_shader(&mut self) { self.binding.borrow_mut().shader = None; } fn set_rect(&mut self, rect: &Rectangle) { self.binding.borrow_mut().rect = rect.clone(); } fn opacity(&self) -> u8 { self.binding.borrow().opacity } fn set_opacity(&mut self, opacity: u8) { self.binding.borrow_mut().opacity = opacity } } #[cfg(feature="threads")] pub type SharedSurface = BoundSurface>>; #[cfg(feature="threads")] impl Default for BoundSurface>> { fn default() -> Self { Self { binding: Arc::new(Mutex::new(ShaderBinding { shader: None, rect: Rectangle::everything() })), } } } #[cfg(feature="threads")] impl Surface for BoundSurface>> { fn rect(&self) -> Rectangle { let r = self.binding.lock().unwrap(); r.rect.clone() //self.binding.lock().unwrap().rect.clone() } fn with_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) { self.binding.lock().unwrap().shader = Some(shader); } fn clear_shader(&mut self) { self.binding.lock().unwrap().shader = None; } } #[cfg(feature="threads")] impl Debug for BoundSurface>> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("BoundSurface") .field("shader", &self.binding.lock().unwrap().shader) .finish() } } #[derive(Clone)] pub struct SurfacePool { surfaces: Vec } impl Debug for SurfacePool { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.surfaces.fmt(f) } } impl SurfacePool { pub const fn new() -> Self { Self { surfaces: Vec::new() } } pub fn iter(&self) -> std::slice::Iter { self.surfaces.iter() } } impl Surfaces for SurfacePool { fn new_surface(&mut self, area: &Rectangle) -> Result { let mut surface = S::default(); surface.set_rect(area); self.surfaces.push(surface.clone()); return Ok(surface); } }