use crate::api::{Context, GraphicsContext};
use crate::image::Image;
use crate::sprite::Sprite;
use crate::types::{Rect, RectPx};
use crate::renderer::{DrawCallHandle, Shaders, TextureWrapping};
#[derive(Clone, Debug)]
pub struct Spritesheet {
pub(crate) handle: DrawCallHandle,
}
impl Spritesheet {
pub fn draw<'a, 'b>(&'b self, ctx: &'a mut GraphicsContext) -> Sprite<'a, 'b> {
ctx.renderer.draw(&self.handle)
}
pub fn upload_texture_region<R: Into<Rect>>(
&self,
ctx: &mut GraphicsContext,
region: R,
image: &Image,
) -> bool {
let Rect {
x,
y,
width,
height,
} = region.into();
let region = RectPx {
x: x.floor() as i32,
y: y.floor() as i32,
width: width.floor() as i32,
height: height.floor() as i32,
};
ctx.renderer
.upload_texture_region(&self.handle, region, image)
}
pub fn resize_texture(
&self,
ctx: &mut GraphicsContext,
new_width: i32,
new_height: i32,
) -> bool {
ctx.renderer
.resize_texture(&self.handle, new_width, new_height)
}
}
#[derive(Clone, Copy)]
pub struct AlphaBlending {
pub blend: bool,
pub sort: bool,
}
#[derive(Clone)]
pub struct SpritesheetBuilder {
pub image: Option<Image>,
pub shaders: Shaders,
pub alpha_blending: AlphaBlending,
pub minification_smoothing: bool,
pub magnification_smoothing: bool,
pub wrap: (TextureWrapping, TextureWrapping),
pub srgb: bool,
}
impl Default for SpritesheetBuilder {
fn default() -> SpritesheetBuilder {
SpritesheetBuilder {
image: None,
shaders: Shaders::default(),
alpha_blending: AlphaBlending {
blend: true,
sort: true,
},
minification_smoothing: true,
magnification_smoothing: true,
wrap: (TextureWrapping::Clamp, TextureWrapping::Clamp),
srgb: true,
}
}
}
impl SpritesheetBuilder {
pub fn build(&self, ctx: &mut Context) -> Spritesheet {
Spritesheet {
handle: ctx.renderer.create_draw_call(
self.image.as_ref(),
&self.shaders,
self.alpha_blending,
self.minification_smoothing,
self.magnification_smoothing,
self.wrap,
self.srgb,
),
}
}
pub fn image(&mut self, image: Image) -> &mut SpritesheetBuilder {
self.image = Some(image);
self
}
pub fn shaders(&mut self, shaders: Shaders) -> &mut SpritesheetBuilder {
self.shaders = shaders;
self
}
pub fn alpha_blending(&mut self, blend: bool, sort: bool) -> &mut SpritesheetBuilder {
self.alpha_blending = AlphaBlending { blend, sort };
self
}
pub fn minification_smoothing(&mut self, smoothing: bool) -> &mut SpritesheetBuilder {
self.minification_smoothing = smoothing;
self
}
pub fn magnification_smoothing(&mut self, smoothing: bool) -> &mut SpritesheetBuilder {
self.magnification_smoothing = smoothing;
self
}
pub fn wrapping_behavior(
&mut self,
wrap_s: TextureWrapping,
wrap_t: TextureWrapping,
) -> &mut SpritesheetBuilder {
self.wrap = (wrap_s, wrap_t);
self
}
pub fn srgb(&mut self, srgb: bool) -> &mut SpritesheetBuilder {
self.srgb = srgb;
self
}
}