1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
use crate::*;

pub unsafe trait TexturePixel {
    const INTERNAL_FORMAT: raw::Enum;
    const FORMAT: raw::Enum;
    const TYPE: raw::Enum;
}

unsafe impl TexturePixel for Color<f32> {
    const INTERNAL_FORMAT: raw::Enum = raw::RGBA;
    const FORMAT: raw::Enum = raw::RGBA;
    const TYPE: raw::Enum = raw::UNSIGNED_BYTE;
}

unsafe impl TexturePixel for u8 {
    #[cfg(target_arch = "wasm32")]
    const INTERNAL_FORMAT: raw::Enum = raw::ALPHA;
    #[cfg(not(target_arch = "wasm32"))]
    const INTERNAL_FORMAT: raw::Enum = raw::RGBA;
    const FORMAT: raw::Enum = raw::ALPHA;
    const TYPE: raw::Enum = raw::UNSIGNED_BYTE;
}

#[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)]
pub enum WrapMode {
    Repeat = raw::REPEAT as _,
    Clamp = raw::CLAMP_TO_EDGE as _,
}

#[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)]
pub enum Filter {
    Nearest = raw::NEAREST as _,
    Linear = raw::LINEAR as _,
}

pub struct Texture2d<P: TexturePixel> {
    pub(crate) ugli: Rc<Ugli>,
    pub(crate) handle: raw::Texture,
    size: Cell<Vec2<usize>>,
    phantom_data: PhantomData<*mut P>,
}

impl<P: TexturePixel> Drop for Texture2d<P> {
    fn drop(&mut self) {
        let gl = &self.ugli.inner;
        gl.delete_texture(&self.handle);
    }
}

pub type Texture = Texture2d<Color<f32>>;

impl<P: TexturePixel> Texture2d<P> {
    fn new_raw(ugli: &Rc<Ugli>, size: Vec2<usize>) -> Self {
        let gl = &ugli.inner;
        let handle = gl.create_texture().unwrap();
        gl.bind_texture(raw::TEXTURE_2D, &handle);
        gl.tex_parameteri(
            raw::TEXTURE_2D,
            raw::TEXTURE_MIN_FILTER,
            raw::LINEAR as raw::Int,
        );
        let mut texture = Self {
            ugli: ugli.clone(),
            handle,
            size: Cell::new(size),
            phantom_data: PhantomData,
        };
        texture.set_filter(Filter::Linear);
        texture.set_wrap_mode(WrapMode::Clamp);
        ugli.debug_check();
        texture
    }

    pub fn is_pot(&self) -> bool {
        let size = self.size.get();
        size.x & (size.x - 1) == 0 && size.y & (size.y - 1) == 0
    }

    pub fn new_uninitialized(ugli: &Rc<Ugli>, size: Vec2<usize>) -> Self {
        let texture = Self::new_raw(ugli, size);
        let gl = &ugli.inner;
        gl.tex_image_2d::<u8>(
            raw::TEXTURE_2D,
            0,
            P::INTERNAL_FORMAT as raw::Int,
            size.x as raw::SizeI,
            size.y as raw::SizeI,
            0,
            P::FORMAT,
            P::TYPE,
            None,
        );
        ugli.debug_check();
        texture
    }
    pub fn set_wrap_mode(&mut self, wrap_mode: WrapMode) {
        assert!(self.is_pot() || wrap_mode == WrapMode::Clamp);
        let gl = &self.ugli.inner;
        gl.bind_texture(raw::TEXTURE_2D, &self.handle);
        gl.tex_parameteri(raw::TEXTURE_2D, raw::TEXTURE_WRAP_S, wrap_mode as raw::Int);
        gl.tex_parameteri(raw::TEXTURE_2D, raw::TEXTURE_WRAP_T, wrap_mode as raw::Int);
        self.ugli.debug_check();
    }

    pub fn set_filter(&mut self, filter: Filter) {
        assert!(self.is_pot() || filter == Filter::Nearest || filter == Filter::Linear);
        let gl = &self.ugli.inner;
        gl.bind_texture(raw::TEXTURE_2D, &self.handle);
        gl.tex_parameteri(raw::TEXTURE_2D, raw::TEXTURE_MAG_FILTER, filter as raw::Int);
        self.ugli.debug_check();
    }

    pub fn size(&self) -> Vec2<usize> {
        self.size.get()
    }

    #[doc(hidden)]
    pub fn _set_size(&self, size: Vec2<usize>) {
        self.size.set(size);
    }

    #[doc(hidden)]
    pub fn _get_handle(&self) -> &raw::Texture {
        &self.handle
    }

    // TODO: use like Matrix<Color>?
    pub unsafe fn sub_image(&mut self, pos: Vec2<usize>, size: Vec2<usize>, data: &[u8]) {
        assert_eq!(
            size.x
                * size.y
                * match P::FORMAT {
                    raw::RGBA => 4,
                    raw::ALPHA => 1,
                    _ => unreachable!(),
                },
            data.len()
        );
        let gl = &self.ugli.inner;
        gl.bind_texture(raw::TEXTURE_2D, &self.handle);
        gl.tex_sub_image_2d(
            raw::TEXTURE_2D,
            0,
            pos.x as raw::Int,
            pos.y as raw::Int,
            size.x as raw::SizeI,
            size.y as raw::SizeI,
            P::FORMAT,
            P::TYPE,
            data,
        );
        self.ugli.debug_check();
    }
}

impl Texture {
    pub fn gen_mipmaps(&mut self) {
        assert!(self.is_pot());
        let gl = &self.ugli.inner;
        gl.bind_texture(raw::TEXTURE_2D, &self.handle);
        gl.generate_mipmap(raw::TEXTURE_2D);
        gl.tex_parameteri(
            raw::TEXTURE_2D,
            raw::TEXTURE_MIN_FILTER,
            raw::LINEAR_MIPMAP_LINEAR as raw::Int,
        );
        self.ugli.debug_check();
    }

    pub fn new_with<F: FnMut(Vec2<usize>) -> Color<f32>>(
        ugli: &Rc<Ugli>,
        size: Vec2<usize>,
        mut f: F,
    ) -> Self {
        let texture = Texture2d::new_raw(ugli, size);
        let mut data: Vec<u8> = Vec::with_capacity(size.x * size.y * 4);
        for y in 0..size.y {
            for x in 0..size.x {
                let color = f(vec2(x, y));
                data.push((color.r * 255.0) as u8);
                data.push((color.g * 255.0) as u8);
                data.push((color.b * 255.0) as u8);
                data.push((color.a * 255.0) as u8);
            }
        }
        let gl = &ugli.inner;
        gl.tex_image_2d(
            raw::TEXTURE_2D,
            0,
            raw::RGBA as raw::Int,
            size.x as raw::SizeI,
            size.y as raw::SizeI,
            0,
            raw::RGBA as raw::Enum,
            raw::UNSIGNED_BYTE,
            Some(&data),
        );
        ugli.debug_check();
        texture
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub fn from_image(ugli: &Rc<Ugli>, image: image::RgbaImage) -> Self {
        let size = vec2(image.width() as usize, image.height() as usize);
        let mut texture = Texture2d::new_raw(ugli, size);
        let gl = &ugli.inner;
        gl.tex_image_2d(
            raw::TEXTURE_2D,
            0,
            raw::RGBA as raw::Int,
            size.x as raw::SizeI,
            size.y as raw::SizeI,
            0,
            raw::RGBA as raw::Enum,
            raw::UNSIGNED_BYTE,
            Some(&image.into_raw()),
        );
        if texture.is_pot() {
            texture.gen_mipmaps();
        }
        ugli.debug_check();
        texture
    }

    #[cfg(target_arch = "wasm32")]
    pub fn from_image(ugli: &Rc<Ugli>, image: &web_sys::HtmlImageElement) -> Self {
        let mut texture =
            Texture2d::new_raw(ugli, vec2(image.width() as usize, image.height() as usize));
        let gl = &ugli.inner;
        gl.tex_image_2d_image(
            raw::TEXTURE_2D,
            0,
            raw::RGBA as raw::Int,
            raw::RGBA,
            raw::UNSIGNED_BYTE,
            image,
        );
        if texture.is_pot() {
            texture.gen_mipmaps();
        }
        ugli.debug_check();
        texture
    }
}