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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
use rustc_hash::FxHashMap;
use smallvec::SmallVec;
use std::{cell::RefCell, ops::Range, rc::Rc};

use rootvg_core::{
    buffer::Buffer,
    math::{PhysicalSizeI32, ScaleFactor},
    pipeline::DefaultConstantUniforms,
};

use crate::{
    primitive::{ImagePrimitive, ImageVertex},
    texture::TextureInner,
    RcTexture,
};

const INITIAL_INSTANCES: usize = 16;
const INITIAL_SUB_BATCHES: usize = 16;

struct Batch {
    range_in_buffer: Range<u32>,
    texture: RcTexture,
}

pub struct ImageBatchBuffer {
    buffer: Buffer<ImageVertex>,
    sub_batches: Vec<Batch>,
    num_instances: usize,

    prev_primitives: Vec<ImagePrimitive>,
}

impl ImageBatchBuffer {
    fn new(device: &wgpu::Device) -> Self {
        Self {
            buffer: Buffer::new(
                device,
                "rootvg-image instance buffer",
                INITIAL_INSTANCES,
                wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            ),
            sub_batches: Vec::with_capacity(INITIAL_SUB_BATCHES),
            num_instances: 0,
            prev_primitives: Vec::new(),
        }
    }

    fn prepare(
        &mut self,
        primitives: &[ImagePrimitive],
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        texture_bind_group_layout: &wgpu::BindGroupLayout,
    ) {
        // Don't prepare if primitives have not changed since the last
        // prepare.
        if primitives == &self.prev_primitives {
            return;
        }
        self.prev_primitives = primitives.into();

        self.sub_batches.clear();
        self.num_instances = primitives.len();

        self.buffer.expand_to_fit_new_size(device, primitives.len());

        struct TempSubBatchEntry {
            vertices: SmallVec<[ImageVertex; INITIAL_INSTANCES]>,
            texture: RcTexture,
        }

        // TODO: reuse the allocation of this hash map?
        let mut sub_batches_map: FxHashMap<*const RefCell<TextureInner>, TempSubBatchEntry> =
            FxHashMap::default();
        sub_batches_map.reserve(INITIAL_SUB_BATCHES);

        for image in primitives.iter() {
            image
                .texture
                .upload_if_needed(device, queue, texture_bind_group_layout);

            let sub_batch = sub_batches_map
                .entry(Rc::as_ptr(&image.texture.inner))
                .or_insert_with(|| TempSubBatchEntry {
                    vertices: SmallVec::new(),
                    texture: image.texture.clone(),
                });

            sub_batch.vertices.push(image.vertex);
        }

        let mut range_start = 0;
        for sub_batch in sub_batches_map.values() {
            self.buffer.write(queue, range_start, &sub_batch.vertices);

            self.sub_batches.push(Batch {
                range_in_buffer: range_start as u32
                    ..(range_start + sub_batch.vertices.len()) as u32,
                texture: sub_batch.texture.clone(),
            });

            range_start += sub_batch.vertices.len();
        }
    }
}

pub struct ImagePipeline {
    pipeline: wgpu::RenderPipeline,

    constants_buffer: wgpu::Buffer,
    constants_bind_group: wgpu::BindGroup,
    texture_layout: wgpu::BindGroupLayout,

    screen_size: PhysicalSizeI32,
    scale_factor: ScaleFactor,
}

impl ImagePipeline {
    pub fn new(
        device: &wgpu::Device,
        format: wgpu::TextureFormat,
        multisample: wgpu::MultisampleState,
    ) -> Self {
        let constants_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("rootvg-image constants layout"),
            entries: &[
                DefaultConstantUniforms::entry(0),
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    // This should match the filterable field of the
                    // Texture entry.
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });

        let constants_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("rootvg-image constants buffer"),
            size: std::mem::size_of::<Self>() as wgpu::BufferAddress,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::FilterMode::Nearest,
            ..Default::default()
        });

        let constants_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("rootvg-image constants bind group"),
            layout: &constants_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: constants_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&sampler),
                },
            ],
        });

        let texture_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("rootvg-image texture layout"),
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::FRAGMENT,
                ty: wgpu::BindingType::Texture {
                    multisampled: false,
                    view_dimension: wgpu::TextureViewDimension::D2,
                    sample_type: wgpu::TextureSampleType::Float { filterable: true },
                },
                count: None,
            }],
        });

        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("rootvg-image pipeline layout"),
            push_constant_ranges: &[],
            bind_group_layouts: &[&constants_layout, &texture_layout],
        });

        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("rootvg-image shader"),
            source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(concat!(include_str!(
                "shader/image.wgsl"
            ),))),
        });

        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("rootvg-image pipeline"),
            layout: Some(&layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: "vs_main",
                buffers: &[wgpu::VertexBufferLayout {
                    array_stride: std::mem::size_of::<ImageVertex>() as u64,
                    step_mode: wgpu::VertexStepMode::Instance,
                    attributes: &wgpu::vertex_attr_array!(
                        // Position
                        0 => Float32x2,
                        // Size
                        1 => Float32x2,
                        // Normalized UV position
                        2 => Float32x2,
                        // Normalized UV size
                        3 => Float32x2,
                        // Transform Matrix 3x2
                        4 => Float32x2,
                        5 => Float32x2,
                        6 => Float32x2,
                        // Has Transformation
                        7 => Uint32,
                    ),
                }],
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: "fs_main",
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    blend: Some(wgpu::BlendState {
                        color: wgpu::BlendComponent {
                            src_factor: wgpu::BlendFactor::SrcAlpha,
                            dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                            operation: wgpu::BlendOperation::Add,
                        },
                        alpha: wgpu::BlendComponent {
                            src_factor: wgpu::BlendFactor::One,
                            dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                            operation: wgpu::BlendOperation::Add,
                        },
                    }),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                front_face: wgpu::FrontFace::Cw,
                ..Default::default()
            },
            depth_stencil: None,
            multisample,
            multiview: None,
        });

        Self {
            pipeline,
            constants_buffer,
            constants_bind_group,
            texture_layout,
            screen_size: PhysicalSizeI32::default(),
            scale_factor: ScaleFactor::default(),
        }
    }

    pub fn create_batch(&mut self, device: &wgpu::Device) -> ImageBatchBuffer {
        ImageBatchBuffer::new(device)
    }

    pub fn start_preparations(
        &mut self,
        _device: &wgpu::Device,
        queue: &wgpu::Queue,
        screen_size: PhysicalSizeI32,
        scale_factor: ScaleFactor,
    ) {
        if self.screen_size == screen_size && self.scale_factor == scale_factor {
            return;
        }

        self.screen_size = screen_size;
        self.scale_factor = scale_factor;

        DefaultConstantUniforms::prepare_buffer(
            &self.constants_buffer,
            screen_size,
            scale_factor,
            queue,
        );
    }

    pub fn prepare_batch(
        &mut self,
        batch: &mut ImageBatchBuffer,
        primitives: &[ImagePrimitive],
        device: &wgpu::Device,
        queue: &wgpu::Queue,
    ) {
        batch.prepare(primitives, device, queue, &self.texture_layout);
    }

    pub fn render_batch<'pass>(
        &'pass self,
        batch: &'pass ImageBatchBuffer,
        render_pass: &mut wgpu::RenderPass<'pass>,
    ) {
        if batch.num_instances == 0 {
            return;
        }

        render_pass.set_pipeline(&self.pipeline);
        render_pass.set_bind_group(0, &self.constants_bind_group, &[]);

        render_pass.set_vertex_buffer(0, batch.buffer.slice(0..batch.num_instances));

        for sub_batch in batch.sub_batches.iter() {
            // # SAFETY:
            //
            // Because wgpu requires the bind group to be borrowed for `'pass`, we
            // are not able to use the safe option that returns a `std::cell::Ref`.
            //
            // By design, data is only mutated during the prepare stage, not during
            // the render pass stage. So there is no chance for the
            // `RefCell<TextureInner>` to be borrowed mutably during the render
            // pass.
            let texture_bind_group = unsafe {
                &RefCell::try_borrow_unguarded(&sub_batch.texture.inner)
                    .unwrap()
                    .bind_group
                    .as_ref()
                    .unwrap()
            };

            render_pass.set_bind_group(1, texture_bind_group, &[]);

            render_pass.draw(0..6, sub_batch.range_in_buffer.clone());
        }
    }
}