PistonDevelopers / texture

A library for texture conventions
MIT License
7 stars 4 forks source link

Use of current objects #15

Closed bvssvni closed 10 years ago

bvssvni commented 10 years ago

With piston-current, it is possible to set Gfx device as current object. This means we can define texture traits like this:

pub trait FromMemoryAlpha {
    fn from_memory_alpha(
        buffer: &[u8], width: u32, height: u32
    ) -> Result<Self, Error>;
}

Can also use the new error convention https://github.com/PistonDevelopers/piston/issues/699

bvssvni commented 10 years ago

This requires adding a generic parameter on Texture to look up the current device.

bvssvni commented 10 years ago

Alternative is to add a TextureFactory<T> type that creates textures of type T.

pub struct TextureFactory<T> {
    pub from_memory_alpha: Option<fn (&[u8], u32, u32) -> Result<T, Error>>,
}

pub fn from_memory_alpha<T>(buffer: &[u8], width: u32, height: u32) -> Result<T, Error> {
    match Current<TextureFactory<T>>.current() {
        None => Error(error::CurrentTextureFactoryNotSet),
        Some(factory) => {
            match factory.from_memory_alpha {
                None => Err(error::MethodNotSupportedByCurrentTextureFactory),
                Some(f) => Ok((f)(buffer, width, height))
            }
        }
    }
}
bvssvni commented 10 years ago

This means for every texture type, there should be a current texture factory, such that knowing the type of the texture is enough to create the texture.

It is possible to override how textures are created by setting a new texture factory as current.

bvssvni commented 10 years ago

A texture back-end can implement the FromMemoryAlpha trait that uses the current texture factory.

bvssvni commented 10 years ago

Error could take a type parameter Error<T> where T is the texture type, which will make it possible to convert the type into a message.

bvssvni commented 10 years ago

Alternative, we could just drop the texture traits and use from_memory_alpha: fn (&[u8], u32, u32) -> T whenever we need it.

bvssvni commented 10 years ago

We'll not use traits but rely on patterns like current objects where this is needed.