sim-engine 0.1.0

A validated high-performance visualization engine for simulations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
use std::{error::Error, fmt};

use crate::Color;

/// A finite, rectangular scalar grid for dense simulation data.
#[derive(Debug, Clone, PartialEq)]
pub struct ScalarField {
    width: usize,
    height: usize,
    values: Vec<f32>,
}

impl ScalarField {
    /// Default maximum allocation performed by [`ScalarField::filled`].
    ///
    /// Hosts needing a different explicit budget can use
    /// [`ScalarField::filled_with_byte_limit`] or pass an already allocated
    /// buffer to [`ScalarField::new`].
    pub const DEFAULT_MAX_FILLED_BYTES: usize = 256 * 1024 * 1024;

    /// Creates a field from row-major values, validating dimensions and finiteness.
    pub fn new(width: usize, height: usize, values: Vec<f32>) -> Result<Self, ScalarFieldError> {
        let expected_len = checked_len(width, height)?;
        if values.len() != expected_len {
            return Err(ScalarFieldError::InvalidValueCount {
                expected: expected_len,
                actual: values.len(),
            });
        }
        if values.iter().any(|value| !value.is_finite()) {
            return Err(ScalarFieldError::NonFiniteValue);
        }
        Ok(Self {
            width,
            height,
            values,
        })
    }

    /// Creates a finite field filled with one finite scalar value.
    ///
    /// Allocation is limited to [`ScalarField::DEFAULT_MAX_FILLED_BYTES`] and
    /// uses fallible reservation before initialization.
    pub fn filled(width: usize, height: usize, value: f32) -> Result<Self, ScalarFieldError> {
        Self::filled_with_byte_limit(width, height, value, Self::DEFAULT_MAX_FILLED_BYTES)
    }

    /// Creates a filled field under an explicit host-memory byte limit.
    ///
    /// `maximum_bytes` applies to the row-major `f32` value buffer. Reservation
    /// failure is returned without partially constructing the field. Supplying
    /// a larger limit is an explicit host decision; system overcommit can still
    /// make physical memory exhaustion unrecoverable on some platforms.
    pub fn filled_with_byte_limit(
        width: usize,
        height: usize,
        value: f32,
        maximum_bytes: usize,
    ) -> Result<Self, ScalarFieldError> {
        let len = checked_len(width, height)?;
        if !value.is_finite() {
            return Err(ScalarFieldError::NonFiniteValue);
        }
        let requested_bytes = len
            .checked_mul(std::mem::size_of::<f32>())
            .ok_or(ScalarFieldError::DimensionsOverflow)?;
        if requested_bytes > maximum_bytes {
            return Err(ScalarFieldError::AllocationLimitExceeded {
                requested_bytes,
                maximum_bytes,
            });
        }
        let mut values = Vec::new();
        values
            .try_reserve_exact(len)
            .map_err(|_| ScalarFieldError::AllocationFailed { requested_bytes })?;
        values.resize(len, value);
        Ok(Self {
            width,
            height,
            values,
        })
    }

    /// Returns the horizontal cell count.
    pub fn width(&self) -> usize {
        self.width
    }

    /// Returns the vertical cell count.
    pub fn height(&self) -> usize {
        self.height
    }

    /// Returns row-major scalar values.
    pub fn values(&self) -> &[f32] {
        &self.values
    }

    /// Returns a cell value, or `None` outside field bounds.
    pub fn value_at(&self, x: usize, y: usize) -> Option<f32> {
        self.index(x, y).map(|index| self.values[index])
    }

    /// Replaces one cell with a finite value.
    pub fn set(&mut self, x: usize, y: usize, value: f32) -> Result<(), ScalarFieldError> {
        if !value.is_finite() {
            return Err(ScalarFieldError::NonFiniteValue);
        }
        let index = self
            .index(x, y)
            .ok_or(ScalarFieldError::OutOfBounds { x, y })?;
        self.values[index] = value;
        Ok(())
    }

    /// Replaces all values while preserving the field dimensions.
    pub fn replace_values(&mut self, values: Vec<f32>) -> Result<(), ScalarFieldError> {
        if values.len() != self.values.len() {
            return Err(ScalarFieldError::InvalidValueCount {
                expected: self.values.len(),
                actual: values.len(),
            });
        }
        if values.iter().any(|value| !value.is_finite()) {
            return Err(ScalarFieldError::NonFiniteValue);
        }
        self.values = values;
        Ok(())
    }

    /// Replaces a contiguous rectangular region with finite row-major values.
    pub fn replace_region(
        &mut self,
        x: usize,
        y: usize,
        width: usize,
        height: usize,
        values: &[f32],
    ) -> Result<(), ScalarFieldError> {
        let expected = checked_len(width, height)?;
        if values.len() != expected {
            return Err(ScalarFieldError::InvalidValueCount {
                expected,
                actual: values.len(),
            });
        }
        if values.iter().any(|value| !value.is_finite()) {
            return Err(ScalarFieldError::NonFiniteValue);
        }
        let end_x = x
            .checked_add(width)
            .ok_or(ScalarFieldError::OutOfBounds { x, y })?;
        let end_y = y
            .checked_add(height)
            .ok_or(ScalarFieldError::OutOfBounds { x, y })?;
        if end_x > self.width || end_y > self.height {
            return Err(ScalarFieldError::OutOfBounds { x, y });
        }
        for row in 0..height {
            let destination = (y + row) * self.width + x;
            let source = row * width;
            self.values[destination..destination + width]
                .copy_from_slice(&values[source..source + width]);
        }
        Ok(())
    }

    /// Returns finite minimum and maximum scalar values.
    pub fn value_range(&self) -> (f32, f32) {
        let mut minimum = self.values[0];
        let mut maximum = minimum;
        for value in &self.values[1..] {
            minimum = minimum.min(*value);
            maximum = maximum.max(*value);
        }
        (minimum, maximum)
    }

    fn index(&self, x: usize, y: usize) -> Option<usize> {
        (x < self.width && y < self.height).then_some(y * self.width + x)
    }
}

fn checked_len(width: usize, height: usize) -> Result<usize, ScalarFieldError> {
    if width == 0 || height == 0 {
        return Err(ScalarFieldError::ZeroDimension);
    }
    width
        .checked_mul(height)
        .ok_or(ScalarFieldError::DimensionsOverflow)
}

/// Rejection reason for scalar-field construction or mutation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScalarFieldError {
    /// Width and height must both be non-zero.
    ZeroDimension,
    /// Width multiplied by height overflowed `usize`.
    DimensionsOverflow,
    /// Input values did not match the grid dimensions.
    InvalidValueCount {
        /// Required row-major cell count.
        expected: usize,
        /// Supplied value count.
        actual: usize,
    },
    /// A scalar value was NaN or infinite.
    NonFiniteValue,
    /// A filled field exceeds the explicit host-memory budget.
    AllocationLimitExceeded {
        /// Bytes required by the row-major `f32` values.
        requested_bytes: usize,
        /// Maximum bytes authorized by the caller or default policy.
        maximum_bytes: usize,
    },
    /// The allocator rejected a value-buffer reservation within the byte limit.
    AllocationFailed {
        /// Bytes requested from the allocator.
        requested_bytes: usize,
    },
    /// A requested cell lies outside the field dimensions.
    OutOfBounds {
        /// Horizontal cell index.
        x: usize,
        /// Vertical cell index.
        y: usize,
    },
}

impl fmt::Display for ScalarFieldError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ZeroDimension => write!(formatter, "scalar field dimensions must be non-zero"),
            Self::DimensionsOverflow => write!(formatter, "scalar field dimensions overflow"),
            Self::InvalidValueCount { expected, actual } => {
                write!(
                    formatter,
                    "scalar field needs {expected} values, got {actual}"
                )
            }
            Self::NonFiniteValue => write!(formatter, "scalar field values must be finite"),
            Self::AllocationLimitExceeded {
                requested_bytes,
                maximum_bytes,
            } => write!(
                formatter,
                "scalar field needs {requested_bytes} bytes, exceeding the {maximum_bytes}-byte allocation limit"
            ),
            Self::AllocationFailed { requested_bytes } => write!(
                formatter,
                "scalar field could not reserve {requested_bytes} bytes"
            ),
            Self::OutOfBounds { x, y } => {
                write!(formatter, "scalar field cell ({x}, {y}) is out of bounds")
            }
        }
    }
}

impl Error for ScalarFieldError {}

/// One normalized color-map control point.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ColorStop {
    position: f32,
    color: Color,
}

impl ColorStop {
    /// Creates a stop with normalized position and normalized linear RGBA color.
    ///
    /// Normalized colors keep the CPU sampler consistent with the renderer's
    /// `Rgba8Unorm` heatmap lookup texture instead of silently clipping HDR values.
    pub fn new(position: f32, color: Color) -> Result<Self, ColorMapError> {
        if !position.is_finite() || !color.is_finite() {
            return Err(ColorMapError::NonFiniteStop);
        }
        if !(0.0..=1.0).contains(&position) {
            return Err(ColorMapError::PositionOutOfRange);
        }
        if !color.is_normalized() {
            return Err(ColorMapError::ColorOutOfRange);
        }
        Ok(Self { position, color })
    }

    /// Returns the normalized stop position.
    pub fn position(self) -> f32 {
        self.position
    }

    /// Returns the linear RGBA stop color.
    pub fn color(self) -> Color {
        self.color
    }
}

/// A piecewise-linear map from normalized scalar values to linear RGBA colors.
///
/// [`Self::sample`] evaluates the control points exactly on the CPU. The `wgpu`
/// heatmap renderer samples a documented 256-entry, 8-bit lookup table, so
/// transitions narrower than one LUT interval can be quantized away.
#[derive(Debug, Clone, PartialEq)]
pub struct ColorMap {
    stops: Vec<ColorStop>,
}

impl ColorMap {
    /// Builds a color map from at least two strictly increasing stops.
    pub fn new(stops: Vec<ColorStop>) -> Result<Self, ColorMapError> {
        if stops.len() < 2 {
            return Err(ColorMapError::TooFewStops);
        }
        if stops
            .windows(2)
            .any(|pair| pair[0].position >= pair[1].position)
        {
            return Err(ColorMapError::StopsNotIncreasing);
        }
        Ok(Self { stops })
    }

    /// Builds a two-color normalized gradient.
    pub fn linear(start: Color, end: Color) -> Result<Self, ColorMapError> {
        Self::new(vec![ColorStop::new(0.0, start)?, ColorStop::new(1.0, end)?])
    }

    /// Returns the immutable control points.
    pub fn stops(&self) -> &[ColorStop] {
        &self.stops
    }

    /// Samples the map, clamping a finite normalized input to its endpoints.
    pub fn sample(&self, value: f32) -> Result<Color, ColorMapError> {
        if !value.is_finite() {
            return Err(ColorMapError::NonFiniteSample);
        }
        Ok(self.sample_normalized(value))
    }

    pub(crate) fn sample_normalized(&self, value: f32) -> Color {
        let value = value.clamp(0.0, 1.0);
        let upper = self.stops.partition_point(|stop| stop.position < value);
        if upper == 0 {
            return self.stops[0].color;
        }
        if upper == self.stops.len() {
            return self.stops[upper - 1].color;
        }
        let start = self.stops[upper - 1];
        let end = self.stops[upper];
        let amount = (value - start.position) / (end.position - start.position);
        Color::rgba(
            start.color.red() + (end.color.red() - start.color.red()) * amount,
            start.color.green() + (end.color.green() - start.color.green()) * amount,
            start.color.blue() + (end.color.blue() - start.color.blue()) * amount,
            start.color.alpha() + (end.color.alpha() - start.color.alpha()) * amount,
        )
    }
}

/// Rejection reason for color-map construction or sampling.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorMapError {
    /// A stop position or color channel was NaN or infinite.
    NonFiniteStop,
    /// A stop position was outside `0.0..=1.0`.
    PositionOutOfRange,
    /// A linear RGBA stop color had a channel outside `0.0..=1.0`.
    ColorOutOfRange,
    /// A map needs at least two stops.
    TooFewStops,
    /// Stops must have strictly increasing positions.
    StopsNotIncreasing,
    /// A sampled normalized value was NaN or infinite.
    NonFiniteSample,
}

impl fmt::Display for ColorMapError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{self:?}")
    }
}

impl Error for ColorMapError {}

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

    #[test]
    fn scalar_field_validates_shape_finiteness_and_updates() {
        let mut field = ScalarField::new(2, 2, vec![1.0, -3.0, 2.0, 4.0]).unwrap();
        assert_eq!(field.value_range(), (-3.0, 4.0));
        field.set(1, 0, 6.0).unwrap();
        assert_eq!(field.value_at(1, 0), Some(6.0));
        assert_eq!(
            field.set(2, 0, 0.0),
            Err(ScalarFieldError::OutOfBounds { x: 2, y: 0 })
        );
        assert_eq!(
            ScalarField::filled(0, 1, 0.0),
            Err(ScalarFieldError::ZeroDimension)
        );
        assert_eq!(
            ScalarField::new(2, 2, vec![0.0; 3]),
            Err(ScalarFieldError::InvalidValueCount {
                expected: 4,
                actual: 3
            })
        );
        assert_eq!(
            ScalarField::filled(1, 1, f32::NAN),
            Err(ScalarFieldError::NonFiniteValue)
        );
        assert_eq!(
            ScalarField::filled(usize::MAX, 1, 0.0),
            Err(ScalarFieldError::DimensionsOverflow)
        );
        let first_over_default_limit =
            ScalarField::DEFAULT_MAX_FILLED_BYTES / std::mem::size_of::<f32>() + 1;
        assert_eq!(
            ScalarField::filled(first_over_default_limit, 1, 0.0),
            Err(ScalarFieldError::AllocationLimitExceeded {
                requested_bytes: first_over_default_limit * std::mem::size_of::<f32>(),
                maximum_bytes: ScalarField::DEFAULT_MAX_FILLED_BYTES,
            })
        );
        assert_eq!(
            ScalarField::filled_with_byte_limit(2, 2, 0.0, 15),
            Err(ScalarFieldError::AllocationLimitExceeded {
                requested_bytes: 16,
                maximum_bytes: 15,
            })
        );
        assert_eq!(
            ScalarField::filled_with_byte_limit(2, 2, 3.0, 16)
                .unwrap()
                .values(),
            &[3.0; 4]
        );
        let first_vector_capacity_overflow = isize::MAX as usize / std::mem::size_of::<f32>() + 1;
        assert_eq!(
            ScalarField::filled_with_byte_limit(first_vector_capacity_overflow, 1, 0.0, usize::MAX,),
            Err(ScalarFieldError::AllocationFailed {
                requested_bytes: first_vector_capacity_overflow * std::mem::size_of::<f32>(),
            })
        );
        field.replace_region(0, 1, 2, 1, &[7.0, 8.0]).unwrap();
        assert_eq!(field.values(), &[1.0, 6.0, 7.0, 8.0]);
        assert_eq!(
            field.replace_region(1, 1, 2, 1, &[0.0, 1.0]),
            Err(ScalarFieldError::OutOfBounds { x: 1, y: 1 })
        );
        assert_eq!(
            field.replace_region(0, 0, 1, 2, &[0.0]),
            Err(ScalarFieldError::InvalidValueCount {
                expected: 2,
                actual: 1
            })
        );
        assert_eq!(
            field.replace_region(0, 0, 1, 1, &[f32::INFINITY]),
            Err(ScalarFieldError::NonFiniteValue)
        );
    }

    #[test]
    fn color_map_interpolates_and_rejects_invalid_contracts() {
        let map = ColorMap::linear(Color::BLACK, Color::WHITE).unwrap();
        assert_eq!(map.sample(-1.0).unwrap(), Color::BLACK);
        assert_eq!(map.sample(2.0).unwrap(), Color::WHITE);
        assert_eq!(map.sample(0.5).unwrap(), Color::rgba(0.5, 0.5, 0.5, 1.0));
        assert_eq!(map.sample(f32::NAN), Err(ColorMapError::NonFiniteSample));
        let first = ColorStop::new(0.75, Color::WHITE).unwrap();
        let second = ColorStop::new(0.5, Color::BLACK).unwrap();
        assert_eq!(
            ColorMap::new(vec![first, second]),
            Err(ColorMapError::StopsNotIncreasing)
        );
        assert_eq!(
            ColorStop::new(0.5, Color::rgba(1.1, 0.0, 0.0, 1.0)),
            Err(ColorMapError::ColorOutOfRange)
        );
    }
}