Skip to main content

pointblitz_core/
renderer.rs

1//! The point pipeline: one draw per chunk, instanced quads, reversed-Z depth, no sorting
2//! (decisions 0006, 0007, 0013). Slot scenes (decision 0052) are one draw each, through the same
3//! shader and size/colour rules.
4
5use crate::camera::Camera;
6use crate::layers::math::fog_params;
7use crate::scene::Scene;
8use crate::slots::{SLOT_BYTES, SlotScene};
9use bytemuck::{Pod, Zeroable};
10
11/// Depth format used by every PointBlitz target.
12pub const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
13
14#[repr(C)]
15#[derive(Clone, Copy, Pod, Zeroable)]
16struct CameraUniform {
17    view_proj: [[f32; 4]; 4],
18    viewport_px: [f32; 2],
19    point_px: f32,
20    /// World diameter in metres; 0 keeps the fixed pixel size (SkyLens).
21    point_m: f32,
22    /// SkyLens fog: rgb in the target's space, a = 1 when on.
23    fog_color: [f32; 4],
24    /// x, y: fog scale and bias; z: focal length in pixels; w: unused.
25    params: [f32; 4],
26}
27
28/// Per-chunk uniform slot; dynamic offsets must be multiples of the device alignment.
29#[repr(C)]
30#[derive(Clone, Copy, Pod, Zeroable)]
31struct ChunkUniform {
32    offset: [f32; 4],
33    scale: [f32; 4],
34}
35
36pub struct Renderer {
37    /// Point pipelines for strides 12 and 8 (decision 0051) and slot scenes (stride 16, decision
38    /// 0052): opaque, then faded (SkyLens: per-scene alpha through the blend constant).
39    pipelines: [wgpu::RenderPipeline; 6],
40    camera_buf: wgpu::Buffer,
41    camera_bg: wgpu::BindGroup,
42    chunk_layout: wgpu::BindGroupLayout,
43    chunk_buf: wgpu::Buffer,
44    chunk_bg: wgpu::BindGroup,
45    chunk_capacity: usize,
46    chunk_stride: u64,
47    /// Point diameter in pixels (decision 0007: 2 px).
48    pub point_px: f32,
49    /// GPU timestamps for the next `render` calls' pass (decision 0049): begin at `index`, end at
50    /// `index + 1`. Needs `Features::TIMESTAMP_QUERY`.
51    timestamps: Option<(wgpu::QuerySet, u32)>,
52    /// World point diameter in metres (`PointSize::Metres`); 0 means `point_px` is used.
53    point_m: f32,
54    /// Per scene given to the last `prepare`/`render`: first chunk slot and chunks written.
55    prepared: Vec<(usize, usize)>,
56    /// Per slot scene given to the last `prepare_with_slots`: its uniform slot.
57    prepared_slots: Vec<usize>,
58}
59
60/// Index into `Renderer::pipelines`: stride 12, 8 or a slot scene, then faded.
61fn pipeline_index(kind: usize, faded: bool) -> usize {
62    kind + 3 * usize::from(faded)
63}
64
65impl Renderer {
66    pub fn new(device: &wgpu::Device, color_format: wgpu::TextureFormat) -> Self {
67        let source = format!(
68            "{}\n{}",
69            include_str!("color.wgsl"),
70            include_str!("points.wgsl")
71        );
72        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
73            label: Some("pointblitz points"),
74            source: wgpu::ShaderSource::Wgsl(source.into()),
75        });
76        let uniform_entry = |dynamic: bool| wgpu::BindGroupLayoutEntry {
77            binding: 0,
78            visibility: wgpu::ShaderStages::VERTEX,
79            ty: wgpu::BindingType::Buffer {
80                ty: wgpu::BufferBindingType::Uniform,
81                has_dynamic_offset: dynamic,
82                min_binding_size: None,
83            },
84            count: None,
85        };
86        let camera_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
87            label: Some("camera"),
88            entries: &[uniform_entry(false)],
89        });
90        let chunk_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
91            label: Some("chunk"),
92            entries: &[uniform_entry(true)],
93        });
94        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
95            label: Some("points"),
96            bind_group_layouts: &[Some(&camera_layout), Some(&chunk_layout)],
97            immediate_size: 0,
98        });
99        // Faded: out = src * a + dst * (1 - a) with `a` the pass's blend constant, so one pipeline
100        // serves every per-scene alpha without a buffer write between draws.
101        let faded = wgpu::BlendComponent {
102            src_factor: wgpu::BlendFactor::Constant,
103            dst_factor: wgpu::BlendFactor::OneMinusConstant,
104            operation: wgpu::BlendOperation::Add,
105        };
106        let faded = Some(wgpu::BlendState {
107            color: faded,
108            alpha: faded,
109        });
110        // One pipeline per point stride of chunk format v2 (decision 0051).
111        let attrs12 = wgpu::vertex_attr_array![0 => Uint16x4, 1 => Unorm8x4];
112        let attrs8 = wgpu::vertex_attr_array![0 => Uint16x4];
113        // Slot scenes: f32 position, then RGB + flags read as integers (bit 0: shown).
114        let attrs16 = wgpu::vertex_attr_array![0 => Float32x3, 1 => Uint8x4];
115        let pipeline = |stride: u64,
116                        entry: &str,
117                        attributes: &[wgpu::VertexAttribute],
118                        blend: Option<wgpu::BlendState>| {
119            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
120                label: Some("points"),
121                layout: Some(&layout),
122                vertex: wgpu::VertexState {
123                    module: &shader,
124                    entry_point: Some(entry),
125                    compilation_options: Default::default(),
126                    buffers: &[Some(wgpu::VertexBufferLayout {
127                        array_stride: stride,
128                        step_mode: wgpu::VertexStepMode::Instance,
129                        attributes,
130                    })],
131                },
132                primitive: wgpu::PrimitiveState {
133                    topology: wgpu::PrimitiveTopology::TriangleStrip,
134                    ..Default::default()
135                },
136                depth_stencil: Some(wgpu::DepthStencilState {
137                    format: DEPTH_FORMAT,
138                    depth_write_enabled: Some(true),
139                    // Reversed-Z: nearer is larger.
140                    depth_compare: Some(wgpu::CompareFunction::Greater),
141                    stencil: Default::default(),
142                    bias: Default::default(),
143                }),
144                multisample: Default::default(),
145                fragment: Some(wgpu::FragmentState {
146                    module: &shader,
147                    entry_point: Some("fs"),
148                    compilation_options: Default::default(),
149                    targets: &[Some(wgpu::ColorTargetState {
150                        format: color_format,
151                        blend,
152                        write_mask: wgpu::ColorWrites::ALL,
153                    })],
154                }),
155                multiview_mask: None,
156                cache: None,
157            })
158        };
159        let slot = SLOT_BYTES as u64;
160        let pipelines = [
161            pipeline(12, "vs12", &attrs12, None),
162            pipeline(8, "vs8", &attrs8, None),
163            pipeline(slot, "vs16", &attrs16, None),
164            pipeline(12, "vs12", &attrs12, faded),
165            pipeline(8, "vs8", &attrs8, faded),
166            pipeline(slot, "vs16", &attrs16, faded),
167        ];
168
169        let camera_buf = device.create_buffer(&wgpu::BufferDescriptor {
170            label: Some("camera"),
171            size: size_of::<CameraUniform>() as u64,
172            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
173            mapped_at_creation: false,
174        });
175        let camera_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
176            label: Some("camera"),
177            layout: &camera_layout,
178            entries: &[wgpu::BindGroupEntry {
179                binding: 0,
180                resource: camera_buf.as_entire_binding(),
181            }],
182        });
183        let align = u64::from(device.limits().min_uniform_buffer_offset_alignment);
184        let chunk_stride = (size_of::<ChunkUniform>() as u64).div_ceil(align) * align;
185        let (chunk_buf, chunk_bg) = Self::chunk_slots(device, &chunk_layout, chunk_stride, 64);
186
187        Self {
188            pipelines,
189            camera_buf,
190            camera_bg,
191            chunk_layout,
192            chunk_buf,
193            chunk_bg,
194            chunk_capacity: 64,
195            chunk_stride,
196            point_px: 2.0,
197            timestamps: None,
198            point_m: 0.0,
199            prepared: Vec::new(),
200            prepared_slots: Vec::new(),
201        }
202    }
203
204    fn chunk_slots(
205        device: &wgpu::Device,
206        layout: &wgpu::BindGroupLayout,
207        stride: u64,
208        capacity: usize,
209    ) -> (wgpu::Buffer, wgpu::BindGroup) {
210        let buf = device.create_buffer(&wgpu::BufferDescriptor {
211            label: Some("chunk offsets"),
212            size: stride * capacity as u64,
213            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
214            mapped_at_creation: false,
215        });
216        let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
217            label: Some("chunk offsets"),
218            layout,
219            entries: &[wgpu::BindGroupEntry {
220                binding: 0,
221                resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
222                    buffer: &buf,
223                    offset: 0,
224                    size: wgpu::BufferSize::new(size_of::<ChunkUniform>() as u64),
225                }),
226            }],
227        });
228        (buf, bg)
229    }
230
231    /// Makes the next `render` calls write the pass's GPU start and end time into `set` at `index` and
232    /// `index + 1` (decision 0049); `None` stops it. The caller resolves the set.
233    pub fn set_timestamp_writes(&mut self, writes: Option<(wgpu::QuerySet, u32)>) {
234        self.timestamps = writes;
235    }
236
237    /// Records one frame: clears colour to black and depth to 0, then draws every visible chunk.
238    #[allow(clippy::too_many_arguments)]
239    pub fn render(
240        &mut self,
241        device: &wgpu::Device,
242        queue: &wgpu::Queue,
243        encoder: &mut wgpu::CommandEncoder,
244        color: &wgpu::TextureView,
245        depth: &wgpu::TextureView,
246        size: [u32; 2],
247        camera: &Camera,
248        scene: &Scene,
249    ) {
250        self.render_with_slots(
251            device,
252            queue,
253            encoder,
254            color,
255            depth,
256            size,
257            camera,
258            &[scene],
259            &[],
260        );
261    }
262
263    /// Like `render`, for chunk scenes and slot scenes (decision 0052) in one pass.
264    #[allow(clippy::too_many_arguments)]
265    pub fn render_with_slots(
266        &mut self,
267        device: &wgpu::Device,
268        queue: &wgpu::Queue,
269        encoder: &mut wgpu::CommandEncoder,
270        color: &wgpu::TextureView,
271        depth: &wgpu::TextureView,
272        size: [u32; 2],
273        camera: &Camera,
274        scenes: &[&Scene],
275        slots: &[&SlotScene],
276    ) {
277        self.write_frame(device, queue, size, camera, scenes, slots, None);
278
279        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
280            label: Some("points"),
281            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
282                view: color,
283                depth_slice: None,
284                resolve_target: None,
285                ops: wgpu::Operations {
286                    load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
287                    store: wgpu::StoreOp::Store,
288                },
289            })],
290            depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
291                view: depth,
292                depth_ops: Some(wgpu::Operations {
293                    load: wgpu::LoadOp::Clear(0.0),
294                    store: wgpu::StoreOp::Discard,
295                }),
296                stencil_ops: None,
297            }),
298            timestamp_writes: self.timestamps.as_ref().map(|(set, index)| {
299                wgpu::RenderPassTimestampWrites {
300                    query_set: set,
301                    beginning_of_pass_write_index: Some(*index),
302                    end_of_pass_write_index: Some(*index + 1),
303                }
304            }),
305            ..Default::default()
306        });
307        self.draw(&mut pass, scenes, None);
308        self.draw_slots(&mut pass, slots, None);
309    }
310
311    /// Writes the camera uniform and one chunk slot per visible chunk of every scene, scenes in
312    /// order, then one per slot scene, and remembers each scene's slots for `draw` / `draw_slots`.
313    #[allow(clippy::too_many_arguments)]
314    fn write_frame(
315        &mut self,
316        device: &wgpu::Device,
317        queue: &wgpu::Queue,
318        size: [u32; 2],
319        camera: &Camera,
320        scenes: &[&Scene],
321        slot_scenes: &[&SlotScene],
322        fog: Option<crate::layers::Fog>,
323    ) {
324        let (w, h) = (size[0].max(1), size[1].max(1));
325        let aspect = f64::from(w) / f64::from(h);
326        let f = fog_params(fog);
327        let cam = CameraUniform {
328            view_proj: camera.view_proj(aspect).to_cols_array_2d(),
329            viewport_px: [w as f32, h as f32],
330            point_px: self.point_px,
331            point_m: self.point_m,
332            fog_color: f.color,
333            params: [f.scale, f.bias, focal_px(camera.fov_y_deg, h) as f32, 0.0],
334        };
335        queue.write_buffer(&self.camera_buf, 0, bytemuck::bytes_of(&cam));
336
337        let counts: Vec<usize> = scenes.iter().map(|s| s.visible_chunks().len()).collect();
338        self.prepared = slot_ranges(&counts);
339        let chunks_total: usize = counts.iter().sum();
340        self.prepared_slots = (chunks_total..chunks_total + slot_scenes.len()).collect();
341        let total = chunks_total + slot_scenes.len();
342        if total > self.chunk_capacity {
343            self.chunk_capacity = total.next_power_of_two();
344            (self.chunk_buf, self.chunk_bg) = Self::chunk_slots(
345                device,
346                &self.chunk_layout,
347                self.chunk_stride,
348                self.chunk_capacity,
349            );
350        }
351        let mut slots = vec![0u8; self.chunk_stride as usize * total];
352        let chunks = scenes.iter().flat_map(|s| s.visible_chunks());
353        for (i, c) in chunks.enumerate() {
354            let h = &c.header;
355            let min = glam::DVec3::from(h.bbox_min.map(f64::from));
356            let size = glam::DVec3::from(h.bbox_max.map(f64::from)) - min;
357            let d = c.origin + min - camera.eye;
358            let s = size / 65535.0;
359            let u = ChunkUniform {
360                offset: [d.x as f32, d.y as f32, d.z as f32, 0.0],
361                scale: [s.x as f32, s.y as f32, s.z as f32, 0.0],
362            };
363            let at = i * self.chunk_stride as usize;
364            slots[at..at + size_of::<ChunkUniform>()].copy_from_slice(bytemuck::bytes_of(&u));
365        }
366        // Slot scenes: positions are f32 relative to the stream origin, so only the camera offset
367        // (in f64, decision 0013) and a unit scale.
368        for (k, s) in slot_scenes.iter().enumerate() {
369            let d = s.origin() - camera.eye;
370            let u = ChunkUniform {
371                offset: [d.x as f32, d.y as f32, d.z as f32, 0.0],
372                scale: [1.0, 1.0, 1.0, 0.0],
373            };
374            let at = (chunks_total + k) * self.chunk_stride as usize;
375            slots[at..at + size_of::<ChunkUniform>()].copy_from_slice(bytemuck::bytes_of(&u));
376        }
377        if !slots.is_empty() {
378            queue.write_buffer(&self.chunk_buf, 0, &slots);
379        }
380    }
381
382    // ---- SkyLens additions (see layers.rs) --------------------------------------------------
383
384    /// Point size: fixed pixels (the original behaviour) or world metres with perspective
385    /// attenuation (three.js `PointsMaterial { sizeAttenuation: true }`).
386    pub fn set_point_size(&mut self, size: PointSize) {
387        match size {
388            PointSize::Pixels(px) => {
389                self.point_px = px;
390                self.point_m = 0.0;
391            }
392            PointSize::Metres(m) => self.point_m = m.max(0.0),
393        }
394    }
395
396    /// Uploads camera, fog and per-chunk uniforms for every scene drawn this frame. Several
397    /// independent scenes (e.g. one per reconstruction segment) share one frame.
398    #[allow(clippy::too_many_arguments)]
399    pub fn prepare(
400        &mut self,
401        device: &wgpu::Device,
402        queue: &wgpu::Queue,
403        size: [u32; 2],
404        camera: &Camera,
405        scenes: &[&Scene],
406        fog: Option<crate::layers::Fog>,
407    ) {
408        self.write_frame(device, queue, size, camera, scenes, &[], fog);
409    }
410
411    /// Like `prepare`, plus slot scenes (decision 0052) for `draw_slots` in the same pass.
412    #[allow(clippy::too_many_arguments)]
413    pub fn prepare_with_slots(
414        &mut self,
415        device: &wgpu::Device,
416        queue: &wgpu::Queue,
417        size: [u32; 2],
418        camera: &Camera,
419        scenes: &[&Scene],
420        slots: &[&SlotScene],
421        fog: Option<crate::layers::Fog>,
422    ) {
423        self.write_frame(device, queue, size, camera, scenes, slots, fog);
424    }
425
426    /// Draws the slot scenes given to the last `prepare_with_slots`, in the same order: one draw of
427    /// `capacity` points each (hidden slots are dropped in the vertex shader). `alpha` as in `draw`.
428    pub fn draw_slots(
429        &self,
430        pass: &mut wgpu::RenderPass<'_>,
431        slots: &[&SlotScene],
432        alpha: Option<&[f32]>,
433    ) {
434        pass.set_bind_group(0, &self.camera_bg, &[]);
435        for (k, s) in slots.iter().enumerate() {
436            let Some(&slot) = self.prepared_slots.get(k) else {
437                break;
438            };
439            let Some(buffer) = s.buffer().filter(|_| s.capacity() > 0) else {
440                continue;
441            };
442            let faded = match fade(alpha, k) {
443                Fade::Skip => continue,
444                Fade::Opaque => false,
445                Fade::Blend(a) => {
446                    let a = f64::from(a);
447                    pass.set_blend_constant(wgpu::Color {
448                        r: a,
449                        g: a,
450                        b: a,
451                        a,
452                    });
453                    true
454                }
455            };
456            pass.set_pipeline(&self.pipelines[pipeline_index(2, faded)]);
457            let at = slot as u64 * self.chunk_stride;
458            pass.set_bind_group(1, &self.chunk_bg, &[at as u32]);
459            let n = s.capacity();
460            pass.set_vertex_buffer(0, buffer.slice(..u64::from(n) * SLOT_BYTES as u64));
461            pass.draw(0..4, 0..n);
462        }
463    }
464
465    /// Draws the scenes given to the last `prepare`, in the same order, into a caller-owned pass
466    /// (see `layers::begin_pass`). `alpha` scales every point's opacity per scene (reveal fades);
467    /// `None` means fully opaque.
468    pub fn draw(&self, pass: &mut wgpu::RenderPass<'_>, scenes: &[&Scene], alpha: Option<&[f32]>) {
469        pass.set_bind_group(0, &self.camera_bg, &[]);
470        let mut bound = None;
471        for (s, scene) in scenes.iter().enumerate() {
472            // A scene that was not prepared has no camera-relative slots: skip it.
473            let Some(&(first, count)) = self.prepared.get(s) else {
474                break;
475            };
476            let faded = match fade(alpha, s) {
477                Fade::Skip => continue,
478                Fade::Opaque => false,
479                Fade::Blend(a) => {
480                    let a = f64::from(a);
481                    pass.set_blend_constant(wgpu::Color {
482                        r: a,
483                        g: a,
484                        b: a,
485                        a,
486                    });
487                    true
488                }
489            };
490            // Chunks appended after `prepare` wait for the next frame. Call `prepare` again after a
491            // generation swap: until then `draw` uses the old slots for the new chunks.
492            for (i, c) in scene.visible_chunks().iter().take(count).enumerate() {
493                let p = pipeline_index(usize::from(c.header.stride != 12), faded);
494                if bound != Some(p) {
495                    pass.set_pipeline(&self.pipelines[p]);
496                    bound = Some(p);
497                }
498                let slot = (first + i) as u64 * self.chunk_stride;
499                pass.set_bind_group(1, &self.chunk_bg, &[slot as u32]);
500                pass.set_vertex_buffer(0, c.buffer.slice(..));
501                pass.draw(0..4, 0..c.points);
502            }
503        }
504    }
505}
506
507/// See `Renderer::set_point_size`.
508#[derive(Debug, Clone, Copy, PartialEq)]
509pub enum PointSize {
510    Pixels(f32),
511    Metres(f32),
512}
513
514/// Focal length in pixels for a vertical field of view over `height` pixels.
515fn focal_px(fov_y_deg: f64, height: u32) -> f64 {
516    f64::from(height) / 2.0 / (fov_y_deg.to_radians() / 2.0).tan()
517}
518
519/// CPU mirror of the point shader's diameter for a point at view depth `depth` metres.
520#[cfg_attr(not(test), allow(dead_code))]
521fn diameter_px(size: PointSize, focal_px: f32, depth: f32) -> f32 {
522    match size {
523        PointSize::Pixels(px) => px,
524        PointSize::Metres(m) if m > 0.0 => (m * focal_px / depth.max(1e-6)).clamp(1.0, 512.0),
525        PointSize::Metres(_) => 0.0,
526    }
527}
528
529/// First slot and count per scene when scenes are laid out back to back.
530fn slot_ranges(counts: &[usize]) -> Vec<(usize, usize)> {
531    let mut first = 0;
532    counts
533        .iter()
534        .map(|&n| {
535            let r = (first, n);
536            first += n;
537            r
538        })
539        .collect()
540}
541
542#[derive(Debug, Clone, Copy, PartialEq)]
543enum Fade {
544    Skip,
545    /// Opaque fast path: no blending.
546    Opaque,
547    Blend(f32),
548}
549
550/// Per-scene alpha: missing or >= 1 is opaque, <= 0 (or NaN) is not drawn.
551fn fade(alpha: Option<&[f32]>, scene: usize) -> Fade {
552    match alpha.and_then(|a| a.get(scene)).copied() {
553        None => Fade::Opaque,
554        Some(a) if a >= 1.0 => Fade::Opaque,
555        Some(a) if a > 0.0 => Fade::Blend(a),
556        Some(_) => Fade::Skip,
557    }
558}
559
560#[cfg(test)]
561mod tests {
562    use super::*;
563
564    #[test]
565    fn camera_uniform_layout_matches_the_wgsl_struct() {
566        // mat4 64 + vec2 8 + f32 4 + f32 4 + vec4 16 + vec4 16.
567        assert_eq!(size_of::<CameraUniform>(), 112);
568        assert_eq!(size_of::<ChunkUniform>(), 32);
569    }
570
571    #[test]
572    fn focal_length_matches_the_projection() {
573        // 90 degrees over 1000 px: tan(45) = 1, focal = 500 px.
574        assert!((focal_px(90.0, 1000) - 500.0).abs() < 1e-9);
575        // Agrees with Camera::project_px: a point 1 m right at 10 m depth is focal / 10 px off.
576        let cam = Camera::new([0.0, -10.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0], 50.0);
577        let a = cam.project_px([0.0, 0.0, 0.0], 800, 600).unwrap();
578        let b = cam.project_px([1.0, 0.0, 0.0], 800, 600).unwrap();
579        assert!((b[0] - a[0] - focal_px(50.0, 600) / 10.0).abs() < 1e-6);
580    }
581
582    #[test]
583    fn point_sizes_in_pixels_and_metres() {
584        assert_eq!(diameter_px(PointSize::Pixels(2.0), 500.0, 1000.0), 2.0);
585        // 0.5 m at 10 m with a 500 px focal length: 25 px; twice as far, half as big.
586        assert_eq!(diameter_px(PointSize::Metres(0.5), 500.0, 10.0), 25.0);
587        assert_eq!(diameter_px(PointSize::Metres(0.5), 500.0, 20.0), 12.5);
588        // Clamped: never below a pixel, never screen-filling.
589        assert_eq!(diameter_px(PointSize::Metres(0.5), 500.0, 1e6), 1.0);
590        assert_eq!(diameter_px(PointSize::Metres(0.5), 500.0, 1e-3), 512.0);
591    }
592
593    #[test]
594    fn scenes_get_back_to_back_slot_ranges() {
595        assert_eq!(slot_ranges(&[3, 0, 2]), vec![(0, 3), (3, 0), (3, 2)]);
596        assert!(slot_ranges(&[]).is_empty());
597    }
598
599    #[test]
600    fn per_scene_alpha_picks_opaque_blend_or_skip() {
601        assert_eq!(fade(None, 0), Fade::Opaque);
602        let a = [1.0, 0.25, 0.0, f32::NAN, 2.0];
603        assert_eq!(fade(Some(&a), 0), Fade::Opaque);
604        assert_eq!(fade(Some(&a), 1), Fade::Blend(0.25));
605        assert_eq!(fade(Some(&a), 2), Fade::Skip);
606        assert_eq!(fade(Some(&a), 3), Fade::Skip);
607        assert_eq!(fade(Some(&a), 4), Fade::Opaque);
608        // Shorter alpha slice: the rest is opaque.
609        assert_eq!(fade(Some(&a), 9), Fade::Opaque);
610    }
611}