use std::path::Path;
use glium::{
Display,
texture::{
RawImage2d,
TextureCreationError,
srgb_texture2d::SrgbTexture2d
},
};
use image::{RgbaImage,DynamicImage};
use image::error::ImageError;
pub enum TextureCreationResult{
Ok(Texture),
TextureCreationError(TextureCreationError),
ImageCreationError(ImageError)
}
impl TextureCreationResult{
pub fn unwrap(self)->Texture{
match self{
TextureCreationResult::Ok(texture)=>texture,
TextureCreationResult::TextureCreationError(e)=>panic!(e),
TextureCreationResult::ImageCreationError(e)=>panic!(e),
}
}
pub fn expect(self,msg:&str)->Texture{
match self{
TextureCreationResult::Ok(texture)=>texture,
TextureCreationResult::TextureCreationError(e)=>panic!("{} {:?}",msg,e),
TextureCreationResult::ImageCreationError(e)=>panic!("{} {:?}",msg,e),
}
}
}
pub struct Texture(pub SrgbTexture2d);
impl Texture{
pub fn create(memory:&[u8],size:[u32;2],factory:&Display)->TextureCreationResult{
let image=RawImage2d::from_raw_rgba_reversed(memory,(size[0],size[1]));
match SrgbTexture2d::new(factory,image){
Ok(texture)=>TextureCreationResult::Ok(Texture(texture)),
Err(e)=>TextureCreationResult::TextureCreationError(e),
}
}
pub fn empty(size:[u32;2],factory:&Display)->TextureCreationResult{
match SrgbTexture2d::empty(factory,size[0],size[1]){
Ok(texture)=>TextureCreationResult::Ok(Texture(texture)),
Err(e)=>TextureCreationResult::TextureCreationError(e),
}
}
pub fn from_path<P:AsRef<Path>>(path:P,factory:&Display)->TextureCreationResult{
match image::open(path){
Ok(image)=>{
let image=match image{
DynamicImage::ImageRgba8(img)=>img,
img=>img.to_rgba8(),
};
Texture::from_image(&image,factory)
},
Err(e)=>TextureCreationResult::ImageCreationError(e)
}
}
pub fn from_image(img:&RgbaImage,factory:&Display)->TextureCreationResult{
let (width,height)=img.dimensions();
Texture::create(img,[width,height],factory)
}
pub fn update(&mut self,img:&RgbaImage){
let (width,height)=img.dimensions();
self.0.write(glium::Rect{
left:0u32,
bottom:0u32,
width:width,
height:height,
},
RawImage2d::from_raw_rgba_reversed(img,(width,height)),
)
}
pub fn width(&self)->u32{
self.0.width()
}
pub fn height(&self)->u32{
self.0.height()
}
pub fn dimensions(&self)->(u32,u32){
self.0.dimensions()
}
}