Skip to main content

dear_implot3d/
layout.rs

1use std::cell::Cell;
2
3use crate::{imgui_sys, sys};
4
5pub(crate) fn len_i32(len: usize) -> Option<i32> {
6    i32::try_from(len).ok()
7}
8
9pub(crate) fn axis_tick_count_to_i32(caller: &str, count: usize) -> i32 {
10    assert!(count > 0, "{caller} n_ticks must be positive");
11    i32::try_from(count)
12        .unwrap_or_else(|_| panic!("{caller} n_ticks exceeded ImPlot3D's i32 range"))
13}
14
15pub(crate) const IMPLOT3D_AUTO: i32 = -1;
16
17/// Sample-index offset used by ImPlot3D item data access.
18///
19/// ImPlot3D intentionally allows negative and out-of-range offsets for circular
20/// buffers, so this is a signed sample offset rather than a Rust slice index.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
22pub struct Plot3DDataOffset(i32);
23
24impl Plot3DDataOffset {
25    /// No data offset.
26    pub const ZERO: Self = Self(0);
27
28    /// Create a sample-index offset.
29    #[inline]
30    pub const fn samples(offset: i32) -> Self {
31        Self(offset)
32    }
33
34    #[inline]
35    pub(crate) const fn raw(self) -> i32 {
36        self.0
37    }
38}
39
40/// Byte stride used by ImPlot3D item data access.
41///
42/// Use [`Plot3DDataStride::AUTO`] for contiguous data of the plotted value type,
43/// or [`Plot3DDataStride::bytes`] for interleaved/custom layouts.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct Plot3DDataStride(i32);
46
47impl Plot3DDataStride {
48    /// Let ImPlot3D use `sizeof(T)` for the plotted value type.
49    pub const AUTO: Self = Self(IMPLOT3D_AUTO);
50
51    /// Create a byte stride.
52    ///
53    /// Panics if `bytes` is zero or exceeds ImPlot3D's `int` range.
54    #[inline]
55    pub fn bytes(bytes: usize) -> Self {
56        assert!(
57            bytes > 0,
58            "Plot3DDataStride::bytes() requires a non-zero stride"
59        );
60        let bytes = i32::try_from(bytes)
61            .expect("Plot3DDataStride::bytes() stride exceeded ImPlot3D's int range");
62        Self(bytes)
63    }
64
65    /// Create the contiguous byte stride for `T`.
66    #[inline]
67    pub fn for_type<T>() -> Self {
68        Self::bytes(std::mem::size_of::<T>())
69    }
70
71    #[inline]
72    pub(crate) const fn raw(self) -> i32 {
73        self.0
74    }
75}
76
77impl Default for Plot3DDataStride {
78    fn default() -> Self {
79        Self::AUTO
80    }
81}
82
83/// Data layout used by ImPlot3D item builders.
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
85pub struct Plot3DDataLayout {
86    offset: Plot3DDataOffset,
87    stride: Plot3DDataStride,
88}
89
90impl Plot3DDataLayout {
91    /// Contiguous data starting at sample offset zero.
92    pub const DEFAULT: Self = Self {
93        offset: Plot3DDataOffset::ZERO,
94        stride: Plot3DDataStride::AUTO,
95    };
96
97    /// Create a data layout from a sample offset and byte stride.
98    #[inline]
99    pub const fn new(offset: Plot3DDataOffset, stride: Plot3DDataStride) -> Self {
100        Self { offset, stride }
101    }
102
103    /// Create a data layout with a different sample offset.
104    #[inline]
105    pub const fn with_offset(mut self, offset: Plot3DDataOffset) -> Self {
106        self.offset = offset;
107        self
108    }
109
110    /// Create a data layout with a different byte stride.
111    #[inline]
112    pub const fn with_stride(mut self, stride: Plot3DDataStride) -> Self {
113        self.stride = stride;
114        self
115    }
116
117    pub(crate) fn sample_count(self, len: usize) -> Option<i32> {
118        let count = i32::try_from(len).ok()?;
119        if count > i32::MAX / 2 && self.raw_offset() != 0 {
120            // Native ImPosMod adds count to the remainder, then IndexData adds the sample index.
121            let remainder = self.raw_offset() % count;
122            let offset = remainder.checked_add(count)? % count;
123            offset.checked_add(count - 1)?;
124        }
125        Some(count)
126    }
127
128    #[inline]
129    pub(crate) const fn raw_offset(self) -> i32 {
130        self.offset.raw()
131    }
132
133    #[inline]
134    pub(crate) const fn raw_stride(self) -> i32 {
135        self.stride.raw()
136    }
137}
138
139/// One-shot overrides for submissions to a single open plot. Borrowed array pointers are
140/// installed only by `scoped` and cannot be carried across plots or into another context.
141#[derive(Default)]
142pub(crate) struct NextItemStyle {
143    pending: Cell<Option<sys::ImPlot3DSpec_c>>,
144    consumed: Cell<u64>,
145}
146
147impl NextItemStyle {
148    pub(crate) fn update(&self, change: impl FnOnce(&mut sys::ImPlot3DSpec_c)) {
149        let mut spec = self.pending.get().unwrap_or_else(default_plot3d_spec);
150        change(&mut spec);
151        self.pending.set(Some(spec));
152    }
153
154    pub(crate) fn scoped<R>(
155        &self,
156        change: impl FnOnce(&mut sys::ImPlot3DSpec_c),
157        f: impl FnOnce() -> R,
158    ) -> R {
159        let _restore = RestoreUnused {
160            next: self,
161            previous: self.pending.get(),
162            consumed: self.consumed.get(),
163        };
164        self.update(change);
165        f()
166    }
167
168    pub(crate) fn spec(&self, flags: u32, layout: Plot3DDataLayout) -> sys::ImPlot3DSpec_c {
169        let mut spec = match self.pending.get() {
170            Some(spec) => {
171                self.consumed.set(
172                    self.consumed
173                        .get()
174                        .checked_add(1)
175                        .expect("ImPlot3D submission counter overflow"),
176                );
177                self.pending.set(None);
178                spec
179            }
180            None => default_plot3d_spec(),
181        };
182        spec.Flags = ((spec.Flags as u32) | flags) as sys::ImPlot3DItemFlags;
183        spec.Offset = layout.raw_offset();
184        spec.Stride = layout.raw_stride();
185        spec
186    }
187}
188
189struct RestoreUnused<'a> {
190    next: &'a NextItemStyle,
191    previous: Option<sys::ImPlot3DSpec_c>,
192    consumed: u64,
193}
194
195impl Drop for RestoreUnused<'_> {
196    fn drop(&mut self) {
197        // A submission consumes all contributing scopes. Keep any new style queued afterwards.
198        if self.next.consumed.get() == self.consumed {
199            self.next.pending.set(self.previous);
200        }
201    }
202}
203
204pub(crate) fn default_plot3d_spec() -> sys::ImPlot3DSpec_c {
205    let auto_col = sys::ImVec4_c {
206        x: 0.0,
207        y: 0.0,
208        z: 0.0,
209        w: -1.0,
210    };
211
212    sys::ImPlot3DSpec_c {
213        LineColor: auto_col,
214        LineColors: std::ptr::null_mut(),
215        LineWeight: 1.0,
216        FillColor: auto_col,
217        FillColors: std::ptr::null_mut(),
218        FillAlpha: -1.0,
219        Marker: sys::ImPlot3DMarker_Auto as _,
220        MarkerSize: -1.0,
221        MarkerSizes: std::ptr::null_mut(),
222        MarkerLineColor: auto_col,
223        MarkerLineColors: std::ptr::null_mut(),
224        MarkerFillColor: auto_col,
225        MarkerFillColors: std::ptr::null_mut(),
226        Offset: 0,
227        Stride: IMPLOT3D_AUTO,
228        Flags: sys::ImPlot3DItemFlags_None as _,
229    }
230}
231
232pub(crate) trait ImVec2Ctor {
233    fn from_xy(x: f32, y: f32) -> Self;
234}
235
236impl ImVec2Ctor for sys::ImVec2_c {
237    fn from_xy(x: f32, y: f32) -> Self {
238        Self { x, y }
239    }
240}
241
242impl ImVec2Ctor for imgui_sys::ImVec2_c {
243    fn from_xy(x: f32, y: f32) -> Self {
244        Self { x, y }
245    }
246}
247
248#[inline]
249pub(crate) fn imvec2<T: ImVec2Ctor>(x: f32, y: f32) -> T {
250    T::from_xy(x, y)
251}
252
253pub(crate) trait ImVec4Ctor {
254    fn from_xyzw(x: f32, y: f32, z: f32, w: f32) -> Self;
255}
256
257impl ImVec4Ctor for sys::ImVec4_c {
258    fn from_xyzw(x: f32, y: f32, z: f32, w: f32) -> Self {
259        Self { x, y, z, w }
260    }
261}
262
263impl ImVec4Ctor for imgui_sys::ImVec4_c {
264    fn from_xyzw(x: f32, y: f32, z: f32, w: f32) -> Self {
265        Self { x, y, z, w }
266    }
267}
268
269#[inline]
270pub(crate) fn imvec4<T: ImVec4Ctor>(x: f32, y: f32, z: f32, w: f32) -> T {
271    T::from_xyzw(x, y, z, w)
272}
273
274#[cfg(test)]
275mod tests {
276    use super::{
277        NextItemStyle, Plot3DDataLayout, Plot3DDataOffset, Plot3DDataStride, axis_tick_count_to_i32,
278    };
279
280    #[test]
281    fn data_layout_allows_signed_sample_offsets() {
282        let layout = Plot3DDataLayout::DEFAULT.with_offset(Plot3DDataOffset::samples(-8));
283        let spec = NextItemStyle::default().spec(0, layout);
284        assert_eq!(spec.Offset, -8);
285        assert_eq!(spec.Stride, super::IMPLOT3D_AUTO);
286    }
287
288    #[test]
289    fn circular_sample_count_checks_native_offset_arithmetic() {
290        let max = i32::MAX as usize;
291        assert_eq!(Plot3DDataLayout::DEFAULT.sample_count(max), Some(i32::MAX));
292        let backward = Plot3DDataLayout::DEFAULT.with_offset(Plot3DDataOffset::samples(-1));
293        assert_eq!(backward.sample_count(4), Some(4));
294        assert_eq!(backward.sample_count(max), None);
295        let forward = Plot3DDataLayout::DEFAULT.with_offset(Plot3DDataOffset::samples(1));
296        assert_eq!(forward.sample_count(max), None);
297    }
298
299    #[test]
300    fn data_stride_bytes_are_positive() {
301        let stride = Plot3DDataStride::bytes(16);
302        let layout = Plot3DDataLayout::DEFAULT.with_stride(stride);
303        let spec = NextItemStyle::default().spec(0, layout);
304        assert_eq!(spec.Stride, 16);
305    }
306
307    #[test]
308    #[should_panic(expected = "requires a non-zero stride")]
309    fn zero_data_stride_panics_before_ffi() {
310        let _ = Plot3DDataStride::bytes(0);
311    }
312
313    #[test]
314    fn axis_ticks_range_count_is_checked_before_ffi() {
315        assert_eq!(axis_tick_count_to_i32("test", 1), 1);
316        assert_eq!(axis_tick_count_to_i32("test", i32::MAX as usize), i32::MAX);
317
318        assert!(
319            std::panic::catch_unwind(|| axis_tick_count_to_i32("test", 0)).is_err(),
320            "zero tick counts must not cross the safe API boundary"
321        );
322        assert!(
323            std::panic::catch_unwind(|| {
324                axis_tick_count_to_i32("test", i32::MAX as usize + 1);
325            })
326            .is_err(),
327            "oversized tick counts must not cross the safe API boundary"
328        );
329    }
330}