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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
use std::borrow::Borrow;
use std::marker;
use std::mem;

use wasm_bindgen::JsCast;
use web_sys::{window, CanvasRenderingContext2d, HtmlCanvasElement, HtmlImageElement};

/// Encapsulates data that may be uploaded to a 2D texture (sub-)image.
///
/// # Example
///
/// ```rust
/// # use web_glitz::runtime::RenderingContext;
/// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext + Clone + 'static {
/// use web_glitz::image::{Image2DSource, MipmapLevels};
/// use web_glitz::image::format::RGB8;
/// use web_glitz::image::texture_2d::Texture2DDescriptor;
///
/// let texture = context.try_create_texture_2d(&Texture2DDescriptor {
///     format: RGB8,
///     width: 256,
///     height: 256,
///     levels: MipmapLevels::Complete
/// }).unwrap();
///
/// let data: Vec<[u8; 3]> = vec![[255, 0, 0]; 256 * 256];
/// let image_source = Image2DSource::from_pixels(data, 256, 256).unwrap();
///
/// context.submit(texture.base_level().upload_command(image_source));
/// # }
/// ```
///
/// Note that the pixel data type (`[u8; 3]` in the example) must implement [ClientFormat] for the
/// texture's [InternalFormat] (in this case that means `ClientFormat<RGB8>` must be implemented
/// for `[u8; 3]`, which it is).
pub struct Image2DSource<D, T> {
    pub(crate) internal: Image2DSourceInternal<D>,
    _marker: marker::PhantomData<[T]>,
}

pub(crate) enum Image2DSourceInternal<D> {
    PixelData {
        data: D,
        row_length: u32,
        image_height: u32,
        alignment: Alignment,
    },
}

impl<D, T> Image2DSource<D, T>
where
    D: Borrow<[T]>,
{
    /// Creates a new [Image2DSource] from the `pixels` for an image with the given `width` and the
    /// given `height`.
    ///
    /// Returns [FromPixelsError::NotEnoughPixels] if the `pixels` does not contain enough data for
    /// at least `width * height` pixels.
    ///
    /// # Example
    ///
    /// ```rust
    /// use web_glitz::image::Image2DSource;
    ///
    /// let data: Vec<[u8; 3]> = vec![[255, 0, 0]; 256 * 256];
    /// let image_source = Image2DSource::from_pixels(data, 256, 256).unwrap();
    /// ```
    pub fn from_pixels(pixels: D, width: u32, height: u32) -> Result<Self, FromPixelsError> {
        let len = pixels.borrow().len();
        let expected_len = width * height;

        if len < expected_len as usize {
            return Err(FromPixelsError::NotEnoughPixels(len, expected_len));
        }

        let alignment = match mem::align_of::<T>() {
            1 => Alignment::Byte,
            2 => Alignment::Byte2,
            4 => Alignment::Byte4,
            8 => Alignment::Byte8,
            a => return Err(FromPixelsError::UnsupportedAlignment(a)),
        };

        Ok(Image2DSource {
            internal: Image2DSourceInternal::PixelData {
                data: pixels,
                row_length: width,
                image_height: height,
                alignment,
            },
            _marker: marker::PhantomData,
        })
    }
}

impl Image2DSource<Vec<[u8; 4]>, [u8; 4]> {
    /// Creates a new [Image2DSource] for the `image_element`.
    ///
    /// The width will be equal to the [HtmlImageElement::natural_width] of the image element and
    /// the height will be equal the [HtmlImageElement::natural_height] of the image element.
    ///
    /// # Panics
    ///
    /// Panics if the image element is not yet "complete" (see [HtmlImageElement::complete]).
    pub fn from_image_element(image_element: &HtmlImageElement) -> Self {
        // Current implementation is very conservative and wasteful, copying the image data into a
        // new vector. WebGL support initializing textures from image elements directly which would
        // avoid the copy and may even avoid an upload as the browser may have already uploaded the
        // pixel data previously. However, it is currently unclear to me how sending
        // HtmlImageElements to secondary workers/threads would work.

        if !image_element.complete() {
            panic!("Incomplete image.");
        }

        let document = window().unwrap().document().unwrap();

        let width = image_element.natural_width();
        let height = image_element.natural_height();

        let canvas = document
            .create_element("canvas")
            .unwrap()
            .dyn_into::<HtmlCanvasElement>()
            .unwrap();

        canvas.set_width(width);
        canvas.set_height(height);

        let context = canvas
            .get_context("2d")
            .unwrap()
            .unwrap()
            .dyn_into::<CanvasRenderingContext2d>()
            .unwrap();

        context
            .draw_image_with_html_image_element(&image_element, 0.0, 0.0)
            .unwrap();

        let mut image_data = context
            .get_image_data(0.0, 0.0, width as f64, height as f64)
            .unwrap()
            .data();

        let len = image_data.len();
        let capacity = image_data.capacity();
        let ptr = image_data.as_mut_ptr();

        mem::forget(image_data);

        let pixels = unsafe { Vec::from_raw_parts(mem::transmute(ptr), len / 4, capacity / 4) };

        Image2DSource {
            internal: Image2DSourceInternal::PixelData {
                data: pixels,
                row_length: width,
                image_height: height,
                alignment: Alignment::Byte4,
            },
            _marker: marker::PhantomData,
        }
    }
}

/// Encapsulates data that may be uploaded to a layered texture (sub-)image.
///
/// # Example
///
/// ```rust
/// # use web_glitz::runtime::RenderingContext;
/// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext + Clone + 'static {
/// use web_glitz::image::{LayeredImageSource, MipmapLevels};
/// use web_glitz::image::format::RGB8;
/// use web_glitz::image::texture_3d::Texture3DDescriptor;
///
/// let texture = context.try_create_texture_3d(&Texture3DDescriptor {
///     format: RGB8,
///     width: 256,
///     height: 256,
///     depth: 256,
///     levels: MipmapLevels::Complete
/// }).unwrap();
///
/// let data: Vec<[u8; 3]> = vec![[255, 0, 0]; 256 * 256 * 256];
/// let image_source = LayeredImageSource::from_pixels(data, 256, 256, 256).unwrap();
///
/// context.submit(texture.base_level().upload_command(image_source));
/// # }
/// ```
///
/// Note that the pixel data type (`[u8; 3]` in the example) must implement [ClientFormat] for the
/// texture's [InternalFormat] (in this case that means `ClientFormat<RGB8>` must be implemented
/// for `[u8; 3]`, which it is).
pub struct LayeredImageSource<D, T> {
    pub(crate) internal: LayeredImageSourceInternal<D>,
    _marker: marker::PhantomData<[T]>,
}

pub(crate) enum LayeredImageSourceInternal<D> {
    PixelData {
        data: D,
        row_length: u32,
        image_height: u32,
        image_count: u32,
        alignment: Alignment,
    },
}

impl<D, T> LayeredImageSource<D, T>
where
    D: Borrow<[T]>,
{
    /// Creates a new [LayeredImageSource] from the `pixels` for an image with the given `width`,
    /// the given `height` and the given `depth`.
    ///
    /// In this context the `depth` of the image corresponds to its number of layers.
    ///
    /// Returns [FromPixelsError::NotEnoughPixels] if the `pixels` does not contain enough data for
    /// at least `width * height * depth` pixels.
    ///
    /// # Example
    ///
    /// ```rust
    /// use web_glitz::image::LayeredImageSource;
    ///
    /// let data: Vec<[u8; 3]> = vec![[255, 0, 0]; 256 * 256 * 256];
    /// let image_source = LayeredImageSource::from_pixels(data, 256, 256, 256).unwrap();
    /// ```
    pub fn from_pixels(
        pixels: D,
        width: u32,
        height: u32,
        depth: u32,
    ) -> Result<Self, FromPixelsError> {
        let len = pixels.borrow().len();
        let expected_len = width * height * depth;

        if len < expected_len as usize {
            return Err(FromPixelsError::NotEnoughPixels(len, expected_len));
        }

        let alignment = match mem::align_of::<T>() {
            1 => Alignment::Byte,
            2 => Alignment::Byte2,
            4 => Alignment::Byte4,
            8 => Alignment::Byte8,
            a => return Err(FromPixelsError::UnsupportedAlignment(a)),
        };

        Ok(LayeredImageSource {
            internal: LayeredImageSourceInternal::PixelData {
                data: pixels,
                row_length: width,
                image_height: height,
                image_count: depth,
                alignment,
            },
            _marker: marker::PhantomData,
        })
    }
}

/// Error returned by [Image2DSource::from_pixels] or [Image3DSource::from_pixels].
///
/// See [Image2DSource::from_pixels] and [Image3DSource::from_pixels] for details.
#[derive(Debug)]
pub enum FromPixelsError {
    /// Variant returned when the data does not contain enough pixels to describe an image of the
    /// required dimensions.
    NotEnoughPixels(usize, u32),

    /// Variant returned when the pixel data type has an unsupported alignment.
    UnsupportedAlignment(usize),
}

#[derive(Clone, Copy, PartialEq, Debug)]
pub(crate) enum Alignment {
    Byte,
    Byte2,
    Byte4,
    Byte8,
}

impl Into<i32> for Alignment {
    fn into(self) -> i32 {
        match self {
            Alignment::Byte => 1,
            Alignment::Byte2 => 2,
            Alignment::Byte4 => 4,
            Alignment::Byte8 => 8,
        }
    }
}