use crate::core::{BoundingBox, GpuPackContext, RenderData};
use crate::plots::surface::ColorMap;
use crate::plots::{
AreaPlot, BarChart, ContourFillPlot, ContourPlot, ErrorBar, Line3Plot, LinePlot, MeshPlot,
PatchPlot, PieChart, QuiverPlot, ReferenceLine, ReferenceLineOrientation, Scatter3Plot,
ScatterPlot, StairsPlot, StemPlot, SurfacePlot,
};
use glam::Vec4;
use log::trace;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[path = "figure/axes_reset.rs"]
mod axes_reset;
#[path = "figure/colormap.rs"]
mod colormap;
#[path = "figure/color_range.rs"]
mod color_range;
#[path = "figure/y_direction.rs"]
mod y_direction;
#[path = "figure/geometry_source.rs"]
mod geometry_source;
pub use y_direction::YDirection;
#[path = "figure/dimensionality.rs"]
mod dimensionality;
#[path = "figure/limits.rs"]
mod limits;
#[path = "figure/preparation.rs"]
mod preparation;
#[path = "figure/persistence_projection/mod.rs"]
mod persistence_projection;
pub use limits::{
display_bounds_3d, positive_log_bounds, resolve_axis_bounds, AxisLimitAxis, AxisLimitMethod,
};
pub use persistence_projection::project_figure_for_persistence;
pub use persistence_projection::{
FigureAnnotationRemap, FigureAxesContainerSelection, FigureAxesPersistenceSelection,
FigureAxesRemap, FigureAxesSelectionKind, FigureDecoration, FigureDecorationRemap,
FigurePersistenceProjection, FigurePersistenceProjectionError, FigurePersistenceSelection,
FigurePlotRemap, FigureProjectionRemap,
};
type ViewBounds2D = (f64, f64, f64, f64);
type PerAxesViewBoundsRef<'a> = &'a [Option<ViewBounds2D>];
#[derive(Debug, Clone)]
pub struct Figure {
plots: Vec<PlotElement>,
pub name: Option<String>,
pub number_title: bool,
pub visible: bool,
pub position: [f64; 4],
pub title: Option<String>,
pub sg_title: Option<String>,
pub x_label: Option<String>,
pub y_label: Option<String>,
pub z_label: Option<String>,
pub legend_enabled: bool,
pub grid_enabled: bool,
pub minor_grid_enabled: bool,
pub box_enabled: bool,
pub background_color: Vec4,
pub x_limits: Option<(f64, f64)>,
pub y_limits: Option<(f64, f64)>,
pub z_limits: Option<(f64, f64)>,
pub x_log: bool,
pub y_log: bool,
pub axis_equal: bool,
pub colormap: ColorMap,
pub default_colormap: ColorMap,
pub default_colormap_length: usize,
pub colorbar_enabled: bool,
pub color_limits: Option<(f64, f64)>,
bounds: Option<BoundingBox>,
dirty: bool,
pub axes_rows: usize,
pub axes_cols: usize,
plot_axes_indices: Vec<usize>,
axes_grid_cells: Vec<Option<AxesGridCell>>,
pub active_axes_index: usize,
pub axes_metadata: Vec<AxesMetadata>,
pub sg_title_style: TextStyle,
geometry_source: Option<std::sync::Arc<crate::geometry_scene::GeometryScene>>,
}
#[derive(Debug, Clone)]
pub struct TextStyle {
pub color: Option<Vec4>,
pub font_size: Option<f32>,
pub font_weight: Option<String>,
pub font_angle: Option<String>,
pub interpreter: Option<String>,
pub visible: bool,
pub horizontal_alignment: Option<String>,
pub vertical_alignment: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AxesGridCell {
pub rows: u32,
pub columns: u32,
pub index: u32,
}
impl Default for TextStyle {
fn default() -> Self {
Self {
color: None,
font_size: None,
font_weight: None,
font_angle: None,
interpreter: None,
visible: true,
horizontal_alignment: None,
vertical_alignment: None,
}
}
}
impl TextStyle {
fn retained_snapshot_bytes(&self) -> Option<usize> {
let mut total = 0usize;
for value in [
self.font_weight.as_ref(),
self.font_angle.as_ref(),
self.interpreter.as_ref(),
]
.into_iter()
.flatten()
{
crate::plots::clone_budget::add(&mut total, value.capacity())?;
}
Some(total)
}
}
#[derive(Debug, Clone)]
pub struct LegendStyle {
pub location: Option<String>,
pub visible: bool,
pub font_size: Option<f32>,
pub font_weight: Option<String>,
pub font_angle: Option<String>,
pub interpreter: Option<String>,
pub box_visible: Option<bool>,
pub orientation: Option<String>,
pub text_color: Option<Vec4>,
}
impl Default for LegendStyle {
fn default() -> Self {
Self {
location: None,
visible: true,
font_size: None,
font_weight: None,
font_angle: None,
interpreter: None,
box_visible: None,
orientation: None,
text_color: None,
}
}
}
impl LegendStyle {
fn retained_snapshot_bytes(&self) -> Option<usize> {
let mut total = 0usize;
for value in [
self.location.as_ref(),
self.font_weight.as_ref(),
self.font_angle.as_ref(),
self.interpreter.as_ref(),
self.orientation.as_ref(),
]
.into_iter()
.flatten()
{
crate::plots::clone_budget::add(&mut total, value.capacity())?;
}
Some(total)
}
}
#[derive(Debug, Clone, Default)]
pub struct AxesMetadata {
pub colormap_length: usize,
pub y_direction: YDirection,
pub axes_kind: AxesKind,
pub overlay_parent: Option<usize>,
pub y_axis_location: String,
pub position: [f64; 4],
pub position_explicit: bool,
pub units: String,
pub title: Option<String>,
pub subtitle: Option<String>,
pub x_label: Option<String>,
pub y_label: Option<String>,
pub z_label: Option<String>,
pub x_ticks: Option<Vec<f64>>,
pub y_ticks: Option<Vec<f64>>,
pub x_tick_labels: Option<Vec<String>>,
pub y_tick_labels: Option<Vec<String>>,
pub x_tick_format: Option<String>,
pub y_tick_format: Option<String>,
pub x_tick_label_rotation: Option<f64>,
pub y_tick_label_rotation: Option<f64>,
pub x_limits: Option<(f64, f64)>,
pub y_limits: Option<(f64, f64)>,
pub z_limits: Option<(f64, f64)>,
pub x_limit_method: AxisLimitMethod,
pub y_limit_method: AxisLimitMethod,
pub z_limit_method: AxisLimitMethod,
pub x_log: bool,
pub y_log: bool,
pub view_azimuth_deg: Option<f32>,
pub view_elevation_deg: Option<f32>,
pub view_revision: u64,
pub grid_enabled: bool,
pub minor_grid_enabled: bool,
pub minor_grid_explicit: bool,
pub hidden_line_removal: bool,
pub box_enabled: bool,
pub axis_equal: bool,
pub data_aspect_ratio: [f64; 3],
pub data_aspect_ratio_mode: String,
pub legend_enabled: bool,
pub colorbar_enabled: bool,
pub colormap: ColorMap,
pub color_order: Option<Vec<Vec4>>,
pub color_limits: Option<(f64, f64)>,
pub axes_style: TextStyle,
pub title_style: TextStyle,
pub subtitle_style: TextStyle,
pub x_label_style: TextStyle,
pub y_label_style: TextStyle,
pub z_label_style: TextStyle,
pub legend_style: LegendStyle,
pub world_text_annotations: Vec<TextAnnotation>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AxesKind {
#[default]
Cartesian,
Polar,
}
#[derive(Debug, Clone)]
pub struct TextAnnotation {
pub position: glam::Vec3,
pub text: String,
pub style: TextStyle,
}
impl AxesMetadata {
fn retained_snapshot_bytes(&self) -> Option<usize> {
let mut total = 0usize;
crate::plots::clone_budget::add(&mut total, self.colormap.retained_snapshot_bytes()?)?;
for value in [
Some(&self.y_axis_location),
Some(&self.units),
self.title.as_ref(),
self.subtitle.as_ref(),
self.x_label.as_ref(),
self.y_label.as_ref(),
self.z_label.as_ref(),
self.x_tick_format.as_ref(),
self.y_tick_format.as_ref(),
Some(&self.data_aspect_ratio_mode),
]
.into_iter()
.flatten()
{
crate::plots::clone_budget::add(&mut total, value.capacity())?;
}
for values in [&self.x_ticks, &self.y_ticks].into_iter().flatten() {
crate::plots::clone_budget::add(
&mut total,
crate::plots::clone_budget::vec::<f64>(values.capacity())?,
)?;
}
for labels in [&self.x_tick_labels, &self.y_tick_labels]
.into_iter()
.flatten()
{
crate::plots::clone_budget::add(
&mut total,
crate::plots::clone_budget::strings(labels)?,
)?;
}
crate::plots::clone_budget::add(
&mut total,
crate::plots::clone_budget::vec::<Vec4>(
self.color_order.as_ref().map_or(0, Vec::capacity),
)?,
)?;
for style in [
&self.axes_style,
&self.title_style,
&self.subtitle_style,
&self.x_label_style,
&self.y_label_style,
&self.z_label_style,
] {
crate::plots::clone_budget::add(&mut total, style.retained_snapshot_bytes()?)?;
}
crate::plots::clone_budget::add(&mut total, self.legend_style.retained_snapshot_bytes()?)?;
crate::plots::clone_budget::add(
&mut total,
crate::plots::clone_budget::vec::<TextAnnotation>(
self.world_text_annotations.capacity(),
)?,
)?;
for annotation in &self.world_text_annotations {
crate::plots::clone_budget::add(&mut total, annotation.text.capacity())?;
crate::plots::clone_budget::add(
&mut total,
annotation.style.retained_snapshot_bytes()?,
)?;
}
Some(total)
}
}
#[derive(Debug, Clone)]
pub enum PlotElement {
Line(LinePlot),
Scatter(ScatterPlot),
Bar(BarChart),
ErrorBar(Box<ErrorBar>),
Stairs(StairsPlot),
Stem(StemPlot),
Area(AreaPlot),
Quiver(QuiverPlot),
Pie(PieChart),
Surface(SurfacePlot),
Mesh(Box<MeshPlot>),
Patch(PatchPlot),
Line3(Line3Plot),
Scatter3(Scatter3Plot),
Contour(ContourPlot),
ContourFill(ContourFillPlot),
ReferenceLine(ReferenceLine),
}
#[derive(Debug, Clone)]
pub struct LegendEntry {
pub label: String,
pub color: Vec4,
pub plot_type: PlotType,
pub marker: Option<LegendMarker>,
pub line_visible: bool,
pub line_style: crate::plots::line::LineStyle,
}
#[derive(Debug, Clone)]
pub struct LegendMarker {
pub kind: crate::plots::scatter::MarkerStyle,
pub face_color: Vec4,
pub edge_color: Vec4,
pub filled: bool,
}
#[derive(Debug, Clone)]
pub struct PieLabelEntry {
pub label: String,
pub position: glam::Vec2,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PlotType {
Line,
Scatter,
Bar,
ErrorBar,
Stairs,
Stem,
Area,
Quiver,
Pie,
Surface,
Mesh,
Patch,
Line3,
Scatter3,
Contour,
ContourFill,
ReferenceLine,
}
#[path = "figure/metadata_budget.rs"]
mod metadata_budget;
pub use metadata_budget::FigureMetadataOverlay;
impl Figure {
pub fn retained_snapshot_bytes_with_metadata<'a>(
&self,
overlays: impl IntoIterator<Item = FigureMetadataOverlay<'a>>,
) -> Option<usize> {
let current = self.retained_snapshot_bytes()?;
let body = current.checked_sub(self.metadata_overlay().retained_bytes(self)?)?;
let mut maximum: Option<usize> = None;
for overlay in overlays {
let bytes = body.checked_add(overlay.retained_bytes(self)?)?;
maximum = Some(maximum.map_or(bytes, |maximum| maximum.max(bytes)));
}
maximum.or(Some(current))
}
pub fn metadata_overlay(&self) -> FigureMetadataOverlay<'_> {
FigureMetadataOverlay {
name: self.name.as_ref(),
sg_title: self.sg_title.as_ref(),
sg_title_style: &self.sg_title_style,
active_axes: None,
}
}
pub fn retained_snapshot_bytes(&self) -> Option<usize> {
let mut total = crate::plots::clone_budget::vec::<PlotElement>(self.plots.capacity())?;
crate::plots::clone_budget::add(&mut total, self.colormap.retained_snapshot_bytes()?)?;
crate::plots::clone_budget::add(
&mut total,
self.default_colormap.retained_snapshot_bytes()?,
)?;
for value in [
self.name.as_ref(),
self.title.as_ref(),
self.sg_title.as_ref(),
self.x_label.as_ref(),
self.y_label.as_ref(),
self.z_label.as_ref(),
]
.into_iter()
.flatten()
{
crate::plots::clone_budget::add(&mut total, value.capacity())?;
}
crate::plots::clone_budget::add(
&mut total,
crate::plots::clone_budget::vec::<usize>(self.plot_axes_indices.capacity())?,
)?;
crate::plots::clone_budget::add(
&mut total,
crate::plots::clone_budget::vec::<Option<AxesGridCell>>(
self.axes_grid_cells.capacity(),
)?,
)?;
crate::plots::clone_budget::add(
&mut total,
crate::plots::clone_budget::vec::<AxesMetadata>(self.axes_metadata.capacity())?,
)?;
crate::plots::clone_budget::add(
&mut total,
self.sg_title_style.retained_snapshot_bytes()?,
)?;
for plot in &self.plots {
crate::plots::clone_budget::add(&mut total, plot.retained_snapshot_bytes()?)?;
}
for axes in &self.axes_metadata {
crate::plots::clone_budget::add(&mut total, axes.retained_snapshot_bytes()?)?;
}
Some(total)
}
fn default_axes_metadata() -> AxesMetadata {
AxesMetadata {
axes_kind: AxesKind::Cartesian,
overlay_parent: None,
y_axis_location: "left".into(),
position: [0.13, 0.11, 0.775, 0.815],
position_explicit: false,
units: "normalized".into(),
x_limits: None,
y_limits: None,
z_limits: None,
grid_enabled: true,
minor_grid_enabled: false,
hidden_line_removal: true,
box_enabled: true,
axis_equal: false,
data_aspect_ratio: [1.0, 1.0, 1.0],
data_aspect_ratio_mode: "auto".into(),
legend_enabled: false,
colorbar_enabled: false,
colormap: ColorMap::Parula,
colormap_length: 256,
color_limits: None,
..Default::default()
}
}
pub fn new() -> Self {
Self {
plots: Vec::new(),
name: None,
number_title: true,
visible: true,
position: [0.0, 0.0, 560.0, 420.0],
title: None,
sg_title: None,
x_label: None,
y_label: None,
z_label: None,
legend_enabled: false,
grid_enabled: true,
minor_grid_enabled: false,
box_enabled: true,
background_color: Vec4::new(1.0, 1.0, 1.0, 1.0), x_limits: None,
y_limits: None,
z_limits: None,
x_log: false,
y_log: false,
axis_equal: false,
colormap: ColorMap::Parula,
default_colormap: ColorMap::Parula,
default_colormap_length: 256,
colorbar_enabled: false,
color_limits: None,
bounds: None,
dirty: true,
axes_rows: 1,
axes_cols: 1,
plot_axes_indices: Vec::new(),
axes_grid_cells: vec![None],
active_axes_index: 0,
axes_metadata: vec![Self::default_axes_metadata()],
sg_title_style: TextStyle::default(),
geometry_source: None,
}
}
fn ensure_axes_metadata_capacity(&mut self, min_len: usize) {
while self.axes_metadata.len() < min_len.max(1) {
self.axes_metadata.push(self.inherited_axes_metadata());
}
self.axes_grid_cells.resize(self.axes_metadata.len(), None);
}
fn sync_legacy_fields_from_active_axes(&mut self) {
self.ensure_axes_metadata_capacity(self.active_axes_index + 1);
if let Some(meta) = self.axes_metadata.get(self.active_axes_index).cloned() {
self.title = meta.title;
self.x_label = meta.x_label;
self.y_label = meta.y_label;
self.z_label = meta.z_label;
self.x_limits = meta.x_limits;
self.y_limits = meta.y_limits;
self.z_limits = meta.z_limits;
self.x_log = meta.x_log;
self.y_log = meta.y_log;
self.grid_enabled = meta.grid_enabled;
self.box_enabled = meta.box_enabled;
self.axis_equal = meta.axis_equal;
self.legend_enabled = meta.legend_enabled;
self.colorbar_enabled = meta.colorbar_enabled;
self.colormap = meta.colormap.clone();
self.color_limits = meta.color_limits;
}
}
pub fn set_active_axes_index(&mut self, axes_index: usize) {
self.ensure_axes_metadata_capacity(axes_index + 1);
self.active_axes_index = axes_index;
self.sync_legacy_fields_from_active_axes();
self.dirty = true;
}
pub fn ensure_axes(&mut self, axes_index: usize) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.axes_kind = AxesKind::Cartesian;
meta.overlay_parent = None;
}
self.dirty = true;
}
pub fn axes_metadata(&self, axes_index: usize) -> Option<&AxesMetadata> {
self.axes_metadata.get(axes_index)
}
pub fn auto_axes_bounds_2d(
&self,
axes_index: usize,
x: (f64, f64),
y: (f64, f64),
) -> ((f64, f64), (f64, f64)) {
let Some(meta) = self.axes_metadata(axes_index) else {
return (x, y);
};
if meta.axis_equal || meta.data_aspect_ratio_mode == "manual" {
return (x, y);
}
let mut lines_only = false;
for (plot, idx) in self.plots().zip(self.plot_axes_indices().iter().copied()) {
if idx != axes_index {
continue;
}
match plot {
PlotElement::Line(_)
| PlotElement::Scatter(_)
| PlotElement::Stairs(_)
| PlotElement::Stem(_)
| PlotElement::ErrorBar(_) => lines_only = true,
PlotElement::ReferenceLine(_) => {}
_ => return (x, y),
}
}
if !lines_only {
return (x, y);
}
let axis = |(lo, hi): (f64, f64), explicit: Option<(f64, f64)>, log: bool, method| {
if explicit.is_some() || log || !(lo.is_finite() && hi.is_finite() && lo < hi) {
(lo, hi)
} else {
resolve_axis_bounds(lo, hi, None, method)
}
};
(
axis(x, meta.x_limits, meta.x_log, meta.x_limit_method),
axis(y, meta.y_limits, meta.y_log, meta.y_limit_method),
)
}
pub fn axes_grid_cell(&self, axes_index: usize) -> Option<AxesGridCell> {
self.axes_grid_cells.get(axes_index).copied().flatten()
}
pub(crate) fn restore_axes_grid_cells(
&mut self,
cells: Vec<Option<AxesGridCell>>,
) -> Result<(), String> {
if cells.len() > self.axes_metadata.len() {
return Err("axes grid-cell metadata exceeds the axes count".into());
}
for cell in cells.iter().flatten() {
let count = cell
.rows
.checked_mul(cell.columns)
.ok_or_else(|| "axes grid-cell dimensions overflow".to_string())?;
if cell.rows == 0 || cell.columns == 0 || cell.index >= count {
return Err("axes grid-cell metadata is invalid".into());
}
}
self.axes_grid_cells = cells;
self.axes_grid_cells.resize(self.axes_metadata.len(), None);
Ok(())
}
pub fn active_axes_metadata(&self) -> Option<&AxesMetadata> {
self.axes_metadata(self.active_axes_index)
}
pub fn with_sg_title<S: Into<String>>(mut self, title: S) -> Self {
self.set_sg_title(title);
self
}
pub fn set_sg_title<S: Into<String>>(&mut self, title: S) {
self.sg_title = Some(title.into());
self.dirty = true;
}
pub fn clear_sg_title(&mut self) {
self.sg_title = None;
self.dirty = true;
}
pub fn set_sg_title_style(&mut self, style: TextStyle) {
self.sg_title_style = style;
self.dirty = true;
}
pub fn set_name<S: Into<String>>(&mut self, name: S) {
self.name = Some(name.into());
self.dirty = true;
}
pub fn set_number_title(&mut self, enabled: bool) {
self.number_title = enabled;
self.dirty = true;
}
pub fn set_visible(&mut self, visible: bool) {
self.visible = visible;
self.dirty = true;
}
pub fn set_position(&mut self, position: [f64; 4]) {
self.position = position;
self.dirty = true;
}
pub fn window_title(&self, handle: Option<u32>) -> String {
let name = self.name.as_deref().map(str::trim).unwrap_or_default();
let numbered = if self.number_title {
handle.filter(|h| *h > 0).map(|h| format!("Figure {h}"))
} else {
None
};
match (numbered, name.is_empty()) {
(Some(numbered), false) => format!("{numbered}: {name}"),
(Some(numbered), true) => numbered,
(None, false) => name.to_string(),
(None, true) => "RunMat Plot".to_string(),
}
}
pub fn has_any_titles(&self) -> bool {
let non_empty = |s: Option<&str>| s.map(str::trim).is_some_and(|t| !t.is_empty());
non_empty(self.sg_title.as_deref())
|| non_empty(self.title.as_deref())
|| self
.axes_metadata
.iter()
.any(|meta| non_empty(meta.title.as_deref()) || non_empty(meta.subtitle.as_deref()))
}
pub fn with_title<S: Into<String>>(mut self, title: S) -> Self {
self.set_title(title);
self
}
pub fn set_title<S: Into<String>>(&mut self, title: S) {
self.set_axes_title(self.active_axes_index, title);
}
pub fn with_labels<S: Into<String>>(mut self, x_label: S, y_label: S) -> Self {
self.set_axis_labels(x_label, y_label);
self
}
pub fn set_axis_labels<S: Into<String>>(&mut self, x_label: S, y_label: S) {
self.set_axes_labels(self.active_axes_index, x_label, y_label);
self.dirty = true;
}
pub fn reset_axes_text(&mut self, axes_index: usize) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.title = None;
meta.subtitle = None;
meta.x_label = None;
meta.y_label = None;
meta.z_label = None;
meta.title_style = TextStyle::default();
meta.subtitle_style = TextStyle::default();
meta.x_label_style = TextStyle::default();
meta.y_label_style = TextStyle::default();
meta.z_label_style = TextStyle::default();
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
pub fn set_axes_title<S: Into<String>>(&mut self, axes_index: usize, title: S) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.title = Some(title.into());
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
pub fn set_axes_subtitle<S: Into<String>>(&mut self, axes_index: usize, subtitle: S) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.subtitle = Some(subtitle.into());
}
self.dirty = true;
}
pub fn set_axes_xlabel<S: Into<String>>(&mut self, axes_index: usize, label: S) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.x_label = Some(label.into());
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
pub fn set_axes_ylabel<S: Into<String>>(&mut self, axes_index: usize, label: S) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.y_label = Some(label.into());
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
pub fn set_axes_zlabel<S: Into<String>>(&mut self, axes_index: usize, label: S) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.z_label = Some(label.into());
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
pub fn add_axes_text_annotation<S: Into<String>>(
&mut self,
axes_index: usize,
position: glam::Vec3,
text: S,
style: TextStyle,
) -> usize {
self.ensure_axes_metadata_capacity(axes_index + 1);
let Some(meta) = self.axes_metadata.get_mut(axes_index) else {
return 0;
};
meta.world_text_annotations.push(TextAnnotation {
position,
text: text.into(),
style,
});
self.dirty = true;
meta.world_text_annotations.len() - 1
}
pub fn axes_text_annotation(
&self,
axes_index: usize,
annotation_index: usize,
) -> Option<&TextAnnotation> {
self.axes_metadata
.get(axes_index)
.and_then(|meta| meta.world_text_annotations.get(annotation_index))
}
pub fn set_axes_text_annotation_text<S: Into<String>>(
&mut self,
axes_index: usize,
annotation_index: usize,
text: S,
) {
if let Some(annotation) = self
.axes_metadata
.get_mut(axes_index)
.and_then(|meta| meta.world_text_annotations.get_mut(annotation_index))
{
annotation.text = text.into();
self.dirty = true;
}
}
pub fn set_axes_text_annotation_position(
&mut self,
axes_index: usize,
annotation_index: usize,
position: glam::Vec3,
) {
if let Some(annotation) = self
.axes_metadata
.get_mut(axes_index)
.and_then(|meta| meta.world_text_annotations.get_mut(annotation_index))
{
annotation.position = position;
self.dirty = true;
}
}
pub fn set_axes_text_annotation_style(
&mut self,
axes_index: usize,
annotation_index: usize,
style: TextStyle,
) {
if let Some(annotation) = self
.axes_metadata
.get_mut(axes_index)
.and_then(|meta| meta.world_text_annotations.get_mut(annotation_index))
{
annotation.style = style;
self.dirty = true;
}
}
pub fn axes_text_annotations(&self, axes_index: usize) -> &[TextAnnotation] {
self.axes_metadata
.get(axes_index)
.map(|meta| meta.world_text_annotations.as_slice())
.unwrap_or(&[])
}
pub fn set_axes_labels<S: Into<String>>(&mut self, axes_index: usize, x_label: S, y_label: S) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.x_label = Some(x_label.into());
meta.y_label = Some(y_label.into());
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
pub fn set_axes_tick_labels(
&mut self,
axes_index: usize,
x_labels: Option<Vec<String>>,
y_labels: Option<Vec<String>>,
) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.x_tick_labels = x_labels;
meta.y_tick_labels = y_labels;
}
self.dirty = true;
}
pub fn set_axes_tick_formats(
&mut self,
axes_index: usize,
x_format: Option<String>,
y_format: Option<String>,
) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.x_tick_format = x_format;
meta.y_tick_format = y_format;
}
self.dirty = true;
}
pub fn set_axes_tick_label_rotations(
&mut self,
axes_index: usize,
x_angle: Option<f64>,
y_angle: Option<f64>,
) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.x_tick_label_rotation = x_angle;
meta.y_tick_label_rotation = y_angle;
}
self.dirty = true;
}
pub fn set_axes_ticks(
&mut self,
axes_index: usize,
x_ticks: Option<Vec<f64>>,
y_ticks: Option<Vec<f64>>,
) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.x_ticks = x_ticks;
meta.y_ticks = y_ticks;
}
self.dirty = true;
}
pub fn set_axes_style(&mut self, axes_index: usize, style: TextStyle) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.axes_style = style;
}
self.dirty = true;
}
pub fn set_axes_title_style(&mut self, axes_index: usize, style: TextStyle) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.title_style = style;
}
self.dirty = true;
}
pub fn set_axes_subtitle_style(&mut self, axes_index: usize, style: TextStyle) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.subtitle_style = style;
}
self.dirty = true;
}
pub fn set_axes_xlabel_style(&mut self, axes_index: usize, style: TextStyle) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.x_label_style = style;
}
self.dirty = true;
}
pub fn set_axes_ylabel_style(&mut self, axes_index: usize, style: TextStyle) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.y_label_style = style;
}
self.dirty = true;
}
pub fn set_axes_zlabel_style(&mut self, axes_index: usize, style: TextStyle) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.z_label_style = style;
}
self.dirty = true;
}
pub fn with_limits(mut self, x_limits: (f64, f64), y_limits: (f64, f64)) -> Self {
self.x_limits = Some(x_limits);
self.y_limits = Some(y_limits);
self.dirty = true;
self
}
pub fn with_legend(mut self, enabled: bool) -> Self {
self.set_legend(enabled);
self
}
pub fn set_legend(&mut self, enabled: bool) {
self.set_axes_legend_enabled(self.active_axes_index, enabled);
}
pub fn set_axes_legend_enabled(&mut self, axes_index: usize, enabled: bool) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.legend_enabled = enabled;
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
pub fn set_axes_legend_style(&mut self, axes_index: usize, style: LegendStyle) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.legend_style = style;
}
self.dirty = true;
}
pub fn set_axes_log_modes(&mut self, axes_index: usize, x_log: bool, y_log: bool) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.x_log = x_log;
meta.y_log = y_log;
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
pub fn set_axes_view(&mut self, axes_index: usize, azimuth_deg: f32, elevation_deg: f32) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.view_azimuth_deg = Some(azimuth_deg);
meta.view_elevation_deg = Some(elevation_deg);
meta.view_revision = meta.view_revision.wrapping_add(1);
}
self.dirty = true;
}
pub fn with_grid(mut self, enabled: bool) -> Self {
self.set_grid(enabled);
self
}
pub fn set_grid(&mut self, enabled: bool) {
self.set_axes_grid_enabled(self.active_axes_index, enabled);
self.dirty = true;
}
pub fn set_axes_grid_enabled(&mut self, axes_index: usize, enabled: bool) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.grid_enabled = enabled;
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
pub fn set_axes_kind(&mut self, axes_index: usize, axes_kind: AxesKind) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.axes_kind = axes_kind;
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
pub fn axes_kind(&self, axes_index: usize) -> AxesKind {
self.axes_metadata(axes_index)
.map(|meta| meta.axes_kind)
.unwrap_or(AxesKind::Cartesian)
}
pub fn with_minor_grid(mut self, enabled: bool) -> Self {
self.set_minor_grid(enabled);
self
}
pub fn set_minor_grid(&mut self, enabled: bool) {
self.set_axes_minor_grid_enabled(self.active_axes_index, enabled);
self.dirty = true;
}
pub fn set_axes_minor_grid_enabled(&mut self, axes_index: usize, enabled: bool) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.minor_grid_enabled = enabled;
meta.minor_grid_explicit = true;
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
pub fn minor_grid_enabled_for_axes(&self, axes_index: usize) -> bool {
self.axes_metadata(axes_index)
.map(|meta| {
if meta.minor_grid_explicit {
meta.minor_grid_enabled
} else {
self.minor_grid_enabled
}
})
.unwrap_or(self.minor_grid_enabled)
}
pub fn with_background_color(mut self, color: Vec4) -> Self {
self.set_background_color(color);
self
}
pub fn set_background_color(&mut self, color: Vec4) {
self.background_color = color;
self.dirty = true;
}
pub fn with_xlog(mut self, enabled: bool) -> Self {
self.set_axes_log_modes(self.active_axes_index, enabled, self.y_log);
self
}
pub fn with_ylog(mut self, enabled: bool) -> Self {
self.set_axes_log_modes(self.active_axes_index, self.x_log, enabled);
self
}
pub fn with_axis_equal(mut self, enabled: bool) -> Self {
self.set_axis_equal(enabled);
self
}
pub fn set_axis_equal(&mut self, enabled: bool) {
self.set_axes_axis_equal(self.active_axes_index, enabled);
self.dirty = true;
}
pub fn set_axes_axis_equal(&mut self, axes_index: usize, enabled: bool) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.axis_equal = enabled;
meta.data_aspect_ratio_mode = if enabled { "manual" } else { "auto" }.into();
if enabled {
meta.data_aspect_ratio = [1.0, 1.0, 1.0];
}
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
pub fn set_axes_data_aspect_ratio(
&mut self,
axes_index: usize,
ratio: [f64; 3],
mode: impl Into<String>,
) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.data_aspect_ratio = ratio;
meta.data_aspect_ratio_mode = mode.into();
meta.axis_equal = meta.data_aspect_ratio_mode == "manual" && ratio == [1.0, 1.0, 1.0];
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
pub fn with_colormap(mut self, cmap: ColorMap) -> Self {
self.set_axes_colormap(self.active_axes_index, cmap);
self
}
pub fn with_colorbar(mut self, enabled: bool) -> Self {
self.set_axes_colorbar_enabled(self.active_axes_index, enabled);
self
}
pub fn with_color_limits(mut self, limits: Option<(f64, f64)>) -> Self {
self.set_axes_color_limits(self.active_axes_index, limits);
self
}
pub fn with_subplot_grid(mut self, rows: usize, cols: usize) -> Self {
self.set_subplot_grid(rows, cols);
self
}
pub fn axes_grid(&self) -> (usize, usize) {
(self.axes_rows, self.axes_cols)
}
pub fn axes_count(&self) -> usize {
let plotted_axes = self
.plot_axes_indices
.iter()
.copied()
.max()
.map(|index| index + 1)
.unwrap_or(0);
let overlay_axes = self
.axes_metadata
.iter()
.enumerate()
.filter(|(_, meta)| meta.overlay_parent.is_some())
.map(|(index, _)| index + 1)
.max()
.unwrap_or(0);
self.total_axes()
.max(plotted_axes)
.max(overlay_axes)
.max(self.axes_metadata.len())
.max(1)
}
pub fn ensure_overlay_axes(&mut self, parent_axes_index: usize) -> usize {
let parent = parent_axes_index.min(self.total_axes().saturating_sub(1));
if let Some((index, _)) = self
.axes_metadata
.iter()
.enumerate()
.find(|(_, meta)| meta.overlay_parent == Some(parent))
{
return index;
}
let index = self.axes_metadata.len().max(self.total_axes());
self.ensure_axes_metadata_capacity(index + 1);
if let Some(parent_meta) = self.axes_metadata.get(parent).cloned() {
if let Some(meta) = self.axes_metadata.get_mut(index) {
*meta = parent_meta;
meta.overlay_parent = Some(parent);
meta.y_axis_location = "right".into();
meta.y_limits = None;
meta.y_ticks = None;
meta.y_tick_labels = None;
meta.y_tick_format = None;
meta.y_label = None;
meta.legend_enabled = false;
meta.grid_enabled = false;
meta.minor_grid_enabled = false;
}
}
self.axes_grid_cells[index] = self.axes_grid_cells.get(parent).copied().flatten();
self.dirty = true;
index
}
pub fn axes_overlay_parent(&self, axes_index: usize) -> Option<usize> {
self.axes_metadata
.get(axes_index)
.and_then(|meta| meta.overlay_parent)
}
pub fn set_axes_y_axis_location(&mut self, axes_index: usize, location: impl Into<String>) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.y_axis_location = location.into();
}
self.dirty = true;
}
pub fn set_axes_position(&mut self, axes_index: usize, position: [f64; 4]) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.position = position;
meta.position_explicit = true;
}
self.axes_grid_cells[axes_index] = None;
self.dirty = true;
}
pub fn set_axes_units(&mut self, axes_index: usize, units: impl Into<String>) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.units = units.into();
}
self.dirty = true;
}
pub fn plot_axes_indices(&self) -> &[usize] {
&self.plot_axes_indices
}
pub fn assign_plot_to_axes(
&mut self,
plot_index: usize,
axes_index: usize,
) -> Result<(), String> {
if plot_index >= self.plot_axes_indices.len() {
return Err(format!(
"assign_plot_to_axes: index {plot_index} out of bounds"
));
}
let max_axes = self.axes_count();
let ai = axes_index.min(max_axes.saturating_sub(1));
self.plot_axes_indices[plot_index] = ai;
self.dirty = true;
Ok(())
}
pub fn set_subplot_grid(&mut self, rows: usize, cols: usize) {
self.axes_rows = rows.max(1);
self.axes_cols = cols.max(1);
let grid_axes = self.axes_rows * self.axes_cols;
self.ensure_axes_metadata_capacity(grid_axes);
self.axes_grid_cells.fill(None);
for axes_index in 0..grid_axes {
if self
.axes_metadata
.get(axes_index)
.is_some_and(|meta| meta.overlay_parent.is_some())
{
self.clear_axes(axes_index);
self.axes_metadata[axes_index] = self.inherited_axes_metadata();
}
}
self.active_axes_index = self.active_axes_index.min(
self.axes_rows
.saturating_mul(self.axes_cols)
.saturating_sub(1),
);
self.sync_legacy_fields_from_active_axes();
self.dirty = true;
}
pub fn set_color_limits(&mut self, limits: Option<(f64, f64)>) {
self.set_axes_color_limits(self.active_axes_index, limits);
self.dirty = true;
}
pub fn set_z_limits(&mut self, limits: Option<(f64, f64)>) {
self.set_axes_z_limits(self.active_axes_index, limits);
self.dirty = true;
}
pub fn set_axes_limits(
&mut self,
axes_index: usize,
x: Option<(f64, f64)>,
y: Option<(f64, f64)>,
) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.x_limits = x;
meta.y_limits = y;
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
pub fn set_axes_z_limits(&mut self, axes_index: usize, limits: Option<(f64, f64)>) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.z_limits = limits;
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
pub fn set_axes_limit_method(
&mut self,
axes_index: usize,
axis: AxisLimitAxis,
method: AxisLimitMethod,
) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
match axis {
AxisLimitAxis::X => meta.x_limit_method = method,
AxisLimitAxis::Y => meta.y_limit_method = method,
AxisLimitAxis::Z => meta.z_limit_method = method,
}
}
self.dirty = true;
}
pub fn set_axes_box_enabled(&mut self, axes_index: usize, enabled: bool) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.box_enabled = enabled;
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
pub fn set_axes_hidden_line_removal(&mut self, axes_index: usize, enabled: bool) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.hidden_line_removal = enabled;
}
self.dirty = true;
}
pub fn set_axes_colorbar_enabled(&mut self, axes_index: usize, enabled: bool) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.colorbar_enabled = enabled;
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
pub fn set_axes_colormap(&mut self, axes_index: usize, cmap: ColorMap) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
if let ColorMap::Listed(colors) = &cmap {
meta.colormap_length = colors.len();
}
meta.colormap = cmap.clone();
}
for (idx, plot) in self.plots.iter_mut().enumerate() {
if self.plot_axes_indices.get(idx).copied().unwrap_or(0) != axes_index {
continue;
}
Self::apply_colormap_to_plot(plot, &cmap);
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
fn apply_colormap_to_plot(plot: &mut PlotElement, cmap: &ColorMap) {
match plot {
PlotElement::Surface(surface) => {
*surface = surface.clone().with_colormap(cmap.clone());
}
PlotElement::Scatter(scatter) => scatter.recolor_with_colormap(cmap),
PlotElement::Scatter3(scatter) => scatter.recolor_with_colormap(cmap),
PlotElement::Contour(contour) => contour.recolor_with_colormap(cmap),
PlotElement::ContourFill(fill) => fill.recolor_with_colormap(cmap),
_ => {}
}
}
pub fn apply_axes_colormaps_from(&mut self, start: usize) {
for idx in start..self.plots.len() {
let axes_index = self.plot_axes_indices.get(idx).copied().unwrap_or(0);
let Some(cmap) = self
.axes_metadata
.get(axes_index)
.map(|m| m.colormap.clone())
else {
continue;
};
Self::apply_colormap_to_plot(&mut self.plots[idx], &cmap);
}
self.dirty = true;
}
pub fn set_axes_color_limits(&mut self, axes_index: usize, limits: Option<(f64, f64)>) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.color_limits = limits;
}
for (idx, plot) in self.plots.iter_mut().enumerate() {
if self.plot_axes_indices.get(idx).copied().unwrap_or(0) != axes_index {
continue;
}
if let PlotElement::Surface(surface) = plot {
if surface.color_mapping == crate::plots::surface::SurfaceColorMapping::Scaled {
surface.set_color_limits(limits);
}
}
}
if axes_index == self.active_axes_index {
self.sync_legacy_fields_from_active_axes();
}
self.dirty = true;
}
pub fn set_axes_color_order(&mut self, axes_index: usize, colors: Vec<Vec4>) {
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.color_order = Some(colors.clone());
}
self.recolor_axes_plots(axes_index, &colors);
self.dirty = true;
}
pub fn set_all_axes_color_order(&mut self, colors: Vec<Vec4>) {
let total_axes = self.total_axes().max(1);
self.ensure_axes_metadata_capacity(total_axes);
for axes_index in 0..total_axes {
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.color_order = Some(colors.clone());
}
self.recolor_axes_plots(axes_index, &colors);
}
self.dirty = true;
}
fn recolor_axes_plots(&mut self, axes_index: usize, colors: &[Vec4]) {
if colors.is_empty() {
return;
}
let mut series = 0usize;
for (plot_index, plot) in self.plots.iter_mut().enumerate() {
if self.plot_axes_indices.get(plot_index).copied().unwrap_or(0) != axes_index {
continue;
}
let color = colors[series % colors.len()];
match plot {
PlotElement::Line(line) => {
line.set_color(color);
series += 1;
}
PlotElement::Scatter(scatter) => {
scatter.set_color(color);
scatter.set_edge_color(color);
series += 1;
}
PlotElement::Bar(bar) => {
bar.set_color(color);
series += 1;
}
PlotElement::Stairs(stairs) => {
stairs.color = color;
series += 1;
}
PlotElement::Stem(stem) => {
stem.color = color;
series += 1;
}
PlotElement::Area(area) => {
area.color = Vec4::new(color.x, color.y, color.z, area.color.w);
series += 1;
}
PlotElement::ErrorBar(errorbar) => {
errorbar.color = color;
series += 1;
}
PlotElement::Quiver(quiver) => {
quiver.color = color;
series += 1;
}
PlotElement::Line3(line) => {
line.color = color;
series += 1;
}
PlotElement::Scatter3(scatter) => {
*scatter = scatter.clone().with_color(color);
scatter.edge_color = color;
series += 1;
}
_ => {}
}
}
}
fn total_axes(&self) -> usize {
self.axes_rows.max(1) * self.axes_cols.max(1)
}
fn normalize_axes_index(&self, axes_index: usize) -> usize {
let total = self.axes_count();
axes_index.min(total - 1)
}
fn push_plot(&mut self, element: PlotElement, axes_index: usize) -> usize {
let idx = self.normalize_axes_index(axes_index);
self.plots.push(element);
self.plot_axes_indices.push(idx);
self.geometry_source = None;
self.dirty = true;
self.plots.len() - 1
}
pub fn add_plot_element_on_axes(&mut self, element: PlotElement, axes_index: usize) -> usize {
self.push_plot(element, axes_index)
}
pub fn add_line_plot(&mut self, plot: LinePlot) -> usize {
self.add_line_plot_on_axes(plot, 0)
}
pub fn add_line_plot_on_axes(&mut self, plot: LinePlot, axes_index: usize) -> usize {
self.push_plot(PlotElement::Line(plot), axes_index)
}
pub fn add_reference_line_on_axes(&mut self, plot: ReferenceLine, axes_index: usize) -> usize {
self.push_plot(PlotElement::ReferenceLine(plot), axes_index)
}
pub fn add_scatter_plot(&mut self, plot: ScatterPlot) -> usize {
self.add_scatter_plot_on_axes(plot, 0)
}
pub fn add_scatter_plot_on_axes(&mut self, plot: ScatterPlot, axes_index: usize) -> usize {
self.push_plot(PlotElement::Scatter(plot), axes_index)
}
pub fn add_bar_chart(&mut self, plot: BarChart) -> usize {
self.add_bar_chart_on_axes(plot, 0)
}
pub fn add_bar_chart_on_axes(&mut self, plot: BarChart, axes_index: usize) -> usize {
self.push_plot(PlotElement::Bar(plot), axes_index)
}
pub fn add_errorbar(&mut self, plot: ErrorBar) -> usize {
self.add_errorbar_on_axes(plot, 0)
}
pub fn add_errorbar_on_axes(&mut self, plot: ErrorBar, axes_index: usize) -> usize {
self.push_plot(PlotElement::ErrorBar(Box::new(plot)), axes_index)
}
pub fn add_stairs_plot(&mut self, plot: StairsPlot) -> usize {
self.add_stairs_plot_on_axes(plot, 0)
}
pub fn add_stairs_plot_on_axes(&mut self, plot: StairsPlot, axes_index: usize) -> usize {
self.push_plot(PlotElement::Stairs(plot), axes_index)
}
pub fn add_stem_plot(&mut self, plot: StemPlot) -> usize {
self.add_stem_plot_on_axes(plot, 0)
}
pub fn add_stem_plot_on_axes(&mut self, plot: StemPlot, axes_index: usize) -> usize {
self.push_plot(PlotElement::Stem(plot), axes_index)
}
pub fn add_area_plot(&mut self, plot: AreaPlot) -> usize {
self.add_area_plot_on_axes(plot, 0)
}
pub fn add_area_plot_on_axes(&mut self, plot: AreaPlot, axes_index: usize) -> usize {
self.push_plot(PlotElement::Area(plot), axes_index)
}
pub fn add_quiver_plot(&mut self, plot: QuiverPlot) -> usize {
self.add_quiver_plot_on_axes(plot, 0)
}
pub fn add_quiver_plot_on_axes(&mut self, plot: QuiverPlot, axes_index: usize) -> usize {
self.push_plot(PlotElement::Quiver(plot), axes_index)
}
pub fn add_pie_chart(&mut self, plot: PieChart) -> usize {
self.add_pie_chart_on_axes(plot, 0)
}
pub fn add_pie_chart_on_axes(&mut self, plot: PieChart, axes_index: usize) -> usize {
self.push_plot(PlotElement::Pie(plot), axes_index)
}
pub fn add_surface_plot(&mut self, plot: SurfacePlot) -> usize {
self.add_surface_plot_on_axes(plot, 0)
}
pub fn add_surface_plot_on_axes(&mut self, plot: SurfacePlot, axes_index: usize) -> usize {
self.push_plot(PlotElement::Surface(plot), axes_index)
}
pub fn add_patch_plot(&mut self, plot: PatchPlot) -> usize {
self.add_patch_plot_on_axes(plot, 0)
}
pub fn add_patch_plot_on_axes(&mut self, plot: PatchPlot, axes_index: usize) -> usize {
self.push_plot(PlotElement::Patch(plot), axes_index)
}
pub fn add_mesh_plot(&mut self, plot: MeshPlot) -> usize {
self.add_mesh_plot_on_axes(plot, 0)
}
pub fn add_mesh_plot_on_axes(&mut self, plot: MeshPlot, axes_index: usize) -> usize {
self.push_plot(PlotElement::Mesh(Box::new(plot)), axes_index)
}
pub fn add_line3_plot(&mut self, plot: Line3Plot) -> usize {
self.add_line3_plot_on_axes(plot, self.active_axes_index)
}
pub fn add_line3_plot_on_axes(&mut self, plot: Line3Plot, axes_index: usize) -> usize {
self.push_plot(PlotElement::Line3(plot), axes_index)
}
pub fn add_scatter3_plot(&mut self, plot: Scatter3Plot) -> usize {
self.add_scatter3_plot_on_axes(plot, 0)
}
pub fn add_scatter3_plot_on_axes(&mut self, plot: Scatter3Plot, axes_index: usize) -> usize {
self.push_plot(PlotElement::Scatter3(plot), axes_index)
}
pub fn add_contour_plot(&mut self, plot: ContourPlot) -> usize {
self.add_contour_plot_on_axes(plot, 0)
}
pub fn add_contour_plot_on_axes(&mut self, plot: ContourPlot, axes_index: usize) -> usize {
self.push_plot(PlotElement::Contour(plot), axes_index)
}
pub fn add_contour_fill_plot(&mut self, plot: ContourFillPlot) -> usize {
self.add_contour_fill_plot_on_axes(plot, 0)
}
pub fn add_contour_fill_plot_on_axes(
&mut self,
plot: ContourFillPlot,
axes_index: usize,
) -> usize {
self.push_plot(PlotElement::ContourFill(plot), axes_index)
}
pub fn remove_plot(&mut self, index: usize) -> Result<(), String> {
if index >= self.plots.len() {
return Err(format!("Plot index {index} out of bounds"));
}
self.plots.remove(index);
self.plot_axes_indices.remove(index);
self.geometry_source = None;
self.dirty = true;
Ok(())
}
pub fn clear(&mut self) {
self.plots.clear();
self.plot_axes_indices.clear();
self.geometry_source = None;
self.dirty = true;
}
pub fn clear_axes(&mut self, axes_index: usize) {
let mut i = 0usize;
while i < self.plots.len() {
let ax = *self.plot_axes_indices.get(i).unwrap_or(&0);
if ax == axes_index {
self.plots.remove(i);
self.plot_axes_indices.remove(i);
self.geometry_source = None;
} else {
i += 1;
}
}
self.ensure_axes_metadata_capacity(axes_index + 1);
if let Some(meta) = self.axes_metadata.get_mut(axes_index) {
meta.world_text_annotations.clear();
}
self.dirty = true;
}
pub fn len(&self) -> usize {
self.plots.len()
}
pub fn is_empty(&self) -> bool {
self.plots.is_empty()
}
pub fn plots(&self) -> impl Iterator<Item = &PlotElement> {
self.plots.iter()
}
pub fn get_plot_mut(&mut self, index: usize) -> Option<&mut PlotElement> {
self.dirty = true;
self.plots.get_mut(index)
}
pub fn bounds(&mut self) -> BoundingBox {
if self.dirty || self.bounds.is_none() {
self.compute_bounds();
}
self.bounds.unwrap()
}
pub fn data_bounds_for_axes(&mut self, axes_index: usize) -> BoundingBox {
let axes_index = self.normalize_axes_index(axes_index);
let mut combined_bounds = None;
for (plot_index, plot) in self.plots.iter_mut().enumerate() {
if self.plot_axes_indices.get(plot_index).copied().unwrap_or(0) != axes_index {
continue;
}
if !plot.is_visible() || matches!(plot, PlotElement::ReferenceLine(_)) {
continue;
}
let plot_bounds = plot.bounds();
combined_bounds = match combined_bounds {
None => Some(plot_bounds),
Some(existing) => Some(existing.union(&plot_bounds)),
};
}
combined_bounds.unwrap_or_default()
}
fn compute_bounds(&mut self) {
if self.plots.is_empty() {
self.bounds = Some(BoundingBox::default());
return;
}
let mut combined_bounds = None;
let mut reference_lines = Vec::new();
for plot in &mut self.plots {
if !plot.is_visible() {
continue;
}
if let PlotElement::ReferenceLine(reference_line) = plot {
reference_lines.push(reference_line.clone());
continue;
}
let plot_bounds = plot.bounds();
combined_bounds = match combined_bounds {
None => Some(plot_bounds),
Some(existing) => Some(existing.union(&plot_bounds)),
};
}
for line in reference_lines {
let mut point_bounds = line.coordinate_bounds();
if let Some(existing) = combined_bounds {
match line.orientation {
ReferenceLineOrientation::Vertical => {
point_bounds.min.y = existing.min.y;
point_bounds.max.y = existing.max.y;
}
ReferenceLineOrientation::Horizontal => {
point_bounds.min.x = existing.min.x;
point_bounds.max.x = existing.max.x;
}
}
} else {
let (x_range, y_range) =
Self::reference_line_ranges(self.x_limits, self.y_limits, None, None, &line);
point_bounds.min.x = x_range.0 as f32;
point_bounds.max.x = x_range.1 as f32;
point_bounds.min.y = y_range.0 as f32;
point_bounds.max.y = y_range.1 as f32;
}
combined_bounds = match combined_bounds {
None => Some(point_bounds),
Some(existing) => Some(existing.union(&point_bounds)),
};
}
self.bounds = combined_bounds.or_else(|| Some(BoundingBox::default()));
self.dirty = false;
}
pub fn render_data(&mut self) -> Vec<RenderData> {
self.render_data_with_viewport(None)
}
pub fn render_data_with_viewport(
&mut self,
viewport_px: Option<(u32, u32)>,
) -> Vec<RenderData> {
self.render_data_with_viewport_and_gpu(viewport_px, None)
}
pub fn render_data_with_viewport_and_gpu(
&mut self,
viewport_px: Option<(u32, u32)>,
gpu: Option<&GpuPackContext<'_>>,
) -> Vec<RenderData> {
self.render_data_with_axes_with_viewport_and_gpu(viewport_px, None, None, gpu)
.into_iter()
.map(|(_, render_data)| render_data)
.collect()
}
pub fn render_data_with_axes_with_viewport_and_gpu(
&mut self,
viewport_px: Option<(u32, u32)>,
axes_viewports_px: Option<&[(u32, u32)]>,
axes_view_bounds: Option<PerAxesViewBoundsRef<'_>>,
gpu: Option<&GpuPackContext<'_>>,
) -> Vec<(usize, RenderData)> {
fn push_with_optional_markers(
out: &mut Vec<(usize, RenderData)>,
axes_index: usize,
render_data: RenderData,
marker_data: Option<RenderData>,
) {
out.push((axes_index, render_data));
if let Some(marker_data) = marker_data {
out.push((axes_index, marker_data));
}
}
let reference_base_bounds = self.reference_base_bounds_by_axes();
let mut out = Vec::new();
for (plot_idx, p) in self.plots.iter_mut().enumerate() {
if !p.is_visible() {
continue;
}
let axes_index = self.plot_axes_indices.get(plot_idx).copied().unwrap_or(0);
let axes_view_bounds = axes_view_bounds
.and_then(|bounds| bounds.get(axes_index).copied())
.flatten();
let resolved_viewport = crate::core::ResolvedViewport {
pixels: axes_viewports_px
.and_then(|viewports| viewports.get(axes_index).copied())
.or(viewport_px),
view: axes_view_bounds,
};
let hidden_line_removal = self
.axes_metadata
.get(axes_index)
.map(|meta| meta.hidden_line_removal)
.unwrap_or(true);
if let PlotElement::Surface(s) = p {
if let Some(meta) = self.axes_metadata.get(axes_index) {
if s.color_mapping == crate::plots::surface::SurfaceColorMapping::Scaled {
s.set_color_limits(meta.color_limits);
}
s.colormap_length = meta.colormap_length;
*s = s.clone().with_colormap(meta.colormap.clone());
}
}
if let PlotElement::Patch(patch) = p {
if let Some(meta) = self.axes_metadata.get(axes_index) {
patch.set_color_context(
meta.colormap.clone(),
meta.colormap_length,
meta.color_limits,
);
}
}
let log_axes = self
.axes_metadata
.get(axes_index)
.map(|meta| (meta.x_log, meta.y_log))
.unwrap_or((self.x_log, self.y_log));
match p {
PlotElement::Line(plot) => {
let axes_viewport_px = axes_viewports_px
.and_then(|viewports| viewports.get(axes_index).copied())
.or(viewport_px);
trace!(
target: "runmat_plot",
"figure: render_data line viewport_px={:?} axes_index={} axes_viewport_px={:?} axes_view_bounds={:?} gpu_ctx_present={} gpu_line_inputs_present={} gpu_vertices_present={}",
viewport_px,
axes_index,
axes_viewport_px,
axes_view_bounds,
gpu.is_some(),
plot.has_gpu_line_inputs(),
plot.has_gpu_vertices()
);
push_with_optional_markers(
&mut out,
axes_index,
plot.render_data_with_viewport_gpu(
axes_viewport_px,
axes_view_bounds,
log_axes,
gpu,
),
plot.marker_render_data(),
);
}
PlotElement::ErrorBar(plot) => {
push_with_optional_markers(
&mut out,
axes_index,
plot.render_data_with_viewport_gpu(
resolved_viewport.pixels,
resolved_viewport.view,
log_axes,
gpu,
),
plot.marker_render_data(),
);
}
PlotElement::Stairs(plot) => {
push_with_optional_markers(
&mut out,
axes_index,
plot.render_data_on_axes(
resolved_viewport.pixels,
resolved_viewport.view,
log_axes,
),
plot.marker_render_data(),
);
}
PlotElement::Stem(plot) => {
push_with_optional_markers(
&mut out,
axes_index,
plot.render_data_on_axes(
resolved_viewport.pixels,
resolved_viewport.view,
log_axes,
),
plot.marker_render_data(),
);
}
PlotElement::Contour(plot) => out.push((
axes_index,
plot.render_data_with_resolved_viewport(resolved_viewport),
)),
PlotElement::ReferenceLine(plot) => {
let (x_range, y_range) = Self::reference_line_ranges(
self.x_limits,
self.y_limits,
self.axes_metadata.get(axes_index),
reference_base_bounds.get(axes_index).copied().flatten(),
plot,
);
out.push((
axes_index,
plot.render_data_with_range(
x_range,
y_range,
resolved_viewport.pixels,
log_axes,
),
));
}
PlotElement::Patch(plot) => {
out.push((axes_index, plot.render_data()));
if let Some(edge_data) =
plot.edge_render_data_with_resolved_viewport(resolved_viewport)
{
out.push((axes_index, edge_data));
}
}
PlotElement::Mesh(plot) => {
out.push((axes_index, plot.render_data()));
if let Some(mut edge_data) = plot.edge_render_data() {
if !hidden_line_removal {
edge_data.pipeline_type = crate::core::PipelineType::LinesNoDepth;
}
out.push((axes_index, edge_data));
}
if let Some(vector_data) = plot.vector_render_data() {
out.push((axes_index, vector_data));
}
}
PlotElement::Line3(plot) => out.push((
axes_index,
plot.render_data_with_viewport_gpu(
axes_viewports_px
.and_then(|viewports| viewports.get(axes_index).copied())
.or(viewport_px),
self.axes_metadata.get(axes_index).and_then(|meta| {
match (meta.view_azimuth_deg, meta.view_elevation_deg) {
(Some(az), Some(el)) => Some((az, el)),
_ => None,
}
}),
gpu,
),
)),
PlotElement::Surface(plot) => {
let mut render_data = plot.render_data();
if !hidden_line_removal
&& render_data.pipeline_type == crate::core::PipelineType::Lines
{
render_data.pipeline_type = crate::core::PipelineType::LinesNoDepth;
}
out.push((axes_index, render_data));
}
_ => out.push((axes_index, p.render_data())),
}
}
out
}
fn reference_base_bounds_by_axes(&mut self) -> Vec<Option<BoundingBox>> {
let axes_count = self.total_axes().max(1);
let mut bounds: Vec<Option<BoundingBox>> = vec![None; axes_count];
for (plot_idx, plot) in self.plots.iter_mut().enumerate() {
if !plot.is_visible() || matches!(plot, PlotElement::ReferenceLine(_)) {
continue;
}
let axes_index = self
.plot_axes_indices
.get(plot_idx)
.copied()
.unwrap_or(0)
.min(axes_count - 1);
let plot_bounds = plot.bounds();
bounds[axes_index] = Some(match bounds[axes_index] {
None => plot_bounds,
Some(existing) => existing.union(&plot_bounds),
});
}
bounds
}
fn reference_line_ranges(
x_limits: Option<(f64, f64)>,
y_limits: Option<(f64, f64)>,
meta: Option<&AxesMetadata>,
base: Option<BoundingBox>,
line: &ReferenceLine,
) -> ((f64, f64), (f64, f64)) {
let x_range = x_limits
.or_else(|| meta.and_then(|m| m.x_limits))
.or_else(|| base.map(|b| (b.min.x as f64, b.max.x as f64)))
.unwrap_or(match line.orientation {
ReferenceLineOrientation::Vertical => (line.value - 0.5, line.value + 0.5),
ReferenceLineOrientation::Horizontal => (0.0, 1.0),
});
let y_range = y_limits
.or_else(|| meta.and_then(|m| m.y_limits))
.or_else(|| base.map(|b| (b.min.y as f64, b.max.y as f64)))
.unwrap_or(match line.orientation {
ReferenceLineOrientation::Vertical => (0.0, 1.0),
ReferenceLineOrientation::Horizontal => (line.value - 0.5, line.value + 0.5),
});
(
normalize_reference_range(x_range),
normalize_reference_range(y_range),
)
}
pub fn legend_entries(&self) -> Vec<LegendEntry> {
let mut entries = Vec::new();
for plot in &self.plots {
if plot.is_hidden_from_legend() {
continue;
}
if let Some(label) = plot.label() {
entries.push(LegendEntry {
label,
color: plot.color(),
plot_type: plot.plot_type(),
marker: plot.legend_marker(),
line_visible: plot.legend_line_visible(),
line_style: plot.legend_line_style(),
});
}
}
entries
}
pub fn legend_entries_for_axes(&self, axes_index: usize) -> Vec<LegendEntry> {
let mut entries = Vec::new();
for (plot_idx, plot) in self.plots.iter().enumerate() {
let plot_axes = *self.plot_axes_indices.get(plot_idx).unwrap_or(&0);
if plot_axes != axes_index {
continue;
}
match plot {
PlotElement::Pie(pie) => {
let legend_labels = pie.legend_labels.clone();
for (slice_index, slice) in pie.slice_meta().into_iter().enumerate() {
entries.push(LegendEntry {
label: legend_labels
.get(slice_index)
.cloned()
.unwrap_or(slice.label),
color: slice.color,
plot_type: plot.plot_type(),
marker: None,
line_visible: true,
line_style: crate::plots::line::LineStyle::Solid,
});
}
}
_ => {
if plot.is_hidden_from_legend() {
continue;
}
if let Some(label) = plot.label() {
entries.push(LegendEntry {
label,
color: plot.color(),
plot_type: plot.plot_type(),
marker: plot.legend_marker(),
line_visible: plot.legend_line_visible(),
line_style: plot.legend_line_style(),
});
}
}
}
}
entries
}
pub fn pie_labels_for_axes(&self, axes_index: usize) -> Vec<PieLabelEntry> {
let mut out = Vec::new();
for (plot_idx, plot) in self.plots.iter().enumerate() {
let plot_axes = *self.plot_axes_indices.get(plot_idx).unwrap_or(&0);
if plot_axes != axes_index {
continue;
}
if let PlotElement::Pie(pie) = plot {
for slice in pie.slice_meta() {
out.push(PieLabelEntry {
label: slice.label,
position: glam::Vec2::new(
slice.mid_angle.cos() * 1.15 + slice.offset.x,
slice.mid_angle.sin() * 1.15 + slice.offset.y,
),
});
}
}
}
out
}
pub fn axes_color_range(&self, axes_index: usize) -> Option<(f64, f64)> {
if let Some(limits) = self.axes_metadata(axes_index).and_then(|m| m.color_limits) {
return Some(limits);
}
let mut range: Option<(f64, f64)> = None;
let mut include = |lo: f64, hi: f64| {
if lo.is_finite() && hi.is_finite() {
range = Some(match range {
Some((a, b)) => (a.min(lo), b.max(hi)),
None => (lo, hi),
});
}
};
let finite_range = |values: &mut dyn Iterator<Item = f64>| {
values
.filter(|v| v.is_finite())
.fold(None, |acc: Option<(f64, f64)>, v| match acc {
Some((a, b)) => Some((a.min(v), b.max(v))),
None => Some((v, v)),
})
};
for (plot_idx, plot) in self.plots.iter().enumerate() {
if *self.plot_axes_indices.get(plot_idx).unwrap_or(&0) != axes_index {
continue;
}
let found = match plot {
PlotElement::Surface(surface)
if surface.visible && surface.color_grid.is_none() =>
{
surface.color_limits.or_else(|| {
surface
.z_data
.as_ref()
.and_then(|rows| finite_range(&mut rows.iter().flatten().copied()))
})
}
PlotElement::Scatter(scatter) if scatter.visible => {
scatter.color_limits.or_else(|| {
scatter
.color_values
.as_ref()
.and_then(|values| finite_range(&mut values.iter().copied()))
})
}
PlotElement::Contour(contour) if contour.visible => contour.value_range,
PlotElement::ContourFill(fill) if fill.visible => fill.value_range,
_ => None,
};
if let Some((lo, hi)) = found {
include(lo, hi);
}
}
range
}
pub fn reference_line_labels_for_axes(
&self,
axes_index: usize,
) -> Vec<(ReferenceLineOrientation, f64, String, Option<Vec4>)> {
let mut out = Vec::new();
for (plot_idx, plot) in self.plots.iter().enumerate() {
if *self.plot_axes_indices.get(plot_idx).unwrap_or(&0) != axes_index {
continue;
}
if let PlotElement::ReferenceLine(line) = plot {
if let Some(label) = line.label.as_ref().filter(|l| !l.trim().is_empty()) {
if line.visible {
out.push((
line.orientation,
line.value,
label.clone(),
(!line.color_auto).then_some(line.color),
));
}
}
}
}
out
}
pub fn reference_lines_for_axes(
&self,
axes_index: usize,
) -> Vec<(ReferenceLineOrientation, f64)> {
self.plots
.iter()
.enumerate()
.filter(|(i, _)| *self.plot_axes_indices.get(*i).unwrap_or(&0) == axes_index)
.filter_map(|(_, plot)| match plot {
PlotElement::ReferenceLine(line) if line.visible => {
Some((line.orientation, line.value))
}
_ => None,
})
.collect()
}
pub fn resolve_auto_reference_line_colors(&mut self, axes_color: Vec4) {
for plot in &mut self.plots {
if let PlotElement::ReferenceLine(line) = plot {
if line.color_auto {
line.color = axes_color;
}
}
}
}
pub fn cell_label_marks_for_axes(
&self,
axes_index: usize,
) -> Vec<(glam::Vec3, String, glam::Vec4)> {
let mut out = Vec::new();
for (plot_idx, plot) in self.plots.iter().enumerate() {
if *self.plot_axes_indices.get(plot_idx).unwrap_or(&0) != axes_index {
continue;
}
if let PlotElement::Surface(surface) = plot {
if surface.visible {
out.extend(surface.cell_label_marks());
}
}
}
out
}
pub fn set_labels(&mut self, labels: &[String]) {
self.set_labels_for_axes(self.active_axes_index, labels);
}
pub fn set_labels_for_axes(&mut self, axes_index: usize, labels: &[String]) {
let mut idx = 0usize;
for (plot_idx, plot) in self.plots.iter_mut().enumerate() {
let plot_axes = *self.plot_axes_indices.get(plot_idx).unwrap_or(&0);
if plot_axes != axes_index {
continue;
}
if !plot.is_visible() || plot.is_hidden_from_legend() {
continue;
}
if idx >= labels.len() {
break;
}
match plot {
PlotElement::Pie(pie) => {
let remaining = &labels[idx..];
if remaining.len() >= pie.values.len() {
pie.set_legend_labels(remaining[..pie.values.len()].to_vec());
idx += pie.values.len();
} else {
pie.set_legend_labels(remaining.to_vec());
idx = labels.len();
}
}
_ => {
plot.set_label(Some(labels[idx].clone()));
idx += 1;
}
}
}
self.dirty = true;
}
pub fn statistics(&self) -> FigureStatistics {
let plot_counts = self.plots.iter().fold(HashMap::new(), |mut acc, plot| {
let plot_type = plot.plot_type();
*acc.entry(plot_type).or_insert(0) += 1;
acc
});
let total_memory: usize = self
.plots
.iter()
.map(|plot| plot.estimated_memory_usage())
.sum();
let visible_count = self.plots.iter().filter(|plot| plot.is_visible()).count();
FigureStatistics {
total_plots: self.plots.len(),
visible_plots: visible_count,
plot_type_counts: plot_counts,
total_memory_usage: total_memory,
has_legend: self.legend_enabled && !self.legend_entries().is_empty(),
}
}
pub fn categorical_axis_labels(&self) -> Option<(bool, Vec<String>)> {
for plot in &self.plots {
if let PlotElement::Bar(b) = plot {
if b.histogram_bin_edges().is_some() {
continue;
}
let is_x = matches!(b.orientation, crate::plots::bar::Orientation::Vertical);
return Some((is_x, b.labels.clone()));
}
}
None
}
pub fn categorical_axis_labels_for_axes(
&self,
axes_index: usize,
) -> Option<(bool, Vec<String>)> {
for (plot_idx, plot) in self.plots.iter().enumerate() {
let plot_axes = *self.plot_axes_indices.get(plot_idx).unwrap_or(&0);
if plot_axes != axes_index {
continue;
}
if let PlotElement::Bar(b) = plot {
if b.histogram_bin_edges().is_some() {
continue;
}
let is_x = matches!(b.orientation, crate::plots::bar::Orientation::Vertical);
return Some((is_x, b.labels.clone()));
}
}
None
}
pub fn x_axis_tick_labels_for_axes(&self, axes_index: usize) -> Option<Vec<String>> {
self.axes_metadata
.get(axes_index)
.and_then(|meta| meta.x_tick_labels.clone())
}
pub fn y_axis_tick_labels_for_axes(&self, axes_index: usize) -> Option<Vec<String>> {
self.axes_metadata
.get(axes_index)
.and_then(|meta| meta.y_tick_labels.clone())
}
pub fn x_axis_tick_format_for_axes(&self, axes_index: usize) -> Option<String> {
self.axes_metadata
.get(axes_index)
.and_then(|meta| meta.x_tick_format.clone())
}
pub fn y_axis_tick_format_for_axes(&self, axes_index: usize) -> Option<String> {
self.axes_metadata
.get(axes_index)
.and_then(|meta| meta.y_tick_format.clone())
}
pub fn x_axis_tick_label_rotation_for_axes(&self, axes_index: usize) -> Option<f64> {
self.axes_metadata
.get(axes_index)
.and_then(|meta| meta.x_tick_label_rotation)
}
pub fn y_axis_tick_label_rotation_for_axes(&self, axes_index: usize) -> Option<f64> {
self.axes_metadata
.get(axes_index)
.and_then(|meta| meta.y_tick_label_rotation)
}
pub fn x_axis_ticks_for_axes(&self, axes_index: usize) -> Option<Vec<f64>> {
self.axes_metadata
.get(axes_index)
.and_then(|meta| meta.x_ticks.clone())
}
pub fn y_axis_ticks_for_axes(&self, axes_index: usize) -> Option<Vec<f64>> {
self.axes_metadata
.get(axes_index)
.and_then(|meta| meta.y_ticks.clone())
}
pub fn histogram_axis_edges_for_axes(&self, axes_index: usize) -> Option<(bool, Vec<f64>)> {
for (plot_idx, plot) in self.plots.iter().enumerate() {
let plot_axes = *self.plot_axes_indices.get(plot_idx).unwrap_or(&0);
if plot_axes != axes_index {
continue;
}
if let PlotElement::Bar(b) = plot {
if let Some(edges) = b.histogram_bin_edges() {
let is_x = matches!(b.orientation, crate::plots::bar::Orientation::Vertical);
return Some((is_x, edges.to_vec()));
}
}
}
None
}
}
impl Default for Figure {
fn default() -> Self {
Self::new()
}
}
fn normalize_reference_range(range: (f64, f64)) -> (f64, f64) {
let (mut lo, mut hi) = range;
if !lo.is_finite() || !hi.is_finite() {
return (0.0, 1.0);
}
if hi < lo {
std::mem::swap(&mut lo, &mut hi);
}
if (hi - lo).abs() < f64::EPSILON {
let pad = lo.abs().max(1.0) * 0.5;
return (lo - pad, hi + pad);
}
(lo, hi)
}
impl PlotElement {
fn retained_snapshot_bytes(&self) -> Option<usize> {
let (boxed, payload) = match self {
Self::Line(plot) => (0, plot.retained_snapshot_bytes()?),
Self::Scatter(plot) => (0, plot.retained_snapshot_bytes()?),
Self::Bar(plot) => (0, plot.retained_snapshot_bytes()?),
Self::ErrorBar(plot) => (
std::mem::size_of::<ErrorBar>(),
plot.retained_snapshot_bytes()?,
),
Self::Stairs(plot) => (0, plot.retained_snapshot_bytes()?),
Self::Stem(plot) => (0, plot.retained_snapshot_bytes()?),
Self::Area(plot) => (0, plot.retained_snapshot_bytes()?),
Self::Quiver(plot) => (0, plot.retained_snapshot_bytes()?),
Self::Pie(plot) => (0, plot.retained_snapshot_bytes()?),
Self::Surface(plot) => (0, plot.retained_snapshot_bytes()?),
Self::Mesh(plot) => (
std::mem::size_of::<MeshPlot>(),
plot.retained_snapshot_bytes()?,
),
Self::Patch(plot) => (0, plot.retained_snapshot_bytes()?),
Self::Line3(plot) => (0, plot.retained_snapshot_bytes()?),
Self::Scatter3(plot) => (0, plot.retained_snapshot_bytes()?),
Self::Contour(plot) => (0, plot.retained_snapshot_bytes()?),
Self::ContourFill(plot) => (0, plot.retained_snapshot_bytes()?),
Self::ReferenceLine(plot) => (0, plot.retained_snapshot_bytes()?),
};
boxed.checked_add(payload)
}
pub fn is_visible(&self) -> bool {
match self {
PlotElement::Line(plot) => plot.visible,
PlotElement::Scatter(plot) => plot.visible,
PlotElement::Bar(plot) => plot.visible,
PlotElement::ErrorBar(plot) => plot.visible,
PlotElement::Stairs(plot) => plot.visible,
PlotElement::Stem(plot) => plot.visible,
PlotElement::Area(plot) => plot.visible,
PlotElement::Quiver(plot) => plot.visible,
PlotElement::Pie(plot) => plot.visible,
PlotElement::Surface(plot) => plot.visible,
PlotElement::Mesh(plot) => plot.is_visible(),
PlotElement::Patch(plot) => plot.is_visible(),
PlotElement::Line3(plot) => plot.visible,
PlotElement::Scatter3(plot) => plot.visible,
PlotElement::Contour(plot) => plot.visible,
PlotElement::ContourFill(plot) => plot.visible,
PlotElement::ReferenceLine(plot) => plot.visible,
}
}
pub fn label(&self) -> Option<String> {
match self {
PlotElement::Line(plot) => plot.label.clone(),
PlotElement::Scatter(plot) => plot.label.clone(),
PlotElement::Bar(plot) => plot.label.clone(),
PlotElement::ErrorBar(plot) => plot.label.clone(),
PlotElement::Stairs(plot) => plot.label.clone(),
PlotElement::Stem(plot) => plot.label.clone(),
PlotElement::Area(plot) => plot.label.clone(),
PlotElement::Quiver(plot) => plot.label.clone(),
PlotElement::Pie(plot) => plot.label.clone(),
PlotElement::Surface(plot) => plot.label.clone(),
PlotElement::Mesh(plot) => plot.label().map(str::to_string),
PlotElement::Patch(plot) => plot.label().map(str::to_string),
PlotElement::Line3(plot) => plot.label.clone(),
PlotElement::Scatter3(plot) => plot.label.clone(),
PlotElement::Contour(plot) => plot.label.clone(),
PlotElement::ContourFill(plot) => plot.label.clone(),
PlotElement::ReferenceLine(plot) => plot.label_for_legend(),
}
}
fn legend_marker(&self) -> Option<LegendMarker> {
match self {
PlotElement::Line(plot) => plot.marker.as_ref().map(|m| LegendMarker {
kind: m.kind,
face_color: m.face_color,
edge_color: m.edge_color,
filled: m.filled,
}),
_ => None,
}
}
fn legend_line_style(&self) -> crate::plots::line::LineStyle {
match self {
PlotElement::Line(plot) => plot.line_style,
PlotElement::Line3(plot) => plot.line_style,
PlotElement::ReferenceLine(plot) => plot.line_style,
_ => crate::plots::line::LineStyle::Solid,
}
}
fn legend_line_visible(&self) -> bool {
!matches!(self, PlotElement::Line(plot) if plot.line_style == crate::plots::line::LineStyle::None)
}
fn is_hidden_from_legend(&self) -> bool {
matches!(
self,
PlotElement::Line(plot) if plot.handle_visibility.eq_ignore_ascii_case("off")
)
}
pub fn set_label(&mut self, label: Option<String>) {
match self {
PlotElement::Line(plot) => plot.label = label,
PlotElement::Scatter(plot) => plot.label = label,
PlotElement::Bar(plot) => plot.label = label,
PlotElement::ErrorBar(plot) => plot.label = label,
PlotElement::Stairs(plot) => plot.label = label,
PlotElement::Stem(plot) => plot.label = label,
PlotElement::Area(plot) => plot.label = label,
PlotElement::Quiver(plot) => plot.label = label,
PlotElement::Pie(plot) => plot.label = label,
PlotElement::Surface(plot) => plot.label = label,
PlotElement::Mesh(plot) => plot.set_label(label),
PlotElement::Patch(plot) => plot.set_label(label),
PlotElement::Line3(plot) => plot.label = label,
PlotElement::Scatter3(plot) => plot.label = label,
PlotElement::Contour(plot) => plot.label = label,
PlotElement::ContourFill(plot) => plot.label = label,
PlotElement::ReferenceLine(plot) => plot.label = label,
}
}
pub fn color(&self) -> Vec4 {
match self {
PlotElement::Line(plot) => plot.color,
PlotElement::Scatter(plot) => plot.color,
PlotElement::Bar(plot) => plot.color,
PlotElement::ErrorBar(plot) => plot.color,
PlotElement::Stairs(plot) => plot.color,
PlotElement::Stem(plot) => plot.color,
PlotElement::Area(plot) => plot.color,
PlotElement::Quiver(plot) => plot.color,
PlotElement::Pie(_plot) => Vec4::new(1.0, 1.0, 1.0, 1.0),
PlotElement::Surface(_plot) => Vec4::new(1.0, 1.0, 1.0, 1.0),
PlotElement::Mesh(plot) => plot.effective_face_color(),
PlotElement::Patch(plot) => plot.effective_face_color(),
PlotElement::Line3(plot) => plot.color,
PlotElement::Scatter3(plot) => plot.colors.first().copied().unwrap_or(Vec4::ONE),
PlotElement::Contour(plot) => plot.legend_color(),
PlotElement::ContourFill(_plot) => Vec4::new(0.9, 0.9, 0.9, 1.0),
PlotElement::ReferenceLine(plot) => plot.color,
}
}
pub fn plot_type(&self) -> PlotType {
match self {
PlotElement::Line(_) => PlotType::Line,
PlotElement::Scatter(_) => PlotType::Scatter,
PlotElement::Bar(_) => PlotType::Bar,
PlotElement::ErrorBar(_) => PlotType::ErrorBar,
PlotElement::Stairs(_) => PlotType::Stairs,
PlotElement::Stem(_) => PlotType::Stem,
PlotElement::Area(_) => PlotType::Area,
PlotElement::Quiver(_) => PlotType::Quiver,
PlotElement::Pie(_) => PlotType::Pie,
PlotElement::Surface(_) => PlotType::Surface,
PlotElement::Mesh(_) => PlotType::Mesh,
PlotElement::Patch(_) => PlotType::Patch,
PlotElement::Line3(_) => PlotType::Line3,
PlotElement::Scatter3(_) => PlotType::Scatter3,
PlotElement::Contour(_) => PlotType::Contour,
PlotElement::ContourFill(_) => PlotType::ContourFill,
PlotElement::ReferenceLine(_) => PlotType::ReferenceLine,
}
}
pub fn bounds(&mut self) -> BoundingBox {
match self {
PlotElement::Line(plot) => plot.bounds(),
PlotElement::Scatter(plot) => plot.bounds(),
PlotElement::Bar(plot) => plot.bounds(),
PlotElement::ErrorBar(plot) => plot.bounds(),
PlotElement::Stairs(plot) => plot.bounds(),
PlotElement::Stem(plot) => plot.bounds(),
PlotElement::Area(plot) => plot.bounds(),
PlotElement::Quiver(plot) => plot.bounds(),
PlotElement::Pie(plot) => plot.bounds(),
PlotElement::Surface(plot) => plot.bounds(),
PlotElement::Mesh(plot) => plot.bounds(),
PlotElement::Patch(plot) => plot.bounds(),
PlotElement::Line3(plot) => plot.bounds(),
PlotElement::Scatter3(plot) => plot.bounds(),
PlotElement::Contour(plot) => plot.bounds(),
PlotElement::ContourFill(plot) => plot.bounds(),
PlotElement::ReferenceLine(plot) => plot.coordinate_bounds(),
}
}
pub fn render_data(&mut self) -> RenderData {
match self {
PlotElement::Line(plot) => plot.render_data(),
PlotElement::Scatter(plot) => plot.render_data(),
PlotElement::Bar(plot) => plot.render_data(),
PlotElement::ErrorBar(plot) => plot.render_data(),
PlotElement::Stairs(plot) => plot.render_data(),
PlotElement::Stem(plot) => plot.render_data(),
PlotElement::Area(plot) => plot.render_data(),
PlotElement::Quiver(plot) => plot.render_data(),
PlotElement::Pie(plot) => plot.render_data(),
PlotElement::Surface(plot) => plot.render_data(),
PlotElement::Mesh(plot) => plot.render_data(),
PlotElement::Patch(plot) => plot.render_data(),
PlotElement::Line3(plot) => plot.render_data(),
PlotElement::Scatter3(plot) => plot.render_data(),
PlotElement::Contour(plot) => plot.render_data(),
PlotElement::ContourFill(plot) => plot.render_data(),
PlotElement::ReferenceLine(plot) => {
plot.render_data_with_range((0.0, 1.0), (0.0, 1.0), None, (false, false))
}
}
}
pub fn estimated_memory_usage(&self) -> usize {
match self {
PlotElement::Line(plot) => plot.estimated_memory_usage(),
PlotElement::Scatter(plot) => plot.estimated_memory_usage(),
PlotElement::Bar(plot) => plot.estimated_memory_usage(),
PlotElement::ErrorBar(plot) => plot.estimated_memory_usage(),
PlotElement::Stairs(plot) => plot.estimated_memory_usage(),
PlotElement::Stem(plot) => plot.estimated_memory_usage(),
PlotElement::Area(plot) => plot.estimated_memory_usage(),
PlotElement::Quiver(plot) => plot.estimated_memory_usage(),
PlotElement::Pie(plot) => plot.estimated_memory_usage(),
PlotElement::Surface(_plot) => 0,
PlotElement::Mesh(plot) => plot.estimated_memory_usage(),
PlotElement::Patch(plot) => plot.estimated_memory_usage(),
PlotElement::Line3(plot) => plot.estimated_memory_usage(),
PlotElement::Scatter3(plot) => plot.estimated_memory_usage(),
PlotElement::Contour(plot) => plot.estimated_memory_usage(),
PlotElement::ContourFill(plot) => plot.estimated_memory_usage(),
PlotElement::ReferenceLine(plot) => plot.estimated_memory_usage(),
}
}
}
#[derive(Debug)]
pub struct FigureStatistics {
pub total_plots: usize,
pub visible_plots: usize,
pub plot_type_counts: HashMap<PlotType, usize>,
pub total_memory_usage: usize,
pub has_legend: bool,
}
pub mod matlab_compat {
use super::*;
use crate::plots::{LinePlot, ScatterPlot};
pub fn figure() -> Figure {
Figure::new()
}
pub fn figure_with_title<S: Into<String>>(title: S) -> Figure {
Figure::new().with_title(title)
}
pub fn plot_multiple_lines(
figure: &mut Figure,
data_sets: Vec<(Vec<f64>, Vec<f64>, Option<String>)>,
) -> Result<Vec<usize>, String> {
let mut indices = Vec::new();
for (i, (x, y, label)) in data_sets.into_iter().enumerate() {
let mut line = LinePlot::new(x, y)?;
let colors = [
Vec4::new(0.0, 0.4470, 0.7410, 1.0), Vec4::new(0.8500, 0.3250, 0.0980, 1.0), Vec4::new(0.9290, 0.6940, 0.1250, 1.0), Vec4::new(0.4940, 0.1840, 0.5560, 1.0), Vec4::new(0.4660, 0.6740, 0.1880, 1.0), Vec4::new(std::f64::consts::LOG10_2 as f32, 0.7450, 0.9330, 1.0), Vec4::new(0.6350, 0.0780, 0.1840, 1.0), ];
let color = colors[i % colors.len()];
line.set_color(color);
if let Some(label) = label {
line = line.with_label(label);
}
indices.push(figure.add_line_plot(line));
}
Ok(indices)
}
pub fn scatter_multiple(
figure: &mut Figure,
data_sets: Vec<(Vec<f64>, Vec<f64>, Option<String>)>,
) -> Result<Vec<usize>, String> {
let mut indices = Vec::new();
for (i, (x, y, label)) in data_sets.into_iter().enumerate() {
let mut scatter = ScatterPlot::new(x, y)?;
let colors = [
Vec4::new(1.0, 0.0, 0.0, 1.0), Vec4::new(0.0, 1.0, 0.0, 1.0), Vec4::new(0.0, 0.0, 1.0, 1.0), Vec4::new(1.0, 1.0, 0.0, 1.0), Vec4::new(1.0, 0.0, 1.0, 1.0), Vec4::new(0.0, 1.0, 1.0, 1.0), Vec4::new(0.5, 0.5, 0.5, 1.0), ];
let color = colors[i % colors.len()];
scatter.set_color(color);
if let Some(label) = label {
scatter = scatter.with_label(label);
}
indices.push(figure.add_scatter_plot(scatter));
}
Ok(indices)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::plots::line::LineStyle;
use glam::Vec3;
#[test]
fn test_figure_creation() {
let figure = Figure::new();
assert_eq!(figure.len(), 0);
assert!(figure.is_empty());
assert!(!figure.legend_enabled);
assert!(!figure.axes_metadata(0).unwrap().legend_enabled);
assert!(figure.grid_enabled);
}
#[test]
fn test_figure_styling() {
let figure = Figure::new()
.with_title("Test Figure")
.with_sg_title("Overview")
.with_labels("X Axis", "Y Axis")
.with_legend(false)
.with_grid(false);
assert_eq!(figure.title, Some("Test Figure".to_string()));
assert_eq!(figure.sg_title, Some("Overview".to_string()));
assert_eq!(figure.x_label, Some("X Axis".to_string()));
assert_eq!(figure.y_label, Some("Y Axis".to_string()));
assert!(!figure.legend_enabled);
assert!(!figure.grid_enabled);
}
#[test]
fn test_window_title_follows_name_and_number_title() {
let mut figure = Figure::new();
assert_eq!(figure.window_title(Some(7)), "Figure 7");
figure.set_name("demo");
assert_eq!(figure.window_title(Some(7)), "Figure 7: demo");
figure.set_number_title(false);
assert_eq!(figure.window_title(Some(7)), "demo");
figure.set_name(" ");
assert_eq!(figure.window_title(Some(7)), "RunMat Plot");
}
#[test]
fn test_has_any_titles_tracks_super_and_axes_titles() {
let mut figure = Figure::new();
assert!(!figure.has_any_titles());
figure.set_sg_title("Summary");
assert!(figure.has_any_titles());
figure.clear_sg_title();
assert!(!figure.has_any_titles());
figure.set_axes_title(0, "Panel");
assert!(figure.has_any_titles());
}
#[test]
fn line_axes_autoscale_to_enclosing_ticks_so_a_flat_top_trace_clears_the_border() {
let mut figure = Figure::new();
figure.add_line_plot(LinePlot::new(vec![1.0, 2.0], vec![-66.0, -66.0]).unwrap());
figure.add_line_plot(LinePlot::new(vec![1.0, 2.0], vec![-67.0, -123.0]).unwrap());
let (x, y) = figure.auto_axes_bounds_2d(0, (1.0, 2.0), (-123.0, -66.0));
assert_eq!(x, (1.0, 2.0));
assert_eq!(y, (-140.0, -60.0));
let mut limited = figure.clone();
limited.set_axes_limits(0, None, Some((-130.0, -66.0)));
assert_eq!(
limited
.auto_axes_bounds_2d(0, (1.0, 2.0), (-123.0, -66.0))
.1,
(-123.0, -66.0)
);
let mut equal = figure.clone();
equal.set_axis_equal(true);
assert_eq!(
equal.auto_axes_bounds_2d(0, (1.0, 2.0), (-123.0, -66.0)).1,
(-123.0, -66.0)
);
}
#[test]
fn test_multiple_line_plots() {
let mut figure = Figure::new();
let line1 = LinePlot::new(vec![0.0, 1.0, 2.0], vec![0.0, 1.0, 4.0])
.unwrap()
.with_label("Quadratic");
let index1 = figure.add_line_plot(line1);
let line2 = LinePlot::new(vec![0.0, 1.0, 2.0], vec![0.0, 1.0, 2.0])
.unwrap()
.with_style(Vec4::new(1.0, 0.0, 0.0, 1.0), 2.0, LineStyle::Dashed)
.with_label("Linear");
let index2 = figure.add_line_plot(line2);
assert_eq!(figure.len(), 2);
assert_eq!(index1, 0);
assert_eq!(index2, 1);
let legend = figure.legend_entries();
assert_eq!(legend.len(), 2);
assert_eq!(legend[0].label, "Quadratic");
assert_eq!(legend[1].label, "Linear");
}
#[test]
fn test_mixed_plot_types() {
let mut figure = Figure::new();
let line = LinePlot::new(vec![0.0, 1.0, 2.0], vec![1.0, 2.0, 3.0])
.unwrap()
.with_label("Line");
figure.add_line_plot(line);
let scatter = ScatterPlot::new(vec![0.5, 1.5, 2.5], vec![1.5, 2.5, 3.5])
.unwrap()
.with_label("Scatter");
figure.add_scatter_plot(scatter);
let bar = BarChart::new(vec!["A".to_string(), "B".to_string()], vec![2.0, 4.0])
.unwrap()
.with_label("Bar");
figure.add_bar_chart(bar);
assert_eq!(figure.len(), 3);
let render_data = figure.render_data();
assert_eq!(render_data.len(), 3);
let stats = figure.statistics();
assert_eq!(stats.total_plots, 3);
assert_eq!(stats.visible_plots, 3);
assert!(!stats.has_legend);
figure.legend_enabled = true;
assert!(figure.statistics().has_legend);
}
#[test]
fn test_plot_visibility() {
let mut figure = Figure::new();
let mut line = LinePlot::new(vec![0.0, 1.0], vec![0.0, 1.0]).unwrap();
line.set_visible(false); figure.add_line_plot(line);
let scatter = ScatterPlot::new(vec![0.0, 1.0], vec![1.0, 2.0]).unwrap();
figure.add_scatter_plot(scatter);
let render_data = figure.render_data();
assert_eq!(render_data.len(), 1);
let stats = figure.statistics();
assert_eq!(stats.total_plots, 2);
assert_eq!(stats.visible_plots, 1);
}
#[test]
fn test_bounds_computation() {
let mut figure = Figure::new();
let line = LinePlot::new(vec![-1.0, 0.0, 1.0], vec![-2.0, 0.0, 2.0]).unwrap();
figure.add_line_plot(line);
let scatter = ScatterPlot::new(vec![2.0, 3.0, 4.0], vec![1.0, 3.0, 5.0]).unwrap();
figure.add_scatter_plot(scatter);
let bounds = figure.bounds();
assert!(bounds.min.x <= -1.0);
assert!(bounds.max.x >= 4.0);
assert!(bounds.min.y <= -2.0);
assert!(bounds.max.y >= 5.0);
}
#[test]
fn test_reference_line_only_bounds_use_default_span() {
let mut vertical_figure = Figure::new();
vertical_figure.add_reference_line_on_axes(
ReferenceLine::new(ReferenceLineOrientation::Vertical, 2.0).unwrap(),
0,
);
let vertical_bounds = vertical_figure.bounds();
assert_eq!(vertical_bounds.min.x, 1.5);
assert_eq!(vertical_bounds.max.x, 2.5);
assert_eq!(vertical_bounds.min.y, 0.0);
assert_eq!(vertical_bounds.max.y, 1.0);
let mut horizontal_figure = Figure::new();
horizontal_figure.add_reference_line_on_axes(
ReferenceLine::new(ReferenceLineOrientation::Horizontal, 3.0).unwrap(),
0,
);
let horizontal_bounds = horizontal_figure.bounds();
assert_eq!(horizontal_bounds.min.x, 0.0);
assert_eq!(horizontal_bounds.max.x, 1.0);
assert_eq!(horizontal_bounds.min.y, 2.5);
assert_eq!(horizontal_bounds.max.y, 3.5);
}
#[test]
fn test_reference_line_render_data_prefers_figure_limits() {
let mut horizontal_figure = Figure::new().with_limits((-2.0, 8.0), (-10.0, 10.0));
horizontal_figure.axes_metadata[0].x_limits = Some((0.0, 1.0));
horizontal_figure.add_reference_line_on_axes(
ReferenceLine::new(ReferenceLineOrientation::Horizontal, 3.0).unwrap(),
0,
);
let horizontal_bounds = horizontal_figure.render_data()[0].bounds.unwrap();
assert_eq!(horizontal_bounds.min.x, -2.0);
assert_eq!(horizontal_bounds.max.x, 8.0);
assert_eq!(horizontal_bounds.min.y, 3.0);
assert_eq!(horizontal_bounds.max.y, 3.0);
let mut vertical_figure = Figure::new().with_limits((-2.0, 8.0), (-10.0, 10.0));
vertical_figure.axes_metadata[0].y_limits = Some((0.0, 1.0));
vertical_figure.add_reference_line_on_axes(
ReferenceLine::new(ReferenceLineOrientation::Vertical, 4.0).unwrap(),
0,
);
let vertical_bounds = vertical_figure.render_data()[0].bounds.unwrap();
assert_eq!(vertical_bounds.min.x, 4.0);
assert_eq!(vertical_bounds.max.x, 4.0);
assert_eq!(vertical_bounds.min.y, -10.0);
assert_eq!(vertical_bounds.max.y, 10.0);
}
#[test]
fn test_matlab_compat_multiple_lines() {
use super::matlab_compat::*;
let mut figure = figure_with_title("Multiple Lines Test");
let data_sets = vec![
(
vec![0.0, 1.0, 2.0],
vec![0.0, 1.0, 4.0],
Some("Quadratic".to_string()),
),
(
vec![0.0, 1.0, 2.0],
vec![0.0, 1.0, 2.0],
Some("Linear".to_string()),
),
(
vec![0.0, 1.0, 2.0],
vec![1.0, 1.0, 1.0],
Some("Constant".to_string()),
),
];
let indices = plot_multiple_lines(&mut figure, data_sets).unwrap();
assert_eq!(indices.len(), 3);
assert_eq!(figure.len(), 3);
let legend = figure.legend_entries();
assert_eq!(legend.len(), 3);
assert_ne!(legend[0].color, legend[1].color);
assert_ne!(legend[1].color, legend[2].color);
}
#[test]
fn axes_metadata_and_labels_are_isolated_per_subplot() {
let mut figure = Figure::new();
figure.set_subplot_grid(1, 2);
figure.set_axes_title(0, "Left Title");
figure.set_axes_xlabel(0, "Left X");
figure.set_axes_ylabel(0, "Left Y");
figure.set_axes_title(1, "Right Title");
figure.set_axes_style(
1,
TextStyle {
font_size: Some(14.0),
..Default::default()
},
);
figure.set_axes_legend_enabled(0, false);
figure.set_axes_legend_style(
1,
LegendStyle {
location: Some("southwest".into()),
..Default::default()
},
);
assert_eq!(
figure.axes_metadata(0).and_then(|m| m.title.as_deref()),
Some("Left Title")
);
assert_eq!(
figure.axes_metadata(1).and_then(|m| m.title.as_deref()),
Some("Right Title")
);
assert_eq!(
figure.axes_metadata(0).and_then(|m| m.x_label.as_deref()),
Some("Left X")
);
assert_eq!(
figure.axes_metadata(0).and_then(|m| m.y_label.as_deref()),
Some("Left Y")
);
assert!(!figure.axes_metadata(0).unwrap().legend_enabled);
assert_eq!(
figure
.axes_metadata(1)
.unwrap()
.legend_style
.location
.as_deref(),
Some("southwest")
);
assert_eq!(figure.axes_metadata(0).unwrap().axes_style.font_size, None);
assert_eq!(
figure.axes_metadata(1).unwrap().axes_style.font_size,
Some(14.0)
);
}
#[test]
fn legend_entry_carries_marker_and_omits_line_for_marker_only_series() {
let mut figure = Figure::new();
let mut plot = LinePlot::new(vec![2.0], vec![6.0])
.unwrap()
.with_label("optimum");
plot.line_style = crate::plots::line::LineStyle::None;
plot.marker = Some(crate::plots::line::LineMarkerAppearance {
kind: crate::plots::scatter::MarkerStyle::Circle,
size: 10.0,
edge_color: Vec4::new(1.0, 0.0, 0.0, 1.0),
face_color: Vec4::new(1.0, 0.0, 0.0, 1.0),
filled: true,
});
figure.add_line_plot(plot);
let entry = &figure.legend_entries()[0];
assert!(!entry.line_visible);
assert!(entry.marker.as_ref().is_some_and(|m| m.filled));
}
#[test]
fn set_labels_skips_lines_hidden_from_legend() {
let mut figure = Figure::new();
figure.add_line_plot(LinePlot::new(vec![0.0, 1.0], vec![1.0, 2.0]).unwrap());
let mut hidden = LinePlot::new(vec![0.0, 1.0], vec![2.0, 1.0]).unwrap();
hidden.handle_visibility = "off".to_string();
figure.add_line_plot(hidden);
figure.add_line_plot(LinePlot::new(vec![0.0, 1.0], vec![3.0, 4.0]).unwrap());
figure.set_labels(&["first".into(), "second".into()]);
let labels: Vec<String> = figure
.legend_entries()
.into_iter()
.map(|e| e.label)
.collect();
assert_eq!(labels, vec!["first".to_string(), "second".to_string()]);
}
#[test]
fn set_labels_for_axes_only_updates_target_subplot() {
let mut figure = Figure::new();
figure.set_subplot_grid(1, 2);
figure.add_line_plot_on_axes(
LinePlot::new(vec![0.0, 1.0], vec![1.0, 2.0])
.unwrap()
.with_label("L0"),
0,
);
figure.add_line_plot_on_axes(
LinePlot::new(vec![0.0, 1.0], vec![2.0, 3.0])
.unwrap()
.with_label("R0"),
1,
);
figure.set_labels_for_axes(1, &["Right Only".into()]);
let left_entries = figure.legend_entries_for_axes(0);
let right_entries = figure.legend_entries_for_axes(1);
assert_eq!(left_entries[0].label, "L0");
assert_eq!(right_entries[0].label, "Right Only");
}
#[test]
fn axes_log_modes_are_isolated_per_subplot() {
let mut figure = Figure::new();
figure.set_subplot_grid(1, 2);
figure.set_axes_log_modes(1, true, false);
assert!(!figure.axes_metadata(0).unwrap().x_log);
assert!(!figure.axes_metadata(0).unwrap().y_log);
assert!(figure.axes_metadata(1).unwrap().x_log);
assert!(!figure.axes_metadata(1).unwrap().y_log);
figure.set_active_axes_index(1);
assert!(figure.x_log);
assert!(!figure.y_log);
}
#[test]
fn z_label_and_view_state_are_isolated_per_subplot() {
let mut figure = Figure::new();
figure.set_subplot_grid(1, 2);
figure.set_axes_zlabel(1, "Height");
figure.set_axes_view(1, 45.0, 20.0);
assert_eq!(figure.axes_metadata(0).unwrap().z_label, None);
assert_eq!(
figure.axes_metadata(1).unwrap().z_label.as_deref(),
Some("Height")
);
assert_eq!(
figure.axes_metadata(1).unwrap().view_azimuth_deg,
Some(45.0)
);
assert_eq!(
figure.axes_metadata(1).unwrap().view_elevation_deg,
Some(20.0)
);
}
#[test]
fn axes_view_revision_advances_for_each_explicit_view_update() {
let mut figure = Figure::new();
assert_eq!(figure.axes_metadata(0).unwrap().view_revision, 0);
figure.set_axes_view(0, 45.0, 20.0);
assert_eq!(figure.axes_metadata(0).unwrap().view_revision, 1);
figure.set_axes_view(0, 45.0, 20.0);
assert_eq!(figure.axes_metadata(0).unwrap().view_revision, 2);
}
#[test]
fn pie_legend_entries_are_slice_based() {
let mut figure = Figure::new();
let pie = PieChart::new(vec![1.0, 2.0], None)
.unwrap()
.with_slice_labels(vec!["A".into(), "B".into()]);
figure.add_pie_chart(pie);
let entries = figure.legend_entries_for_axes(0);
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].label, "A");
assert_eq!(entries[1].label, "B");
}
#[test]
fn histogram_bars_do_not_use_categorical_axis_labels() {
let mut figure = Figure::new();
let mut bar = BarChart::new(vec!["a".into(), "b".into()], vec![2.0, 3.0]).unwrap();
bar.set_histogram_bin_edges(vec![0.0, 0.5, 1.0]);
figure.add_bar_chart(bar);
assert!(figure.categorical_axis_labels().is_none());
assert_eq!(
figure.histogram_axis_edges_for_axes(0),
Some((true, vec![0.0, 0.5, 1.0]))
);
}
#[test]
fn plain_bar_charts_keep_categorical_axis_labels() {
let mut figure = Figure::new();
let bar = BarChart::new(vec!["A".into(), "B".into()], vec![1.0, 2.0]).unwrap();
figure.add_bar_chart(bar);
assert_eq!(
figure.categorical_axis_labels(),
Some((true, vec!["A".to_string(), "B".to_string()]))
);
}
#[test]
fn line3_contributes_to_3d_bounds_and_metadata() {
let mut figure = Figure::new();
let line3 = Line3Plot::new(vec![0.0, 1.0], vec![1.0, 2.0], vec![2.0, 4.0])
.unwrap()
.with_label("Trajectory");
figure.add_line3_plot(line3);
let bounds = figure.bounds();
assert_eq!(bounds.min.z, 2.0);
assert_eq!(bounds.max.z, 4.0);
let entries = figure.legend_entries_for_axes(0);
assert_eq!(entries[0].plot_type, PlotType::Line3);
}
#[test]
fn hidden_line_removal_off_uses_no_depth_pipeline_for_mesh_edges() {
let mut figure = Figure::new();
let mesh = MeshPlot::new(
vec![
Vec3::new(0.0, 0.0, 0.0),
Vec3::new(1.0, 0.0, 0.0),
Vec3::new(0.0, 1.0, 1.0),
],
vec![[0, 1, 2]],
)
.unwrap();
figure.add_mesh_plot(mesh);
figure.set_axes_hidden_line_removal(0, false);
let render_data = figure.render_data();
assert_eq!(render_data.len(), 2);
assert_eq!(
render_data[0].pipeline_type,
crate::core::PipelineType::Triangles
);
assert_eq!(
render_data[1].pipeline_type,
crate::core::PipelineType::LinesNoDepth
);
}
#[test]
fn hidden_line_removal_off_uses_no_depth_pipeline_for_wireframe_surfaces() {
let mut figure = Figure::new();
let surface = SurfacePlot::new(
vec![0.0, 1.0],
vec![0.0, 1.0],
vec![vec![0.0, 1.0], vec![1.0, 0.0]],
)
.unwrap()
.with_wireframe(true);
figure.add_surface_plot(surface);
figure.set_axes_hidden_line_removal(0, false);
let render_data = figure.render_data();
assert_eq!(render_data.len(), 1);
assert_eq!(
render_data[0].pipeline_type,
crate::core::PipelineType::LinesNoDepth
);
}
#[test]
fn stem_render_data_includes_marker_pass() {
let mut figure = Figure::new();
figure.add_stem_plot(StemPlot::new(vec![0.0, 1.0], vec![1.0, 2.0]).unwrap());
let render_data = figure.render_data();
assert_eq!(render_data.len(), 2);
assert_eq!(
render_data[0].pipeline_type,
crate::core::PipelineType::Lines
);
assert_eq!(
render_data[1].pipeline_type,
crate::core::PipelineType::Points
);
}
#[test]
fn errorbar_render_data_includes_marker_pass() {
let mut figure = Figure::new();
let mut errorbar = ErrorBar::new_vertical(
vec![0.0, 1.0],
vec![1.0, 2.0],
vec![0.1, 0.2],
vec![0.1, 0.2],
)
.unwrap();
errorbar.set_marker(Some(crate::plots::line::LineMarkerAppearance {
kind: crate::plots::scatter::MarkerStyle::Circle,
size: 6.0,
edge_color: Vec4::ZERO,
face_color: Vec4::ONE,
filled: false,
}));
figure.add_errorbar(errorbar);
let render_data = figure.render_data();
assert_eq!(render_data.len(), 2);
assert_eq!(
render_data[0].pipeline_type,
crate::core::PipelineType::Lines
);
assert_eq!(
render_data[1].pipeline_type,
crate::core::PipelineType::Points
);
}
#[test]
fn subplot_sensitive_axes_state_is_isolated_per_subplot() {
let mut figure = Figure::new();
figure.set_subplot_grid(1, 2);
figure.set_axes_limits(1, Some((1.0, 2.0)), Some((3.0, 4.0)));
figure.set_axes_z_limits(1, Some((5.0, 6.0)));
figure.set_axes_grid_enabled(1, false);
figure.set_axes_minor_grid_enabled(1, true);
figure.set_axes_box_enabled(1, false);
figure.set_axes_axis_equal(1, true);
figure.set_axes_colorbar_enabled(1, true);
figure.set_axes_colormap(1, ColorMap::Hot);
figure.set_axes_color_limits(1, Some((0.0, 10.0)));
let left = figure.axes_metadata(0).unwrap();
let right = figure.axes_metadata(1).unwrap();
assert_eq!(left.x_limits, None);
assert_eq!(right.x_limits, Some((1.0, 2.0)));
assert!(!left.minor_grid_enabled);
assert!(!left.minor_grid_explicit);
assert!(!right.grid_enabled);
assert!(right.minor_grid_enabled);
assert!(right.minor_grid_explicit);
assert!(!right.box_enabled);
assert!(right.axis_equal);
assert!(right.colorbar_enabled);
assert_eq!(format!("{:?}", right.colormap), "Hot");
assert_eq!(right.color_limits, Some((0.0, 10.0)));
}
#[test]
fn subplot_grid_expansion_reclaims_overlay_axes_slots() {
let mut figure = Figure::new();
let overlay_axes = figure.ensure_overlay_axes(0);
assert_eq!(overlay_axes, 1);
figure.add_line_plot_on_axes(
LinePlot::new(vec![0.0, 1.0], vec![10.0, 20.0]).unwrap(),
overlay_axes,
);
assert_eq!(figure.axes_overlay_parent(overlay_axes), Some(0));
assert_eq!(figure.axes_count(), 2);
figure.set_subplot_grid(2, 1);
let second_subplot = figure.axes_metadata(1).unwrap();
assert_eq!(second_subplot.overlay_parent, None);
assert_eq!(second_subplot.y_axis_location, "left");
assert!(figure.plot_axes_indices().is_empty());
assert_eq!(figure.axes_count(), 2);
}
#[test]
fn active_axes_sync_does_not_clobber_figure_minor_grid_default() {
let mut figure = Figure::new();
figure.set_subplot_grid(1, 2);
figure.minor_grid_enabled = true;
assert!(figure.minor_grid_enabled_for_axes(0));
assert!(figure.minor_grid_enabled_for_axes(1));
figure.set_active_axes_index(1);
assert!(figure.minor_grid_enabled);
assert!(figure.minor_grid_enabled_for_axes(0));
assert!(figure.minor_grid_enabled_for_axes(1));
figure.set_axes_minor_grid_enabled(1, false);
assert!(figure.minor_grid_enabled);
assert!(figure.minor_grid_enabled_for_axes(0));
assert!(!figure.minor_grid_enabled_for_axes(1));
}
}