runmat-plot 0.0.17

GPU-accelerated and static plotting for RunMat with WGPU and Plotters
Documentation
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
//! 3D point cloud visualization
//!
//! High-performance GPU-accelerated 3D point cloud rendering for scatter data.

use crate::core::{BoundingBox, DrawCall, Material, PipelineType, RenderData, Vertex};
use crate::plots::surface::ColorMap;
use glam::{Vec3, Vec4};

/// Point cloud plot for 3D scatter data
#[derive(Debug, Clone)]
pub struct PointCloudPlot {
    /// Point positions
    pub positions: Vec<Vec3>,

    /// Per-point data
    pub values: Option<Vec<f64>>,
    pub colors: Option<Vec<Vec4>>,
    pub sizes: Option<Vec<f32>>,

    /// Global styling
    pub default_color: Vec4,
    pub default_size: f32,
    pub colormap: ColorMap,

    /// Point rendering
    pub point_style: PointStyle,
    pub size_mode: SizeMode,

    /// Metadata
    pub label: Option<String>,
    pub visible: bool,

    /// Generated rendering data (cached)
    vertices: Option<Vec<Vertex>>,
    bounds: Option<BoundingBox>,
    dirty: bool,
}

/// Point rendering styles
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PointStyle {
    /// Circular points
    Circle,
    /// Square points
    Square,
    /// 3D spheres (higher quality)
    Sphere,
    /// Custom mesh
    Custom,
}

/// Point size modes
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SizeMode {
    /// Fixed size for all points
    Fixed,
    /// Size proportional to value
    Proportional,
    /// Size scaled by distance from camera
    Perspective,
}

impl Default for PointStyle {
    fn default() -> Self {
        Self::Circle
    }
}

impl Default for SizeMode {
    fn default() -> Self {
        Self::Fixed
    }
}

impl PointCloudPlot {
    /// Create a new point cloud from positions
    pub fn new(positions: Vec<Vec3>) -> Self {
        Self {
            positions,
            values: None,
            colors: None,
            sizes: None,
            default_color: Vec4::new(0.0, 0.5, 1.0, 1.0), // Blue
            default_size: 3.0,
            colormap: ColorMap::Viridis,
            point_style: PointStyle::default(),
            size_mode: SizeMode::default(),
            label: None,
            visible: true,
            vertices: None,
            bounds: None,
            dirty: true,
        }
    }

    /// Create point cloud with values for color mapping
    pub fn with_values(mut self, values: Vec<f64>) -> Result<Self, String> {
        if values.len() != self.positions.len() {
            return Err(format!(
                "Values length ({}) must match positions length ({})",
                values.len(),
                self.positions.len()
            ));
        }
        self.values = Some(values);
        self.dirty = true;
        Ok(self)
    }

    /// Create point cloud with explicit colors
    pub fn with_colors(mut self, colors: Vec<Vec4>) -> Result<Self, String> {
        if colors.len() != self.positions.len() {
            return Err(format!(
                "Colors length ({}) must match positions length ({})",
                colors.len(),
                self.positions.len()
            ));
        }
        self.colors = Some(colors);
        self.dirty = true;
        Ok(self)
    }

    /// Create point cloud with variable sizes
    pub fn with_sizes(mut self, sizes: Vec<f32>) -> Result<Self, String> {
        if sizes.len() != self.positions.len() {
            return Err(format!(
                "Sizes length ({}) must match positions length ({})",
                sizes.len(),
                self.positions.len()
            ));
        }
        self.sizes = Some(sizes);
        self.dirty = true;
        Ok(self)
    }

    /// Set default color for all points
    pub fn with_default_color(mut self, color: Vec4) -> Self {
        self.default_color = color;
        self.dirty = true;
        self
    }

    /// Set default size for all points
    pub fn with_default_size(mut self, size: f32) -> Self {
        self.default_size = size.max(0.1);
        self.dirty = true;
        self
    }

    /// Set colormap for value-based coloring
    pub fn with_colormap(mut self, colormap: ColorMap) -> Self {
        self.colormap = colormap;
        self.dirty = true;
        self
    }

    /// Set point rendering style
    pub fn with_point_style(mut self, style: PointStyle) -> Self {
        self.point_style = style;
        self.dirty = true;
        self
    }

    /// Set size mode
    pub fn with_size_mode(mut self, mode: SizeMode) -> Self {
        self.size_mode = mode;
        self.dirty = true;
        self
    }

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

    /// Get the number of points
    pub fn len(&self) -> usize {
        self.positions.len()
    }

    /// Check if the point cloud has no data
    pub fn is_empty(&self) -> bool {
        self.positions.is_empty()
    }

    /// Generate vertices for GPU rendering
    pub fn generate_vertices(&mut self) -> &Vec<Vertex> {
        if self.dirty || self.vertices.is_none() {
            self.compute_vertices();
            self.dirty = false;
        }
        self.vertices.as_ref().unwrap()
    }

    /// Get the bounding box of the point cloud
    pub fn bounds(&mut self) -> BoundingBox {
        if self.dirty || self.bounds.is_none() {
            self.compute_bounds();
        }
        self.bounds.unwrap()
    }

    /// Compute vertices
    fn compute_vertices(&mut self) {
        let mut vertices = Vec::with_capacity(self.positions.len());

        // Compute value range for color mapping
        let (value_min, value_max) = if let Some(ref values) = self.values {
            let min = values.iter().copied().fold(f64::INFINITY, f64::min);
            let max = values.iter().copied().fold(f64::NEG_INFINITY, f64::max);
            (min, max)
        } else {
            (0.0, 1.0)
        };

        for (i, &position) in self.positions.iter().enumerate() {
            // Determine color
            let color = if let Some(ref colors) = self.colors {
                colors[i]
            } else if let Some(ref values) = self.values {
                let normalized = if value_max > value_min {
                    ((values[i] - value_min) / (value_max - value_min)).clamp(0.0, 1.0)
                } else {
                    0.5
                };
                let rgb = self.colormap.map_value(normalized as f32);
                Vec4::new(rgb.x, rgb.y, rgb.z, self.default_color.w)
            } else {
                self.default_color
            };

            // Determine size (encoded in normal.x for now)
            let size = if let Some(ref sizes) = self.sizes {
                sizes[i]
            } else {
                match self.size_mode {
                    SizeMode::Fixed => self.default_size,
                    SizeMode::Proportional => {
                        if let Some(ref values) = self.values {
                            let normalized = if value_max > value_min {
                                ((values[i] - value_min) / (value_max - value_min)).clamp(0.0, 1.0)
                            } else {
                                0.5
                            };
                            self.default_size * (0.5 + normalized as f32)
                        } else {
                            self.default_size
                        }
                    }
                    SizeMode::Perspective => self.default_size, // Camera distance handled in shader
                }
            };

            vertices.push(Vertex {
                position: position.to_array(),
                color: color.to_array(),
                normal: [size, 0.0, 0.0],    // Store size in normal.x
                tex_coords: [i as f32, 0.0], // Point index for potential lookup
            });
        }

        self.vertices = Some(vertices);
    }

    /// Compute bounding box
    fn compute_bounds(&mut self) {
        if self.positions.is_empty() {
            self.bounds = Some(BoundingBox::new(Vec3::ZERO, Vec3::ZERO));
            return;
        }

        let mut min = self.positions[0];
        let mut max = self.positions[0];

        for &pos in &self.positions[1..] {
            min = min.min(pos);
            max = max.max(pos);
        }

        // Expand bounds slightly to account for point size
        let expansion = Vec3::splat(self.default_size * 0.01);
        min -= expansion;
        max += expansion;

        self.bounds = Some(BoundingBox::new(min, max));
    }

    /// Generate complete render data for the graphics pipeline
    pub fn render_data(&mut self) -> RenderData {
        println!(
            "DEBUG: PointCloudPlot::render_data() called with {} points",
            self.positions.len()
        );

        let vertices = self.generate_vertices().clone();
        let vertex_count = vertices.len();

        println!("DEBUG: Generated {vertex_count} vertices for point cloud");

        let material = Material {
            albedo: self.default_color,
            ..Default::default()
        };

        let draw_call = DrawCall {
            vertex_offset: 0,
            vertex_count,
            index_offset: None,
            index_count: None,
            instance_count: 1,
        };

        println!("DEBUG: PointCloudPlot render_data completed successfully");

        RenderData {
            pipeline_type: PipelineType::Points,
            vertices,
            indices: None,
            material,
            draw_calls: vec![draw_call],
        }
    }

    /// Get plot statistics for debugging
    pub fn statistics(&self) -> PointCloudStatistics {
        PointCloudStatistics {
            point_count: self.positions.len(),
            has_values: self.values.is_some(),
            has_colors: self.colors.is_some(),
            has_sizes: self.sizes.is_some(),
            memory_usage: self.estimated_memory_usage(),
        }
    }

    /// Estimate memory usage in bytes
    pub fn estimated_memory_usage(&self) -> usize {
        let positions_size = self.positions.len() * std::mem::size_of::<Vec3>();
        let values_size = self
            .values
            .as_ref()
            .map_or(0, |v| v.len() * std::mem::size_of::<f64>());
        let colors_size = self
            .colors
            .as_ref()
            .map_or(0, |c| c.len() * std::mem::size_of::<Vec4>());
        let sizes_size = self
            .sizes
            .as_ref()
            .map_or(0, |s| s.len() * std::mem::size_of::<f32>());
        let vertices_size = self
            .vertices
            .as_ref()
            .map_or(0, |v| v.len() * std::mem::size_of::<Vertex>());

        positions_size + values_size + colors_size + sizes_size + vertices_size
    }
}

/// Point cloud performance and data statistics
#[derive(Debug, Clone)]
pub struct PointCloudStatistics {
    pub point_count: usize,
    pub has_values: bool,
    pub has_colors: bool,
    pub has_sizes: bool,
    pub memory_usage: usize,
}

/// MATLAB-compatible point cloud creation utilities
pub mod matlab_compat {
    use super::*;

    /// Create a 3D scatter plot (equivalent to MATLAB's `scatter3(x, y, z)`)
    pub fn scatter3(x: Vec<f64>, y: Vec<f64>, z: Vec<f64>) -> Result<PointCloudPlot, String> {
        if x.len() != y.len() || y.len() != z.len() {
            return Err("X, Y, and Z vectors must have the same length".to_string());
        }

        let positions: Vec<Vec3> = x
            .into_iter()
            .zip(y)
            .zip(z)
            .map(|((x, y), z)| Vec3::new(x as f32, y as f32, z as f32))
            .collect();

        Ok(PointCloudPlot::new(positions))
    }

    /// Create scatter3 with colors
    pub fn scatter3_with_colors(
        x: Vec<f64>,
        y: Vec<f64>,
        z: Vec<f64>,
        colors: Vec<Vec4>,
    ) -> Result<PointCloudPlot, String> {
        scatter3(x, y, z)?.with_colors(colors)
    }

    /// Create scatter3 with values for color mapping
    pub fn scatter3_with_values(
        x: Vec<f64>,
        y: Vec<f64>,
        z: Vec<f64>,
        values: Vec<f64>,
        colormap: &str,
    ) -> Result<PointCloudPlot, String> {
        let cmap = match colormap {
            "jet" => ColorMap::Jet,
            "hot" => ColorMap::Hot,
            "cool" => ColorMap::Cool,
            "viridis" => ColorMap::Viridis,
            "plasma" => ColorMap::Plasma,
            "gray" | "grey" => ColorMap::Gray,
            _ => return Err(format!("Unknown colormap: {colormap}")),
        };

        Ok(scatter3(x, y, z)?.with_values(values)?.with_colormap(cmap))
    }

    /// Create point cloud from matrix data
    pub fn point_cloud_from_matrix(points: Vec<Vec<f64>>) -> Result<PointCloudPlot, String> {
        if points.is_empty() {
            return Err("Points matrix cannot be empty".to_string());
        }

        let dim = points[0].len();
        if dim < 3 {
            return Err("Points must have at least 3 dimensions (X, Y, Z)".to_string());
        }

        let positions: Vec<Vec3> = points
            .into_iter()
            .map(|point| {
                if point.len() != dim {
                    Vec3::ZERO // Handle inconsistent dimensions gracefully
                } else {
                    Vec3::new(point[0] as f32, point[1] as f32, point[2] as f32)
                }
            })
            .collect();

        Ok(PointCloudPlot::new(positions))
    }
}

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

    #[test]
    fn test_point_cloud_creation() {
        let positions = vec![
            Vec3::new(0.0, 0.0, 0.0),
            Vec3::new(1.0, 1.0, 1.0),
            Vec3::new(2.0, 2.0, 2.0),
        ];

        let cloud = PointCloudPlot::new(positions.clone());

        assert_eq!(cloud.positions, positions);
        assert_eq!(cloud.len(), 3);
        assert!(!cloud.is_empty());
        assert!(cloud.visible);
        assert!(cloud.values.is_none());
        assert!(cloud.colors.is_none());
        assert!(cloud.sizes.is_none());
    }

    #[test]
    fn test_point_cloud_with_values() {
        let positions = vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 1.0)];
        let values = vec![0.5, 1.5];

        let cloud = PointCloudPlot::new(positions)
            .with_values(values.clone())
            .unwrap();

        assert_eq!(cloud.values, Some(values));
    }

    #[test]
    fn test_point_cloud_with_colors() {
        let positions = vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 1.0)];
        let colors = vec![Vec4::new(1.0, 0.0, 0.0, 1.0), Vec4::new(0.0, 1.0, 0.0, 1.0)];

        let cloud = PointCloudPlot::new(positions)
            .with_colors(colors.clone())
            .unwrap();

        assert_eq!(cloud.colors, Some(colors));
    }

    #[test]
    fn test_point_cloud_validation() {
        let positions = vec![Vec3::new(0.0, 0.0, 0.0)];
        let wrong_values = vec![1.0, 2.0]; // Length mismatch

        let result = PointCloudPlot::new(positions).with_values(wrong_values);
        assert!(result.is_err());
    }

    #[test]
    fn test_point_cloud_styling() {
        let positions = vec![Vec3::new(0.0, 0.0, 0.0)];

        let cloud = PointCloudPlot::new(positions)
            .with_default_color(Vec4::new(1.0, 0.0, 0.0, 1.0))
            .with_default_size(5.0)
            .with_colormap(ColorMap::Hot)
            .with_point_style(PointStyle::Sphere)
            .with_size_mode(SizeMode::Proportional)
            .with_label("Test Cloud");

        assert_eq!(cloud.default_color, Vec4::new(1.0, 0.0, 0.0, 1.0));
        assert_eq!(cloud.default_size, 5.0);
        assert_eq!(cloud.colormap, ColorMap::Hot);
        assert_eq!(cloud.point_style, PointStyle::Sphere);
        assert_eq!(cloud.size_mode, SizeMode::Proportional);
        assert_eq!(cloud.label, Some("Test Cloud".to_string()));
    }

    #[test]
    fn test_point_cloud_bounds() {
        let positions = vec![
            Vec3::new(-1.0, -2.0, -3.0),
            Vec3::new(1.0, 2.0, 3.0),
            Vec3::new(0.0, 0.0, 0.0),
        ];

        let mut cloud = PointCloudPlot::new(positions);
        let bounds = cloud.bounds();

        // Should be slightly expanded from actual bounds
        assert!(bounds.min.x <= -1.0);
        assert!(bounds.min.y <= -2.0);
        assert!(bounds.min.z <= -3.0);
        assert!(bounds.max.x >= 1.0);
        assert!(bounds.max.y >= 2.0);
        assert!(bounds.max.z >= 3.0);
    }

    #[test]
    fn test_point_cloud_vertex_generation() {
        let positions = vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 1.0)];

        let mut cloud = PointCloudPlot::new(positions);
        let vertices = cloud.generate_vertices();

        assert_eq!(vertices.len(), 2);
        assert_eq!(vertices[0].position, [0.0, 0.0, 0.0]);
        assert_eq!(vertices[1].position, [1.0, 1.0, 1.0]);
    }

    #[test]
    fn test_point_cloud_statistics() {
        let positions = vec![
            Vec3::new(0.0, 0.0, 0.0),
            Vec3::new(1.0, 1.0, 1.0),
            Vec3::new(2.0, 2.0, 2.0),
        ];
        let values = vec![0.0, 1.0, 2.0];

        let cloud = PointCloudPlot::new(positions).with_values(values).unwrap();

        let stats = cloud.statistics();

        assert_eq!(stats.point_count, 3);
        assert!(stats.has_values);
        assert!(!stats.has_colors);
        assert!(!stats.has_sizes);
        assert!(stats.memory_usage > 0);
    }

    #[test]
    fn test_matlab_compat() {
        use super::matlab_compat::*;

        let x = vec![0.0, 1.0, 2.0];
        let y = vec![0.0, 1.0, 2.0];
        let z = vec![0.0, 1.0, 2.0];

        let cloud = scatter3(x.clone(), y.clone(), z.clone()).unwrap();
        assert_eq!(cloud.len(), 3);

        let values = vec![0.0, 0.5, 1.0];
        let cloud_with_values = scatter3_with_values(x, y, z, values, "viridis").unwrap();
        assert!(cloud_with_values.values.is_some());
        assert_eq!(cloud_with_values.colormap, ColorMap::Viridis);
    }
}