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
use std::cell::RefCell;
use std::rc::Rc;

use image::RgbaImage;
use rootvg_core::math::PhysicalSizeU32;

#[derive(Debug)]
enum TextureSource {
    Image {
        data_to_upload: Option<RgbaImage>,
        uploaded_texture: Option<wgpu::Texture>,
    },
    Prepass {
        view: wgpu::TextureView,
    },
}

#[derive(Debug)]
pub(crate) struct TextureInner {
    source: TextureSource,
    pub(crate) bind_group: Option<wgpu::BindGroup>,
}

/// A source of raw image data.
///
/// Once this texture has been uploaded to the GPU, the image
/// data will be automatically removed from RAM.
#[derive(Debug)]
pub struct RcTexture {
    pub(crate) inner: Rc<RefCell<TextureInner>>,
    size: PhysicalSizeU32,
}

impl RcTexture {
    pub fn new(image: impl Into<RgbaImage>) -> Self {
        let image: RgbaImage = image.into();

        let dimensions = image.dimensions();

        Self {
            inner: Rc::new(RefCell::new(TextureInner {
                source: TextureSource::Image {
                    data_to_upload: Some(image),
                    uploaded_texture: None,
                },
                bind_group: None,
            })),
            size: PhysicalSizeU32::new(dimensions.0, dimensions.1),
        }
    }

    pub fn from_prepass_texture(texture_view: wgpu::TextureView, size: PhysicalSizeU32) -> Self {
        Self {
            inner: Rc::new(RefCell::new(TextureInner {
                source: TextureSource::Prepass { view: texture_view },
                bind_group: None,
            })),
            size,
        }
    }

    // TODO: Custom error
    pub fn replace_with_image(&mut self, image: impl Into<RgbaImage>) -> Result<(), ()> {
        let image: RgbaImage = image.into();
        let dimensions = image.dimensions();
        let size = PhysicalSizeU32::new(dimensions.0, dimensions.1);

        if size != self.size {
            return Err(());
        }

        let mut inner = RefCell::borrow_mut(&self.inner);

        let TextureSource::Image { data_to_upload, .. } = &mut inner.source else {
            return Err(());
        };

        *data_to_upload = Some(image);

        Ok(())
    }

    // TODO: Custom error
    pub fn replace_prepass_texture(
        &mut self,
        texture_view: wgpu::TextureView,
        size: PhysicalSizeU32,
    ) -> Result<(), ()> {
        if self.size != size {
            return Err(());
        }

        let mut inner = RefCell::borrow_mut(&self.inner);

        let TextureSource::Prepass { view } = &mut inner.source else {
            return Err(());
        };

        *view = texture_view;

        inner.bind_group = None;

        Ok(())
    }

    pub fn size(&self) -> PhysicalSizeU32 {
        self.size
    }

    pub(crate) fn upload_if_needed(
        &self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        texture_bind_group_layout: &wgpu::BindGroupLayout,
    ) {
        let mut inner = RefCell::borrow_mut(&self.inner);

        let TextureInner { source, bind_group } = &mut *inner;

        match source {
            TextureSource::Image {
                data_to_upload,
                uploaded_texture,
            } => {
                let Some(data_to_upload) = data_to_upload.take() else {
                    return;
                };

                if bind_group.is_none() {
                    let dimensions = data_to_upload.dimensions();
                    let texture_size = wgpu::Extent3d {
                        width: dimensions.0,
                        height: dimensions.1,
                        depth_or_array_layers: 1,
                    };

                    let texture = device.create_texture(&wgpu::TextureDescriptor {
                        // All textures are stored as 3D, we represent our 2D texture
                        // by setting depth to 1.
                        size: texture_size,
                        mip_level_count: 1,
                        sample_count: 1,
                        dimension: wgpu::TextureDimension::D2,
                        format: wgpu::TextureFormat::Rgba8UnormSrgb,
                        // TEXTURE_BINDING tells wgpu that we want to use this texture in shaders
                        // COPY_DST means that we want to copy data to this texture
                        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                        label: None,
                        view_formats: &[],
                    });

                    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());

                    let new_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
                        layout: &texture_bind_group_layout,
                        entries: &[wgpu::BindGroupEntry {
                            binding: 0,
                            resource: wgpu::BindingResource::TextureView(&view),
                        }],
                        label: None,
                    });

                    *bind_group = Some(new_bind_group);

                    *uploaded_texture = Some(texture);
                };

                let uploaded_texture = uploaded_texture.as_ref().unwrap();

                let texture_size = wgpu::Extent3d {
                    width: self.size.width,
                    height: self.size.height,
                    depth_or_array_layers: 1,
                };

                queue.write_texture(
                    wgpu::ImageCopyTexture {
                        texture: uploaded_texture,
                        mip_level: 0,
                        origin: wgpu::Origin3d::ZERO,
                        aspect: wgpu::TextureAspect::All,
                    },
                    &data_to_upload,
                    // The layout of the texture
                    wgpu::ImageDataLayout {
                        offset: 0,
                        bytes_per_row: Some(4 * self.size.width),
                        rows_per_image: Some(self.size.height),
                    },
                    texture_size,
                );
            }
            TextureSource::Prepass { view } => {
                if bind_group.is_some() {
                    return;
                }

                let new_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
                    layout: &texture_bind_group_layout,
                    entries: &[wgpu::BindGroupEntry {
                        binding: 0,
                        resource: wgpu::BindingResource::TextureView(view),
                    }],
                    label: None,
                });

                *bind_group = Some(new_bind_group);
            }
        }
    }
}

impl Clone for RcTexture {
    fn clone(&self) -> Self {
        Self {
            inner: Rc::clone(&self.inner),
            size: self.size,
        }
    }
}

impl PartialEq for RcTexture {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.inner, &other.inner)
    }
}

impl From<RgbaImage> for RcTexture {
    fn from(image: RgbaImage) -> Self {
        RcTexture::new(image)
    }
}