Skip to main content

pointblitz_core/
layers.rs

1//! SkyLens additions: everything a map-style scene needs next to the points, drawn into one
2//! caller-owned pass so points, meshes and lines share a depth buffer.
3//!
4//! Frame recipe (all layers use the same camera-relative convention as the points: positions are
5//! absolute ENU metres, the GPU sees `position - camera.eye`):
6//!
7//! ```ignore
8//! let style = FrameStyle { clear: [0.039, 0.067, 0.157, 1.0], fog: Some(Fog { .. }) };
9//! points.prepare(device, queue, size, &camera, &[&scene], style.fog);
10//! meshes.prepare(queue, size, &camera, style.fog);
11//! lines.prepare(queue, size, &camera, style.fog);
12//! {
13//!     let mut pass = begin_pass(encoder, color, depth, &style);
14//!     meshes.draw_opaque(&mut pass);
15//!     points.draw(&mut pass, &[&scene], None);
16//!     meshes.draw_transparent(&mut pass);
17//!     lines.draw(&mut pass);
18//! }
19//! ```
20//!
21//! Depth is reversed-Z (`Depth32Float`, cleared to 0, compare `Greater`), exactly like the point
22//! pipeline. The signatures in this file are the contract the SkyLens screens code against.
23//!
24//! Colours: every colour given to this module (tints, light colours, emissive, vertex colours,
25//! texture texels) is display-encoded sRGB, i.e. CSS hex / 255, like the point colours. Meshes and
26//! lines decode to linear, light and blend like three.js (`MeshLambertMaterial`,
27//! `MeshBasicMaterial`, `LineBasicMaterial`), and encode again when the colour target is not an
28//! `*Srgb` format. `FrameStyle::clear` and `Fog::color` are values for the colour target as is
29//! (what a clear colour means for that format), so fog fades exactly into the background. Points
30//! keep the original behaviour: their bytes are written unchanged.
31//!
32//! WebGL2: uniforms are read only in vertex stages, no storage buffers, every uniform binding is a
33//! single small slot addressed with dynamic offsets aligned to
34//! `min_uniform_buffer_offset_alignment`, textures are shrunk to `max_texture_dimension_2d`.
35
36pub(crate) mod math;
37
38use crate::camera::Camera;
39use crate::renderer::DEPTH_FORMAT;
40use bytemuck::Zeroable;
41use glam::DVec3;
42use math::{
43    Candidate, FrameUniform, LineObject, MeshObject, Planned, frame_uniform, line_pipeline,
44    mesh_object, mesh_pipeline, pack_lines, pack_mesh, pack_slots, plan, slot_stride,
45};
46use std::collections::BTreeMap;
47use wgpu::util::DeviceExt;
48
49/// Linear distance fog, applied by every layer (like three.js `Fog`).
50#[derive(Debug, Clone, Copy, PartialEq)]
51pub struct Fog {
52    pub color: [f32; 3],
53    /// Metres from the eye where fog starts and where it is total.
54    pub near: f32,
55    pub far: f32,
56}
57
58/// Per-frame look shared by all layers.
59#[derive(Debug, Clone, Copy, PartialEq)]
60pub struct FrameStyle {
61    /// Background colour, the value written to the colour target as is (see the module docs).
62    pub clear: [f64; 4],
63    pub fog: Option<Fog>,
64}
65
66/// Opens the one render pass of a frame: clears colour to `style.clear`, depth to 0, and KEEPS
67/// depth stored so later passes (e.g. overlays) may test against it.
68pub fn begin_pass<'e>(
69    encoder: &'e mut wgpu::CommandEncoder,
70    color: &wgpu::TextureView,
71    depth: &wgpu::TextureView,
72    style: &FrameStyle,
73) -> wgpu::RenderPass<'e> {
74    let [r, g, b, a] = style.clear;
75    encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
76        label: Some("pointblitz frame"),
77        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
78            view: color,
79            depth_slice: None,
80            resolve_target: None,
81            ops: wgpu::Operations {
82                load: wgpu::LoadOp::Clear(wgpu::Color { r, g, b, a }),
83                store: wgpu::StoreOp::Store,
84            },
85        })],
86        depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
87            view: depth,
88            depth_ops: Some(wgpu::Operations {
89                // Reversed-Z: 0 is infinitely far.
90                load: wgpu::LoadOp::Clear(0.0),
91                store: wgpu::StoreOp::Store,
92            }),
93            stencil_ops: None,
94        }),
95        ..Default::default()
96    })
97}
98
99// ---------------------------------------------------------------------------------------------
100// Shared GPU plumbing
101// ---------------------------------------------------------------------------------------------
102
103fn uniform_layout(device: &wgpu::Device, label: &str, dynamic: bool) -> wgpu::BindGroupLayout {
104    device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
105        label: Some(label),
106        entries: &[wgpu::BindGroupLayoutEntry {
107            binding: 0,
108            // Vertex only: the fragment stages get what they need through varyings.
109            visibility: wgpu::ShaderStages::VERTEX,
110            ty: wgpu::BindingType::Buffer {
111                ty: wgpu::BufferBindingType::Uniform,
112                has_dynamic_offset: dynamic,
113                min_binding_size: None,
114            },
115            count: None,
116        }],
117    })
118}
119
120/// The per-frame uniform (camera, fog, output encoding) of one layer renderer.
121struct FrameSlot {
122    layout: wgpu::BindGroupLayout,
123    buf: wgpu::Buffer,
124    bg: wgpu::BindGroup,
125    encode_srgb: bool,
126}
127
128impl FrameSlot {
129    fn new(device: &wgpu::Device, color_format: wgpu::TextureFormat) -> Self {
130        let layout = uniform_layout(device, "layer frame", false);
131        let buf = device.create_buffer(&wgpu::BufferDescriptor {
132            label: Some("layer frame"),
133            size: size_of::<FrameUniform>() as u64,
134            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
135            mapped_at_creation: false,
136        });
137        let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
138            label: Some("layer frame"),
139            layout: &layout,
140            entries: &[wgpu::BindGroupEntry {
141                binding: 0,
142                resource: buf.as_entire_binding(),
143            }],
144        });
145        Self {
146            layout,
147            buf,
148            bg,
149            // An sRGB target encodes in hardware; anything else gets display values from the shader.
150            encode_srgb: !color_format.is_srgb(),
151        }
152    }
153
154    fn write(&self, queue: &wgpu::Queue, size: [u32; 2], camera: &Camera, fog: Option<Fog>) {
155        let aspect = f64::from(size[0].max(1)) / f64::from(size[1].max(1));
156        let u = frame_uniform(
157            camera.view_proj(aspect).to_cols_array_2d(),
158            fog,
159            self.encode_srgb,
160        );
161        queue.write_buffer(&self.buf, 0, bytemuck::bytes_of(&u));
162    }
163}
164
165/// Per-object uniform slots in one buffer, bound with a dynamic offset. Each binding is one slot,
166/// far below WebGL2's 16 KiB `max_uniform_buffer_binding_size`.
167struct Slots {
168    layout: wgpu::BindGroupLayout,
169    buf: wgpu::Buffer,
170    bg: wgpu::BindGroup,
171    capacity: usize,
172    stride: u64,
173    size: u64,
174}
175
176impl Slots {
177    fn new(device: &wgpu::Device, label: &str, size: u64) -> Self {
178        let layout = uniform_layout(device, label, true);
179        let align = u64::from(device.limits().min_uniform_buffer_offset_alignment);
180        let stride = slot_stride(size, align);
181        let capacity = 16;
182        let (buf, bg) = Self::alloc(device, &layout, stride, size, capacity);
183        Self {
184            layout,
185            buf,
186            bg,
187            capacity,
188            stride,
189            size,
190        }
191    }
192
193    fn alloc(
194        device: &wgpu::Device,
195        layout: &wgpu::BindGroupLayout,
196        stride: u64,
197        size: u64,
198        capacity: usize,
199    ) -> (wgpu::Buffer, wgpu::BindGroup) {
200        let buf = device.create_buffer(&wgpu::BufferDescriptor {
201            label: Some("layer objects"),
202            size: stride * capacity as u64,
203            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
204            mapped_at_creation: false,
205        });
206        let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
207            label: Some("layer objects"),
208            layout,
209            entries: &[wgpu::BindGroupEntry {
210                binding: 0,
211                resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
212                    buffer: &buf,
213                    offset: 0,
214                    size: wgpu::BufferSize::new(size),
215                }),
216            }],
217        });
218        (buf, bg)
219    }
220
221    /// Makes room for `n` slots. Returns true when the buffer was replaced (its contents are gone,
222    /// so whatever `prepare` planned must not be drawn).
223    fn reserve(&mut self, device: &wgpu::Device, n: usize) -> bool {
224        if n <= self.capacity {
225            return false;
226        }
227        self.capacity = n.next_power_of_two();
228        (self.buf, self.bg) =
229            Self::alloc(device, &self.layout, self.stride, self.size, self.capacity);
230        true
231    }
232
233    fn write<T: bytemuck::Pod>(&self, queue: &wgpu::Queue, items: &[T]) {
234        if !items.is_empty() {
235            queue.write_buffer(&self.buf, 0, &pack_slots(items, self.stride as usize));
236        }
237    }
238
239    fn offset(&self, slot: u32) -> u32 {
240        (u64::from(slot) * self.stride) as u32
241    }
242}
243
244fn blend_state(blend: Blend) -> Option<wgpu::BlendState> {
245    use wgpu::{BlendComponent, BlendFactor as F, BlendOperation::Add};
246    match blend {
247        Blend::Opaque => None,
248        // three.js NormalBlending (non-premultiplied).
249        Blend::Alpha => Some(wgpu::BlendState {
250            color: BlendComponent {
251                src_factor: F::SrcAlpha,
252                dst_factor: F::OneMinusSrcAlpha,
253                operation: Add,
254            },
255            alpha: BlendComponent {
256                src_factor: F::One,
257                dst_factor: F::OneMinusSrcAlpha,
258                operation: Add,
259            },
260        }),
261        // three.js AdditiveBlending (non-premultiplied): colour * alpha added; target alpha kept.
262        Blend::Additive => Some(wgpu::BlendState {
263            color: BlendComponent {
264                src_factor: F::SrcAlpha,
265                dst_factor: F::One,
266                operation: Add,
267            },
268            alpha: BlendComponent {
269                src_factor: F::Zero,
270                dst_factor: F::One,
271                operation: Add,
272            },
273        }),
274    }
275}
276
277/// Reversed-Z depth state; blended geometry tests but does not write.
278fn depth_state(test: bool, write: bool) -> wgpu::DepthStencilState {
279    wgpu::DepthStencilState {
280        format: DEPTH_FORMAT,
281        depth_write_enabled: Some(write),
282        depth_compare: Some(if test {
283            wgpu::CompareFunction::Greater
284        } else {
285            wgpu::CompareFunction::Always
286        }),
287        stencil: Default::default(),
288        bias: Default::default(),
289    }
290}
291
292fn shader(device: &wgpu::Device, label: &str, body: &str) -> wgpu::ShaderModule {
293    let source = format!("{}\n{}", include_str!("color.wgsl"), body);
294    device.create_shader_module(wgpu::ShaderModuleDescriptor {
295        label: Some(label),
296        source: wgpu::ShaderSource::Wgsl(source.into()),
297    })
298}
299
300/// Non-empty contents for a buffer (an empty slice cannot be bound).
301fn non_empty<'a>(bytes: &'a [u8], fallback: &'a [u8]) -> &'a [u8] {
302    if bytes.is_empty() { fallback } else { bytes }
303}
304
305// ---------------------------------------------------------------------------------------------
306// Meshes
307// ---------------------------------------------------------------------------------------------
308
309/// How a mesh is lit. Mirrors the three.js materials the SkyLens tower used.
310#[derive(Debug, Clone, Copy, PartialEq)]
311pub enum Shading {
312    /// Colour (vertex colour x texture x tint) as is.
313    Unlit,
314    /// `MeshLambertMaterial` under a hemisphere light plus one directional sun, with emissive.
315    ///
316    /// Same numbers as three.js (r155+ physical units, so `diffuse / pi` per light): `sky` and
317    /// `ground` are the `HemisphereLight` colours with +Z (ENU up) as its up axis, `sun_dir` points
318    /// from the scene towards the sun (three.js `light.position - target.position`).
319    Lambert {
320        sky: [f32; 3],
321        ground: [f32; 3],
322        hemi_intensity: f32,
323        sun_dir: [f32; 3],
324        sun_color: [f32; 3],
325        sun_intensity: f32,
326        emissive: [f32; 3],
327    },
328}
329
330#[derive(Debug, Clone, Copy, PartialEq, Eq)]
331pub enum Blend {
332    Opaque,
333    /// Alpha blended, depth tested, no depth write.
334    Alpha,
335    /// Additive (`AdditiveBlending`), depth tested, no depth write.
336    Additive,
337}
338
339#[derive(Debug, Clone, Copy, PartialEq)]
340pub struct Material {
341    pub shading: Shading,
342    /// Multiplied with vertex colours and the texture. Alpha is the opacity.
343    pub tint: [f32; 4],
344    pub blend: Blend,
345    /// Draw back faces too.
346    pub double_sided: bool,
347}
348
349/// RGBA8 sRGB image, row-major, top row first.
350#[derive(Debug, Clone)]
351pub struct TextureImage {
352    pub width: u32,
353    pub height: u32,
354    pub rgba: Vec<u8>,
355}
356
357/// One mesh in absolute ENU metres. Missing normals are computed (smooth when `flat == false`,
358/// per-face when `flat == true`).
359#[derive(Debug, Clone, Default)]
360pub struct MeshData {
361    pub positions: Vec<[f64; 3]>,
362    pub normals: Option<Vec<[f32; 3]>>,
363    /// RGBA8 per vertex; white when absent.
364    pub colors: Option<Vec<[u8; 4]>>,
365    /// Texture coordinates; required when a texture is given.
366    pub uvs: Option<Vec<[f32; 2]>>,
367    pub indices: Vec<u32>,
368    pub flat: bool,
369}
370
371struct GpuMesh {
372    vertices: wgpu::Buffer,
373    indices: wgpu::Buffer,
374    index_count: u32,
375    /// Absolute ENU origin the vertices are relative to (bounding-box centre).
376    origin: DVec3,
377    /// The texture is kept with its bind group so both live exactly as long as the mesh.
378    texture: Option<(wgpu::Texture, wgpu::BindGroup)>,
379    material: Material,
380    visible: bool,
381    /// Bumped by every `upsert`, so a draw list made before a replacement skips the new geometry
382    /// until the next `prepare` has written its uniform.
383    version: u64,
384}
385
386/// Owns GPU meshes by caller-chosen id.
387pub struct MeshRenderer {
388    /// Indexed by `math::mesh_pipeline(blend, double_sided)`.
389    pipelines: Vec<wgpu::RenderPipeline>,
390    frame: FrameSlot,
391    slots: Slots,
392    texture_layout: wgpu::BindGroupLayout,
393    sampler: wgpu::Sampler,
394    /// 1x1 white texture for untextured meshes (one shader for both). Made by the first `upsert`,
395    /// because `new` has no queue to upload it with.
396    white: Option<(wgpu::Texture, wgpu::BindGroup)>,
397    meshes: BTreeMap<u64, GpuMesh>,
398    next_version: u64,
399    opaque: Vec<Planned>,
400    transparent: Vec<Planned>,
401}
402
403impl MeshRenderer {
404    pub fn new(device: &wgpu::Device, color_format: wgpu::TextureFormat) -> Self {
405        let module = shader(device, "pointblitz meshes", include_str!("mesh.wgsl"));
406        let frame = FrameSlot::new(device, color_format);
407        let slots = Slots::new(device, "mesh objects", size_of::<MeshObject>() as u64);
408        let texture_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
409            label: Some("mesh texture"),
410            entries: &[
411                wgpu::BindGroupLayoutEntry {
412                    binding: 0,
413                    visibility: wgpu::ShaderStages::FRAGMENT,
414                    ty: wgpu::BindingType::Texture {
415                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
416                        view_dimension: wgpu::TextureViewDimension::D2,
417                        multisampled: false,
418                    },
419                    count: None,
420                },
421                wgpu::BindGroupLayoutEntry {
422                    binding: 1,
423                    visibility: wgpu::ShaderStages::FRAGMENT,
424                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
425                    count: None,
426                },
427            ],
428        });
429        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
430            label: Some("meshes"),
431            bind_group_layouts: &[
432                Some(&frame.layout),
433                Some(&slots.layout),
434                Some(&texture_layout),
435            ],
436            immediate_size: 0,
437        });
438        let attributes = wgpu::vertex_attr_array![
439            0 => Float32x3,
440            1 => Float32x3,
441            2 => Float32x2,
442            3 => Unorm8x4,
443        ];
444        let mut pipelines = Vec::with_capacity(6);
445        for blend in [Blend::Opaque, Blend::Alpha, Blend::Additive] {
446            for double_sided in [false, true] {
447                debug_assert_eq!(pipelines.len(), mesh_pipeline(blend, double_sided));
448                pipelines.push(
449                    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
450                        label: Some("meshes"),
451                        layout: Some(&layout),
452                        vertex: wgpu::VertexState {
453                            module: &module,
454                            entry_point: Some("vs"),
455                            compilation_options: Default::default(),
456                            buffers: &[Some(wgpu::VertexBufferLayout {
457                                array_stride: size_of::<math::MeshVertex>() as u64,
458                                step_mode: wgpu::VertexStepMode::Vertex,
459                                attributes: &attributes,
460                            })],
461                        },
462                        primitive: wgpu::PrimitiveState {
463                            topology: wgpu::PrimitiveTopology::TriangleList,
464                            front_face: wgpu::FrontFace::Ccw,
465                            cull_mode: if double_sided {
466                                None
467                            } else {
468                                Some(wgpu::Face::Back)
469                            },
470                            ..Default::default()
471                        },
472                        depth_stencil: Some(depth_state(true, blend == Blend::Opaque)),
473                        multisample: Default::default(),
474                        fragment: Some(wgpu::FragmentState {
475                            module: &module,
476                            entry_point: Some("fs"),
477                            compilation_options: Default::default(),
478                            targets: &[Some(wgpu::ColorTargetState {
479                                format: color_format,
480                                blend: blend_state(blend),
481                                write_mask: wgpu::ColorWrites::ALL,
482                            })],
483                        }),
484                        multiview_mask: None,
485                        cache: None,
486                    }),
487                );
488            }
489        }
490        // three.js textures: linear filtering with mipmaps; clamp so drapes do not bleed at edges.
491        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
492            label: Some("mesh texture"),
493            address_mode_u: wgpu::AddressMode::ClampToEdge,
494            address_mode_v: wgpu::AddressMode::ClampToEdge,
495            address_mode_w: wgpu::AddressMode::ClampToEdge,
496            mag_filter: wgpu::FilterMode::Linear,
497            min_filter: wgpu::FilterMode::Linear,
498            mipmap_filter: wgpu::MipmapFilterMode::Linear,
499            ..Default::default()
500        });
501        Self {
502            pipelines,
503            frame,
504            slots,
505            texture_layout,
506            sampler,
507            white: None,
508            meshes: BTreeMap::new(),
509            next_version: 0,
510            opaque: Vec::new(),
511            transparent: Vec::new(),
512        }
513    }
514
515    /// Inserts or replaces mesh `id`. The texture, if any, is uploaded once and owned by the mesh.
516    pub fn upsert(
517        &mut self,
518        device: &wgpu::Device,
519        queue: &wgpu::Queue,
520        id: u64,
521        mesh: &MeshData,
522        texture: Option<&TextureImage>,
523        material: Material,
524    ) {
525        assert!(
526            texture.is_none() || mesh.uvs.is_some(),
527            "a textured mesh needs uvs"
528        );
529        let packed = pack_mesh(mesh);
530        let vertices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
531            label: Some("mesh vertices"),
532            contents: non_empty(bytemuck::cast_slice(&packed.vertices), &[0; 36]),
533            usage: wgpu::BufferUsages::VERTEX,
534        });
535        let indices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
536            label: Some("mesh indices"),
537            contents: non_empty(bytemuck::cast_slice(&packed.indices), &[0; 4]),
538            usage: wgpu::BufferUsages::INDEX,
539        });
540        let texture = texture.map(|img| self.upload_texture(device, queue, img));
541        if self.white.is_none() {
542            let white = math::MipChain {
543                width: 1,
544                height: 1,
545                levels: 1,
546                data: vec![255; 4],
547            };
548            self.white = Some(self.texture_from_chain(device, queue, &white));
549        }
550        self.next_version += 1;
551        // A replaced mesh keeps its visibility (e.g. a hidden layer being refreshed stays hidden).
552        let visible = self.meshes.get(&id).is_none_or(|m| m.visible);
553        self.meshes.insert(
554            id,
555            GpuMesh {
556                vertices,
557                indices,
558                index_count: packed.indices.len() as u32,
559                origin: packed.origin,
560                texture,
561                material,
562                visible,
563                version: self.next_version,
564            },
565        );
566        if self.slots.reserve(device, self.meshes.len()) {
567            self.opaque.clear();
568            self.transparent.clear();
569        }
570    }
571
572    fn upload_texture(
573        &self,
574        device: &wgpu::Device,
575        queue: &wgpu::Queue,
576        img: &TextureImage,
577    ) -> (wgpu::Texture, wgpu::BindGroup) {
578        let chain = math::mip_chain(img, device.limits().max_texture_dimension_2d);
579        self.texture_from_chain(device, queue, &chain)
580    }
581
582    fn texture_from_chain(
583        &self,
584        device: &wgpu::Device,
585        queue: &wgpu::Queue,
586        chain: &math::MipChain,
587    ) -> (wgpu::Texture, wgpu::BindGroup) {
588        let texture = device.create_texture_with_data(
589            queue,
590            &wgpu::TextureDescriptor {
591                label: Some("mesh texture"),
592                size: wgpu::Extent3d {
593                    width: chain.width,
594                    height: chain.height,
595                    depth_or_array_layers: 1,
596                },
597                mip_level_count: chain.levels,
598                sample_count: 1,
599                dimension: wgpu::TextureDimension::D2,
600                // Sampling decodes sRGB, so the shader filters and lights in linear.
601                format: wgpu::TextureFormat::Rgba8UnormSrgb,
602                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
603                view_formats: &[],
604            },
605            wgpu::util::TextureDataOrder::LayerMajor,
606            &chain.data,
607        );
608        let view = texture.create_view(&Default::default());
609        let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
610            label: Some("mesh texture"),
611            layout: &self.texture_layout,
612            entries: &[
613                wgpu::BindGroupEntry {
614                    binding: 0,
615                    resource: wgpu::BindingResource::TextureView(&view),
616                },
617                wgpu::BindGroupEntry {
618                    binding: 1,
619                    resource: wgpu::BindingResource::Sampler(&self.sampler),
620                },
621            ],
622        });
623        (texture, bg)
624    }
625
626    /// Changes only the material (e.g. a display-mode switch) without re-uploading geometry.
627    pub fn set_material(&mut self, id: u64, material: Material) {
628        if let Some(m) = self.meshes.get_mut(&id) {
629            m.material = material;
630        }
631    }
632
633    pub fn set_visible(&mut self, id: u64, visible: bool) {
634        if let Some(m) = self.meshes.get_mut(&id) {
635            m.visible = visible;
636        }
637    }
638
639    pub fn remove(&mut self, id: u64) {
640        self.meshes.remove(&id);
641    }
642
643    pub fn clear(&mut self) {
644        self.meshes.clear();
645        self.opaque.clear();
646        self.transparent.clear();
647    }
648
649    pub fn len(&self) -> usize {
650        self.meshes.len()
651    }
652
653    pub fn is_empty(&self) -> bool {
654        self.len() == 0
655    }
656
657    /// Uploads camera, light and fog uniforms for this frame.
658    pub fn prepare(
659        &mut self,
660        queue: &wgpu::Queue,
661        size: [u32; 2],
662        camera: &Camera,
663        fog: Option<Fog>,
664    ) {
665        self.frame.write(queue, size, camera, fog);
666        let candidates: Vec<Candidate> = self
667            .meshes
668            .iter()
669            .map(|(&id, m)| Candidate {
670                id,
671                version: m.version,
672                visible: m.visible && m.index_count > 0,
673                blend: m.material.blend,
674                pipeline: mesh_pipeline(m.material.blend, m.material.double_sided),
675                distance: (m.origin - camera.eye).length(),
676            })
677            .collect();
678        let (opaque, transparent) = plan(&candidates);
679        let mut objects = vec![MeshObject::zeroed(); opaque.len() + transparent.len()];
680        for p in opaque.iter().chain(&transparent) {
681            let m = &self.meshes[&p.id];
682            objects[p.slot as usize] = mesh_object(&m.material, m.origin - camera.eye);
683        }
684        self.slots.write(queue, &objects);
685        self.opaque = opaque;
686        self.transparent = transparent;
687    }
688
689    /// Draws `Blend::Opaque` meshes.
690    pub fn draw_opaque(&self, pass: &mut wgpu::RenderPass<'_>) {
691        self.draw_list(pass, &self.opaque);
692    }
693
694    /// Draws `Blend::Alpha` and `Blend::Additive` meshes (after opaque geometry and points).
695    pub fn draw_transparent(&self, pass: &mut wgpu::RenderPass<'_>) {
696        self.draw_list(pass, &self.transparent);
697    }
698
699    fn draw_list(&self, pass: &mut wgpu::RenderPass<'_>, list: &[Planned]) {
700        if list.is_empty() {
701            return;
702        }
703        pass.set_bind_group(0, &self.frame.bg, &[]);
704        let mut bound = None;
705        for p in list {
706            let Some(m) = self.meshes.get(&p.id) else {
707                continue;
708            };
709            if m.version != p.version || !m.visible || m.index_count == 0 {
710                continue;
711            }
712            if bound != Some(p.pipeline) {
713                pass.set_pipeline(&self.pipelines[p.pipeline]);
714                bound = Some(p.pipeline);
715            }
716            pass.set_bind_group(1, &self.slots.bg, &[self.slots.offset(p.slot)]);
717            let Some((_, texture)) = m.texture.as_ref().or(self.white.as_ref()) else {
718                continue;
719            };
720            pass.set_bind_group(2, texture, &[]);
721            pass.set_vertex_buffer(0, m.vertices.slice(..));
722            pass.set_index_buffer(m.indices.slice(..), wgpu::IndexFormat::Uint32);
723            pass.draw_indexed(0..m.index_count, 0, 0..1);
724        }
725    }
726}
727
728// ---------------------------------------------------------------------------------------------
729// Lines
730// ---------------------------------------------------------------------------------------------
731
732#[derive(Debug, Clone, Copy, PartialEq, Eq)]
733pub enum Topology {
734    /// Pairs of points.
735    List,
736    /// One connected polyline.
737    Strip,
738}
739
740/// A set of 1-pixel lines (like three.js `LineBasicMaterial` / `LineSegments`).
741#[derive(Debug, Clone)]
742pub struct LineSet {
743    pub positions: Vec<[f64; 3]>,
744    pub topology: Topology,
745    /// Per-vertex RGBA8; overrides `color` when present (used for fading trails).
746    pub colors: Option<Vec<[u8; 4]>>,
747    pub color: [f32; 4],
748    pub blend: Blend,
749    /// `false` draws on top of everything (no depth test).
750    pub depth_test: bool,
751}
752
753struct GpuLines {
754    buffer: wgpu::Buffer,
755    draw_count: u32,
756    origin: DVec3,
757    tint: [f32; 4],
758    blend: Blend,
759    depth_test: bool,
760    topology: Topology,
761    visible: bool,
762    version: u64,
763}
764
765/// Owns GPU line sets by caller-chosen id.
766pub struct LineRenderer {
767    /// Indexed by `math::line_pipeline(blend, depth_test, topology)`.
768    pipelines: Vec<wgpu::RenderPipeline>,
769    frame: FrameSlot,
770    slots: Slots,
771    sets: BTreeMap<u64, GpuLines>,
772    next_version: u64,
773    /// Depth-tested sets (opaque, then blended far to near), then sets drawn on top.
774    planned: Vec<Planned>,
775}
776
777impl LineRenderer {
778    pub fn new(device: &wgpu::Device, color_format: wgpu::TextureFormat) -> Self {
779        let module = shader(device, "pointblitz lines", include_str!("lines.wgsl"));
780        let frame = FrameSlot::new(device, color_format);
781        let slots = Slots::new(device, "line objects", size_of::<LineObject>() as u64);
782        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
783            label: Some("lines"),
784            bind_group_layouts: &[Some(&frame.layout), Some(&slots.layout)],
785            immediate_size: 0,
786        });
787        let attributes = wgpu::vertex_attr_array![0 => Float32x3, 1 => Unorm8x4];
788        let mut pipelines = Vec::with_capacity(12);
789        for blend in [Blend::Opaque, Blend::Alpha, Blend::Additive] {
790            for depth_test in [false, true] {
791                for topology in [Topology::List, Topology::Strip] {
792                    debug_assert_eq!(pipelines.len(), line_pipeline(blend, depth_test, topology));
793                    pipelines.push(device.create_render_pipeline(
794                        &wgpu::RenderPipelineDescriptor {
795                            label: Some("lines"),
796                            layout: Some(&layout),
797                            vertex: wgpu::VertexState {
798                                module: &module,
799                                entry_point: Some("vs"),
800                                compilation_options: Default::default(),
801                                buffers: &[Some(wgpu::VertexBufferLayout {
802                                    array_stride: size_of::<math::LineVertex>() as u64,
803                                    step_mode: wgpu::VertexStepMode::Vertex,
804                                    attributes: &attributes,
805                                })],
806                            },
807                            primitive: wgpu::PrimitiveState {
808                                topology: match topology {
809                                    Topology::List => wgpu::PrimitiveTopology::LineList,
810                                    Topology::Strip => wgpu::PrimitiveTopology::LineStrip,
811                                },
812                                ..Default::default()
813                            },
814                            depth_stencil: Some(depth_state(
815                                depth_test,
816                                depth_test && blend == Blend::Opaque,
817                            )),
818                            multisample: Default::default(),
819                            fragment: Some(wgpu::FragmentState {
820                                module: &module,
821                                entry_point: Some("fs"),
822                                compilation_options: Default::default(),
823                                targets: &[Some(wgpu::ColorTargetState {
824                                    format: color_format,
825                                    blend: blend_state(blend),
826                                    write_mask: wgpu::ColorWrites::ALL,
827                                })],
828                            }),
829                            multiview_mask: None,
830                            cache: None,
831                        },
832                    ));
833                }
834            }
835        }
836        Self {
837            pipelines,
838            frame,
839            slots,
840            sets: BTreeMap::new(),
841            next_version: 0,
842            planned: Vec::new(),
843        }
844    }
845
846    pub fn upsert(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, id: u64, lines: &LineSet) {
847        let _ = queue;
848        let packed = pack_lines(lines);
849        let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
850            label: Some("line vertices"),
851            contents: non_empty(bytemuck::cast_slice(&packed.vertices), &[0; 16]),
852            usage: wgpu::BufferUsages::VERTEX,
853        });
854        self.next_version += 1;
855        let visible = self.sets.get(&id).is_none_or(|s| s.visible);
856        self.sets.insert(
857            id,
858            GpuLines {
859                buffer,
860                draw_count: packed.draw_count,
861                origin: packed.origin,
862                tint: packed.tint,
863                blend: lines.blend,
864                depth_test: lines.depth_test,
865                topology: lines.topology,
866                visible,
867                version: self.next_version,
868            },
869        );
870        if self.slots.reserve(device, self.sets.len()) {
871            self.planned.clear();
872        }
873    }
874
875    /// Hides or shows line set `id` without re-uploading it (SkyLens helper).
876    pub fn set_visible(&mut self, id: u64, visible: bool) {
877        if let Some(s) = self.sets.get_mut(&id) {
878            s.visible = visible;
879        }
880    }
881
882    pub fn remove(&mut self, id: u64) {
883        self.sets.remove(&id);
884    }
885
886    pub fn clear(&mut self) {
887        self.sets.clear();
888        self.planned.clear();
889    }
890
891    /// Number of line sets held (SkyLens helper).
892    pub fn len(&self) -> usize {
893        self.sets.len()
894    }
895
896    pub fn is_empty(&self) -> bool {
897        self.sets.is_empty()
898    }
899
900    pub fn prepare(
901        &mut self,
902        queue: &wgpu::Queue,
903        size: [u32; 2],
904        camera: &Camera,
905        fog: Option<Fog>,
906    ) {
907        self.frame.write(queue, size, camera, fog);
908        let candidates: Vec<Candidate> = self
909            .sets
910            .iter()
911            .map(|(&id, s)| Candidate {
912                id,
913                version: s.version,
914                visible: s.visible && s.draw_count > 0,
915                blend: s.blend,
916                pipeline: line_pipeline(s.blend, s.depth_test, s.topology),
917                distance: (s.origin - camera.eye).length(),
918            })
919            .collect();
920        let (opaque, blended) = plan(&candidates);
921        let mut objects = vec![LineObject::zeroed(); opaque.len() + blended.len()];
922        let mut planned: Vec<Planned> = opaque.into_iter().chain(blended).collect();
923        for p in &planned {
924            let s = &self.sets[&p.id];
925            let d = (s.origin - camera.eye).as_vec3();
926            objects[p.slot as usize] = LineObject {
927                offset: [d.x, d.y, d.z, 0.0],
928                tint: s.tint,
929            };
930        }
931        // Sets without depth test go last so they really are on top (stable: order kept).
932        planned.sort_by_key(|p| !self.sets[&p.id].depth_test);
933        self.slots.write(queue, &objects);
934        self.planned = planned;
935    }
936
937    pub fn draw(&self, pass: &mut wgpu::RenderPass<'_>) {
938        if self.planned.is_empty() {
939            return;
940        }
941        pass.set_bind_group(0, &self.frame.bg, &[]);
942        let mut bound = None;
943        for p in &self.planned {
944            let Some(s) = self.sets.get(&p.id) else {
945                continue;
946            };
947            if s.version != p.version || !s.visible || s.draw_count == 0 {
948                continue;
949            }
950            if bound != Some(p.pipeline) {
951                pass.set_pipeline(&self.pipelines[p.pipeline]);
952                bound = Some(p.pipeline);
953            }
954            pass.set_bind_group(1, &self.slots.bg, &[self.slots.offset(p.slot)]);
955            pass.set_vertex_buffer(0, s.buffer.slice(..));
956            pass.draw(0..s.draw_count, 0..1);
957        }
958    }
959}