runmat-plot 0.7.1

GPU-accelerated and static plotting for RunMat with WGPU and Plotters
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
//! 3D scatter plot implementation for MATLAB's `scatter3`.

use crate::context::shared_wgpu_context;
use crate::core::{
    vertex_utils, BoundingBox, DrawCall, GpuVertexBuffer, Material, PipelineType, RenderData,
    Vertex,
};
use crate::gpu::scatter2::{
    ScatterAttributeBuffer, ScatterColorBuffer, ScatterColorLayout, ScatterSizeUnit,
};
use crate::gpu::scatter3::Scatter3GpuInputs;
use crate::gpu::util::{copy_readback_bytes_typed, readback_scalar_buffer_f64_typed};
use crate::gpu::PlotReadbackError;
use crate::plots::scatter::{marker_area_points2_to_diameter_px, MarkerStyle};
use crate::plots::{NumericPlotData, PlotDataExportError};
use glam::{Vec3, Vec4};
use runmat_value::NumericStorage;

#[derive(Clone, Copy, Debug)]
pub struct Scatter3GpuStyle {
    pub color: Vec4,
    pub edge_color: Vec4,
    pub edge_thickness: f32,
    pub marker_style: MarkerStyle,
    pub filled: bool,
    pub has_per_point_colors: bool,
    pub edge_from_vertex_colors: bool,
}

/// GPU-accelerated scatter3 plot for MATLAB semantics.
#[derive(Debug, Clone)]
pub struct Scatter3Plot {
    /// Point positions in 3D space.
    pub points: Vec<Vec3>,
    /// Per-point RGBA colors.
    pub colors: Vec<Vec4>,
    /// Marker size in pixels.
    pub point_size: f32,
    /// Optional per-point marker sizes.
    pub point_sizes: Option<Vec<f32>>,
    /// Marker edge color.
    pub edge_color: Vec4,
    /// Marker edge thickness in pixels.
    pub edge_thickness: f32,
    /// Marker shape.
    pub marker_style: MarkerStyle,
    /// Whether marker faces are filled.
    pub filled: bool,
    /// Whether edge color should come from per-vertex colors.
    pub edge_color_from_vertex_colors: bool,
    /// Legend label.
    pub label: Option<String>,
    /// Visibility flag.
    pub visible: bool,
    /// Scalar color data (`C`) and its limits, kept so the colors follow the colormap.
    pub color_values: Option<Vec<f64>>,
    pub color_limits: Option<(f64, f64)>,
    source_x: Option<NumericPlotData>,
    source_y: Option<NumericPlotData>,
    source_z: Option<NumericPlotData>,
    vertices: Option<Vec<Vertex>>,
    bounds: Option<BoundingBox>,
    gpu_vertices: Option<GpuVertexBuffer>,
    gpu_point_count: Option<usize>,
    gpu_inputs: Option<Scatter3GpuInputs>,
    gpu_has_per_point_colors: bool,
}

impl Scatter3Plot {
    pub async fn export_scene_points(&self) -> Result<Vec<Vec3>, PlotDataExportError> {
        if let Some((x, y, z)) = self.export_numeric_xyz_data().await? {
            return Ok(x
                .materialize_f64()
                .into_iter()
                .zip(y.materialize_f64())
                .zip(z.materialize_f64())
                .map(|((x, y), z)| Vec3::new(x as f32, y as f32, z as f32))
                .collect());
        }
        if !self.points.is_empty() {
            return Ok(self.points.clone());
        }

        Ok(Vec::new())
    }

    pub async fn export_numeric_xyz_data(
        &self,
    ) -> Result<Option<(NumericPlotData, NumericPlotData, NumericPlotData)>, PlotDataExportError>
    {
        match (&self.source_x, &self.source_y, &self.source_z) {
            (Some(x), Some(y), Some(z)) if x.len() == y.len() && x.len() == z.len() => {
                return Ok(Some((x.clone(), y.clone(), z.clone())));
            }
            (None, None, None) => {}
            _ => {
                return Err(PlotDataExportError::SourceUnavailable(
                    "scatter3 plot has incomplete CPU source data",
                ))
            }
        }

        if let Some(inputs) = &self.gpu_inputs {
            let context = shared_wgpu_context().ok_or(PlotDataExportError::SourceUnavailable(
                "scatter3 plot has GPU source data but no shared WGPU context is installed",
            ))?;
            let len = inputs.len as usize;
            let x = readback_scalar_buffer_f64_typed(
                &context.access,
                &inputs.x_buffer,
                len,
                inputs.scalar,
            )
            .await?;
            let y = readback_scalar_buffer_f64_typed(
                &context.access,
                &inputs.y_buffer,
                len,
                inputs.scalar,
            )
            .await?;
            let z = readback_scalar_buffer_f64_typed(
                &context.access,
                &inputs.z_buffer,
                len,
                inputs.scalar,
            )
            .await?;
            let shape = vec![1, len];
            let wrap = |values: Vec<f64>| match inputs.scalar {
                crate::gpu::ScalarType::F64 => {
                    NumericPlotData::new(NumericStorage::F64(values), shape.clone())
                }
                crate::gpu::ScalarType::F32 => NumericPlotData::new(
                    NumericStorage::F32(values.into_iter().map(|value| value as f32).collect()),
                    shape.clone(),
                ),
            };
            return Ok(Some((
                wrap(x).map_err(PlotDataExportError::InvalidSourceLayout)?,
                wrap(y).map_err(PlotDataExportError::InvalidSourceLayout)?,
                wrap(z).map_err(PlotDataExportError::InvalidSourceLayout)?,
            )));
        }

        if self.gpu_vertices.is_some() {
            return Err(PlotDataExportError::SourceUnavailable(
                "scatter3 plot has GPU render vertices but no exportable source data",
            ));
        }

        Ok(None)
    }

    pub async fn export_scene_colors(
        &self,
        point_count: usize,
    ) -> Result<Vec<Vec4>, PlotDataExportError> {
        if self.colors.len() == point_count && !self.has_resident_color_source() {
            return Ok(self.colors.clone());
        }
        if self.colors.len() == 1 && !self.gpu_has_per_point_colors {
            return Ok(vec![self.colors[0]; point_count]);
        }

        if let Some(inputs) = &self.gpu_inputs {
            match &inputs.colors {
                ScatterColorBuffer::None => {
                    let color = self.colors.first().copied().unwrap_or(Vec4::ONE);
                    return Ok(vec![color; point_count]);
                }
                ScatterColorBuffer::Host(colors) => {
                    if colors.len() != point_count {
                        return Err(PlotDataExportError::InvalidSourceLayout(format!(
                            "scatter3 color count ({}) does not match point count ({point_count})",
                            colors.len()
                        )));
                    }
                    return Ok(colors
                        .iter()
                        .map(|color| Vec4::from_array(*color))
                        .collect());
                }
                ScatterColorBuffer::Gpu { buffer, components } => {
                    let context = shared_wgpu_context()
                        .ok_or(PlotDataExportError::SourceUnavailable(
                        "scatter3 plot has GPU color data but no shared WGPU context is installed",
                    ))?;
                    let components = *components as usize;
                    if components != 3 && components != 4 {
                        return Err(PlotDataExportError::InvalidSourceLayout(format!(
                            "scatter3 GPU color source has unsupported component count {components}"
                        )));
                    }
                    let value_count = point_count
                        .checked_mul(components)
                        .ok_or(PlotReadbackError::ByteSizeOverflow)?;
                    let byte_len = value_count
                        .checked_mul(std::mem::size_of::<f32>())
                        .ok_or(PlotReadbackError::ByteSizeOverflow)?;
                    let bytes =
                        copy_readback_bytes_typed(&context.access, buffer, byte_len).await?;
                    let values: &[f32] = bytemuck::try_cast_slice(&bytes).map_err(|err| {
                        PlotDataExportError::InvalidSourceLayout(format!(
                            "scatter3 GPU color readback failed: {err}"
                        ))
                    })?;
                    if values.len() != value_count {
                        return Err(PlotDataExportError::InvalidSourceLayout(format!(
                            "scatter3 GPU color readback returned {} values, expected {value_count}",
                            values.len()
                        )));
                    }
                    let mut colors = Vec::with_capacity(point_count);
                    for point in 0..point_count {
                        let component = |channel: usize| match inputs.color_layout {
                            ScatterColorLayout::Interleaved => values[point * components + channel],
                            ScatterColorLayout::ColumnMajor => {
                                values[point + channel * point_count]
                            }
                        };
                        let alpha = if components == 4 { component(3) } else { 1.0 };
                        colors.push(Vec4::new(component(0), component(1), component(2), alpha));
                    }
                    return Ok(colors);
                }
            }
        }

        if self.gpu_has_per_point_colors {
            return Err(PlotDataExportError::SourceUnavailable(
                "scatter3 plot has GPU per-point colors but no exportable color source",
            ));
        }
        if self.colors.is_empty() {
            return Ok(vec![Vec4::ONE; point_count]);
        }
        Err(PlotDataExportError::InvalidSourceLayout(format!(
            "scatter3 color count ({}) does not match point count {point_count}",
            self.colors.len()
        )))
    }

    /// Read the retained per-point size source, if one was supplied. GPU
    /// readback uses the same exported buffer owner used by vertex packing.
    pub async fn export_scene_sizes(&self) -> Result<Option<Vec<f32>>, PlotDataExportError> {
        if let Some(sizes) = &self.point_sizes {
            return Ok(Some(sizes.clone()));
        }
        let Some(inputs) = &self.gpu_inputs else {
            return Ok(None);
        };
        let count = inputs.len as usize;
        match &inputs.sizes {
            ScatterAttributeBuffer::None => Ok(None),
            ScatterAttributeBuffer::Host(sizes) if sizes.len() == count => Ok(Some(sizes.clone())),
            ScatterAttributeBuffer::Host(sizes) => {
                Err(PlotDataExportError::InvalidSourceLayout(format!(
                    "scatter3 size count ({}) does not match point count {count}",
                    sizes.len()
                )))
            }
            ScatterAttributeBuffer::Gpu(buffer) => {
                let context =
                    shared_wgpu_context().ok_or(PlotDataExportError::SourceUnavailable(
                        "scatter3 plot has GPU size data but no shared WGPU context is installed",
                    ))?;
                let byte_len = count
                    .checked_mul(std::mem::size_of::<f32>())
                    .ok_or(PlotReadbackError::ByteSizeOverflow)?;
                let bytes = copy_readback_bytes_typed(&context.access, buffer, byte_len).await?;
                let values: &[f32] = bytemuck::try_cast_slice(&bytes).map_err(|err| {
                    PlotDataExportError::InvalidSourceLayout(format!(
                        "scatter3 GPU size readback failed: {err}"
                    ))
                })?;
                if values.len() != count {
                    return Err(PlotDataExportError::InvalidSourceLayout(format!(
                        "scatter3 GPU size readback returned {} values, expected {count}",
                        values.len()
                    )));
                }
                Ok(Some(match inputs.size_unit {
                    ScatterSizeUnit::DiameterPixels => values.to_vec(),
                    ScatterSizeUnit::AreaPointsSquared => values
                        .iter()
                        .map(|value| marker_area_points2_to_diameter_px(f64::from(*value)))
                        .collect(),
                }))
            }
        }
    }

    /// Create a new scatter3 plot. Colors default to a blue colormap.
    pub fn new(points: Vec<Vec3>) -> Result<Self, String> {
        let shape = vec![1, points.len()];
        let x = NumericPlotData::new(
            NumericStorage::F32(points.iter().map(|point| point.x).collect()),
            shape.clone(),
        )?;
        let y = NumericPlotData::new(
            NumericStorage::F32(points.iter().map(|point| point.y).collect()),
            shape.clone(),
        )?;
        let z = NumericPlotData::new(
            NumericStorage::F32(points.iter().map(|point| point.z).collect()),
            shape,
        )?;
        Self::from_numeric_data(x, y, z)
    }

    /// Create a scatter3 plot while retaining native source class and values.
    pub fn from_numeric_data(
        x: NumericPlotData,
        y: NumericPlotData,
        z: NumericPlotData,
    ) -> Result<Self, String> {
        if x.len() != y.len() || x.len() != z.len() {
            return Err("scatter3 source lengths must match".to_string());
        }
        let points = x
            .materialize_f64()
            .into_iter()
            .zip(y.materialize_f64())
            .zip(z.materialize_f64())
            .map(|((x, y), z)| Vec3::new(x as f32, y as f32, z as f32))
            .collect::<Vec<_>>();
        let default_color = Vec4::new(0.1, 0.7, 0.3, 1.0);
        let colors = vec![default_color; points.len()];
        Ok(Self {
            points,
            colors,
            point_size: 8.0,
            point_sizes: None,
            edge_color: default_color,
            edge_thickness: 1.0,
            marker_style: MarkerStyle::Circle,
            filled: true,
            edge_color_from_vertex_colors: false,
            label: None,
            visible: true,
            source_x: Some(x),
            source_y: Some(y),
            source_z: Some(z),
            vertices: None,
            bounds: None,
            gpu_vertices: None,
            gpu_point_count: None,
            gpu_inputs: None,
            gpu_has_per_point_colors: false,
            color_values: None,
            color_limits: None,
        })
    }

    /// Replace point coordinates while retaining their native source class and values.
    pub fn update_numeric_data(
        &mut self,
        x: NumericPlotData,
        y: NumericPlotData,
        z: NumericPlotData,
    ) -> Result<(), String> {
        if x.len() != y.len() || x.len() != z.len() {
            return Err("scatter3 source lengths must match".to_string());
        }
        self.points = x
            .materialize_f64()
            .into_iter()
            .zip(y.materialize_f64())
            .zip(z.materialize_f64())
            .map(|((x, y), z)| Vec3::new(x as f32, y as f32, z as f32))
            .collect();
        self.source_x = Some(x);
        self.source_y = Some(y);
        self.source_z = Some(z);
        self.bounds = None;
        self.invalidate_gpu_vertices();
        self.clear_gpu_source_inputs();
        Ok(())
    }

    /// Build a scatter plot directly from a GPU vertex buffer, bypassing CPU copies.
    pub fn from_gpu_buffer(
        buffer: GpuVertexBuffer,
        point_count: usize,
        style: Scatter3GpuStyle,
        point_size: f32,
        bounds: BoundingBox,
    ) -> Self {
        Self {
            points: Vec::new(),
            colors: vec![style.color],
            point_size,
            point_sizes: None,
            edge_color: style.edge_color,
            edge_thickness: style.edge_thickness,
            marker_style: style.marker_style,
            filled: style.filled,
            edge_color_from_vertex_colors: style.edge_from_vertex_colors,
            label: None,
            visible: true,
            source_x: None,
            source_y: None,
            source_z: None,
            vertices: None,
            bounds: Some(bounds),
            gpu_vertices: Some(buffer),
            gpu_point_count: Some(point_count),
            gpu_inputs: None,
            gpu_has_per_point_colors: style.has_per_point_colors,
            color_values: None,
            color_limits: None,
        }
    }

    pub fn with_gpu_source_inputs(mut self, inputs: Scatter3GpuInputs) -> Self {
        self.gpu_inputs = Some(inputs);
        self
    }

    pub fn source_data(&self) -> Option<(&NumericPlotData, &NumericPlotData, &NumericPlotData)> {
        match (&self.source_x, &self.source_y, &self.source_z) {
            (Some(x), Some(y), Some(z)) => Some((x, y, z)),
            _ => None,
        }
    }

    pub fn point_count(&self) -> usize {
        self.source_x
            .as_ref()
            .map(NumericPlotData::len)
            .or_else(|| self.gpu_inputs.as_ref().map(|input| input.len as usize))
            .or(self.gpu_point_count)
            .unwrap_or(self.points.len())
    }

    pub fn has_resident_size_source(&self) -> bool {
        self.gpu_inputs
            .as_ref()
            .is_some_and(|inputs| inputs.sizes.has_data())
    }

    pub fn has_resident_color_source(&self) -> bool {
        self.gpu_inputs
            .as_ref()
            .is_some_and(|inputs| inputs.colors.has_data())
    }

    fn invalidate_gpu_vertices(&mut self) {
        self.vertices = None;
        self.gpu_vertices = None;
        self.gpu_point_count = None;
    }

    fn clear_gpu_source_inputs(&mut self) {
        self.gpu_inputs = None;
        self.gpu_has_per_point_colors = false;
    }

    /// Override all point colors with a single RGBA value.
    pub fn with_color(mut self, color: Vec4) -> Self {
        self.colors = if self.points.is_empty() {
            vec![color]
        } else {
            vec![color; self.points.len()]
        };
        self.invalidate_gpu_vertices();
        self.gpu_has_per_point_colors = false;
        self
    }

    /// Supply per-point colors. Length must match the number of points.
    pub fn with_colors(mut self, colors: Vec<Vec4>) -> Result<Self, String> {
        if colors.len() != self.points.len() {
            return Err(format!(
                "Point cloud color count ({}) must match point count ({})",
                colors.len(),
                self.points.len()
            ));
        }
        self.colors = colors;
        self.invalidate_gpu_vertices();
        self.clear_gpu_source_inputs();
        Ok(self)
    }

    /// Keep scalar color data so the point colors can be remapped when the colormap changes.
    pub fn with_color_values(mut self, values: Vec<f64>, limits: Option<(f64, f64)>) -> Self {
        if values.len() == self.points.len() {
            self.color_values = Some(values);
            self.color_limits = limits;
        }
        self
    }

    /// Map scalar color data (`C`) through `cmap`; RGB colors are left as they are.
    pub fn recolor_with_colormap(&mut self, cmap: &crate::plots::surface::ColorMap) {
        let Some(values) = self.color_values.as_ref() else {
            return;
        };
        let (lo, hi) = self.color_limits.unwrap_or_else(|| {
            values
                .iter()
                .filter(|v| v.is_finite())
                .fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), &v| {
                    (a.min(v), b.max(v))
                })
        });
        let span = if hi > lo { hi - lo } else { 1.0 };
        let colors: Vec<Vec4> = values
            .iter()
            .zip(&self.colors)
            .map(|(&v, old)| {
                let t = if v.is_finite() {
                    ((v - lo) / span).clamp(0.0, 1.0)
                } else {
                    0.0
                };
                let rgb = cmap.map_value(t as f32);
                Vec4::new(rgb.x, rgb.y, rgb.z, old.w)
            })
            .collect();
        self.colors = colors;
        self.invalidate_gpu_vertices();
        self.clear_gpu_source_inputs();
    }

    /// Set the legend label.
    pub fn with_label<S: Into<String>>(mut self, label: S) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Set marker size in pixels.
    pub fn with_point_size(mut self, size: f32) -> Self {
        self.point_size = size.max(1.0);
        self.point_sizes = None;
        self.invalidate_gpu_vertices();
        self
    }

    pub fn set_marker_style(&mut self, style: MarkerStyle) {
        self.marker_style = style;
        self.invalidate_gpu_vertices();
    }

    pub fn set_filled(&mut self, filled: bool) {
        self.filled = filled;
        self.invalidate_gpu_vertices();
    }

    pub fn set_edge_color(&mut self, color: Vec4) {
        self.edge_color = color;
        self.invalidate_gpu_vertices();
    }

    pub fn set_edge_thickness(&mut self, px: f32) {
        self.edge_thickness = px.max(0.0);
        self.invalidate_gpu_vertices();
    }

    pub fn set_edge_color_from_vertex(&mut self, enabled: bool) {
        self.edge_color_from_vertex_colors = enabled;
        self.invalidate_gpu_vertices();
    }

    /// Enable or disable visibility.
    pub fn set_visible(&mut self, visible: bool) {
        self.visible = visible;
    }

    /// Attach a GPU-resident vertex buffer that already encodes this point cloud in the renderer's vertex format.
    /// When provided, the renderer can skip per-frame uploads and reuse the supplied buffer directly.
    pub fn with_gpu_vertices(mut self, buffer: GpuVertexBuffer, point_count: usize) -> Self {
        self.gpu_vertices = Some(buffer);
        self.gpu_point_count = Some(point_count);
        self.vertices = None;
        self.clear_gpu_source_inputs();
        self
    }

    /// Supply per-point sizes in pixels.
    pub fn set_point_sizes(&mut self, sizes: Vec<f32>) {
        self.point_sizes = Some(sizes);
        self.invalidate_gpu_vertices();
    }

    fn ensure_vertices(&mut self) {
        if self.vertices.is_none() {
            let mut verts = vertex_utils::create_point_cloud(&self.points, &self.colors);
            if let Some(sizes) = self.point_sizes.as_ref() {
                for (idx, vertex) in verts.iter_mut().enumerate() {
                    let size = sizes.get(idx).copied().unwrap_or(self.point_size);
                    vertex.normal[2] = size;
                }
            } else {
                for vertex in &mut verts {
                    vertex.normal[2] = self.point_size;
                }
            }
            self.vertices = Some(verts);
        }
    }

    fn ensure_bounds(&mut self) {
        if self.bounds.is_none() {
            self.bounds = Some(BoundingBox::from_points(&self.points));
        }
    }

    /// Estimate memory required for this plot.
    pub fn estimated_memory_usage(&self) -> usize {
        let gpu_bytes = self
            .gpu_point_count
            .map(|count| count * std::mem::size_of::<Vertex>())
            .unwrap_or(0);
        self.points.len() * std::mem::size_of::<Vec3>()
            + self.colors.len() * std::mem::size_of::<Vec4>()
            + self
                .point_sizes
                .as_ref()
                .map(|sizes| sizes.len() * std::mem::size_of::<f32>())
                .unwrap_or(0)
            + gpu_bytes
            + self
                .source_x
                .as_ref()
                .map_or(0, NumericPlotData::estimated_byte_len)
            + self
                .source_y
                .as_ref()
                .map_or(0, NumericPlotData::estimated_byte_len)
            + self
                .source_z
                .as_ref()
                .map_or(0, NumericPlotData::estimated_byte_len)
    }

    /// Generate render data for the renderer.
    pub fn render_data(&mut self) -> RenderData {
        let bounds = self.bounds();
        let vertex_count = self.gpu_point_count.unwrap_or_else(|| {
            self.ensure_vertices();
            self.vertices
                .as_ref()
                .map(|v| v.len())
                .unwrap_or(self.points.len())
        });

        let vertices = if self.gpu_vertices.is_some() {
            Vec::new()
        } else {
            self.ensure_vertices();
            self.vertices.clone().unwrap_or_default()
        };

        let is_multi_color = if self.gpu_vertices.is_some() {
            self.gpu_has_per_point_colors || self.colors.len() > 1
        } else if vertices.is_empty() {
            false
        } else {
            let first = vertices[0].color;
            vertices.iter().any(|v| v.color != first)
        };
        let has_vertex_colors = if self.gpu_vertices.is_some() {
            self.gpu_has_per_point_colors
        } else {
            self.colors.len() > 1
        };
        let use_vertex_edge_color = self.edge_color_from_vertex_colors && has_vertex_colors;
        let mut material = Material {
            albedo: self.colors.first().copied().unwrap_or(Vec4::ONE),
            roughness: self.edge_thickness,
            metallic: match self.marker_style {
                MarkerStyle::Circle => 0.0,
                MarkerStyle::Square => 1.0,
                MarkerStyle::Triangle => 2.0,
                MarkerStyle::Diamond => 3.0,
                MarkerStyle::Plus => 4.0,
                MarkerStyle::Cross => 5.0,
                MarkerStyle::Star => 6.0,
                MarkerStyle::Hexagon => 7.0,
            },
            emissive: self.edge_color,
            alpha_mode: crate::core::scene::AlphaMode::Blend,
            double_sided: true,
        };
        if is_multi_color {
            material.albedo.w = 0.0;
        } else if self.filled {
            material.albedo.w = 1.0;
        }
        material.emissive.w = if use_vertex_edge_color { 0.0 } else { 1.0 };

        RenderData {
            pipeline_type: PipelineType::Scatter3,
            vertices,
            indices: None,
            gpu_vertices: self.gpu_vertices.clone(),
            bounds: Some(bounds),
            material,
            draw_calls: vec![DrawCall {
                vertex_offset: 0,
                vertex_count,
                index_offset: None,
                index_count: None,
                instance_count: 1,
            }],
            image: None,
        }
    }

    /// Compute the axis-aligned bounding box.
    pub fn bounds(&mut self) -> BoundingBox {
        self.ensure_bounds();
        self.bounds.unwrap_or_default()
    }

    pub(crate) fn retained_snapshot_bytes(&self) -> Option<usize> {
        let mut total = self.label.as_ref().map_or(0, String::capacity);
        for bytes in [
            crate::plots::clone_budget::vec::<Vec3>(self.points.capacity())?,
            crate::plots::clone_budget::vec::<Vec4>(self.colors.capacity())?,
            crate::plots::clone_budget::vec::<f32>(
                self.point_sizes.as_ref().map_or(0, Vec::capacity),
            )?,
            crate::plots::clone_budget::vec::<f64>(
                self.color_values.as_ref().map_or(0, Vec::capacity),
            )?,
            crate::plots::clone_budget::vec::<Vertex>(
                self.vertices.as_ref().map_or(0, Vec::capacity),
            )?,
        ] {
            crate::plots::clone_budget::add(&mut total, bytes)?;
        }
        for source in [&self.source_x, &self.source_y, &self.source_z]
            .into_iter()
            .flatten()
        {
            crate::plots::clone_budget::add(&mut total, source.retained_snapshot_bytes()?)?;
        }
        if let Some(inputs) = &self.gpu_inputs {
            if let ScatterAttributeBuffer::Host(sizes) = &inputs.sizes {
                crate::plots::clone_budget::add(
                    &mut total,
                    crate::plots::clone_budget::vec::<f32>(sizes.capacity())?,
                )?;
            }
            if let crate::gpu::scatter2::ScatterColorBuffer::Host(colors) = &inputs.colors {
                crate::plots::clone_budget::add(
                    &mut total,
                    crate::plots::clone_budget::vec::<[f32; 4]>(colors.capacity())?,
                )?;
            }
        }
        Some(total)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn scatter3_defaults() {
        let points = vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 2.0, 3.0)];
        let cloud = Scatter3Plot::new(points.clone()).unwrap();
        assert_eq!(cloud.points.len(), points.len());
        assert_eq!(cloud.colors.len(), points.len());
        assert!(cloud.visible);
    }

    #[test]
    fn scatter3_custom_colors() {
        let points = vec![Vec3::new(0.0, 0.0, 0.0)];
        let colors = vec![Vec4::new(1.0, 0.0, 0.0, 1.0)];
        let cloud = Scatter3Plot::new(points)
            .unwrap()
            .with_colors(colors)
            .unwrap();
        assert_eq!(cloud.colors[0], Vec4::new(1.0, 0.0, 0.0, 1.0));
    }

    #[test]
    fn scatter3_render_data_contains_vertices() {
        let points = vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 1.0)];
        let mut cloud = Scatter3Plot::new(points).unwrap();
        let render_data = cloud.render_data();
        assert_eq!(render_data.vertices.len(), 2);
        assert_eq!(render_data.pipeline_type, PipelineType::Scatter3);
    }

    #[test]
    fn scatter3_marker_style_encodes_material_shape_channel() {
        let points = vec![Vec3::new(0.0, 0.0, 0.0)];
        let mut cloud = Scatter3Plot::new(points).unwrap();
        cloud.set_marker_style(MarkerStyle::Diamond);
        let render_data = cloud.render_data();
        assert_eq!(render_data.material.metallic, 3.0);
    }

    #[test]
    fn scatter3_default_material_uses_plot_color_not_white_override() {
        let points = vec![Vec3::new(0.0, 0.0, 0.0)];
        let mut cloud = Scatter3Plot::new(points).unwrap();
        let render_data = cloud.render_data();
        assert_ne!(render_data.material.albedo.truncate(), Vec4::ONE.truncate());
    }
}