1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
//! Auto-generated module
//!
//! 🤖 Generated with [SplitRS](https://github.com/cool-japan/splitrs)
use thiserror::Error;
use super::functions::{vec3_add, vec3_cross, vec3_norm, vec3_scale, vec3_sub};
/// A ray for volumetric rendering — origin + normalised direction.
///
/// Named `VolumetricRay` to avoid collision with [`crate::picking::Ray`] which is
/// already exported from the crate root.
#[derive(Debug, Clone, Copy)]
pub struct VolumetricRay {
/// World-space ray origin.
pub origin: [f32; 3],
/// World-space direction (unit vector).
pub direction: [f32; 3],
}
impl VolumetricRay {
/// Construct, normalising `direction`. Uses un-normalised direction on
/// degenerate input (very short vectors) to avoid division by zero.
pub fn new_normalized(origin: [f32; 3], direction: [f32; 3]) -> Self {
let len_sq =
direction[0] * direction[0] + direction[1] * direction[1] + direction[2] * direction[2];
let dir = if len_sq > f32::EPSILON {
let inv = 1.0 / len_sq.sqrt();
[direction[0] * inv, direction[1] * inv, direction[2] * inv]
} else {
direction
};
Self {
origin,
direction: dir,
}
}
/// Point on ray at parameter `t`: `origin + t * direction`.
#[inline]
pub fn at(&self, t: f32) -> [f32; 3] {
[
self.origin[0] + t * self.direction[0],
self.origin[1] + t * self.direction[1],
self.origin[2] + t * self.direction[2],
]
}
}
/// Aggregated statistics over a batch of marched rays.
#[derive(Debug, Clone)]
pub struct VolumetricStats {
/// Number of rays analysed.
pub n_rays: usize,
/// Mean number of integration steps per ray.
pub mean_steps_per_ray: f32,
/// Maximum steps taken by any single ray.
pub max_steps_per_ray: usize,
/// Mean alpha across all rays.
pub mean_alpha: f32,
/// Rays that reached `alpha > 0.99`.
pub fully_opaque_rays: usize,
/// Rays that never intersected the volume (`t_entry == t_exit == 0`).
pub empty_rays: usize,
}
/// Pin-hole camera for volumetric rendering.
#[derive(Debug, Clone)]
pub struct VolumetricCamera {
/// Camera position in world space.
pub eye: [f32; 3],
/// Point the camera is looking at.
pub target: [f32; 3],
/// Up vector hint (need not be perpendicular to the viewing direction).
pub up: [f32; 3],
/// Vertical field of view in radians.
pub fov_y_rad: f32,
/// Image width in pixels.
pub width: u32,
/// Image height in pixels.
pub height: u32,
/// Near clip distance (unused in ray marching, stored for reference).
pub near: f32,
/// Far clip distance (unused in ray marching, stored for reference).
pub far: f32,
}
impl VolumetricCamera {
/// Generate a ray through pixel centre `(px, py)` (integer pixel coords).
pub fn generate_ray(&self, px: f32, py: f32) -> VolumetricRay {
let fwd = vec3_norm(vec3_sub(self.target, self.eye));
let right = vec3_norm(vec3_cross(fwd, self.up));
let up = vec3_cross(right, fwd);
let aspect = self.width as f32 / self.height as f32;
let half_h = (self.fov_y_rad * 0.5).tan();
let half_w = aspect * half_h;
let ndc_x = (px + 0.5) / self.width as f32 * 2.0 - 1.0;
let ndc_y = 1.0 - (py + 0.5) / self.height as f32 * 2.0;
let dir = vec3_add(
vec3_add(fwd, vec3_scale(right, ndc_x * half_w)),
vec3_scale(up, ndc_y * half_h),
);
VolumetricRay::new_normalized(self.eye, dir)
}
/// Default front-facing camera looking at the origin from `z = 3`.
pub fn default_front(width: u32, height: u32) -> Self {
Self {
eye: [0.0, 0.0, 3.0],
target: [0.0, 0.0, 0.0],
up: [0.0, 1.0, 0.0],
fov_y_rad: std::f32::consts::FRAC_PI_4,
width,
height,
near: 0.01,
far: 100.0,
}
}
}
/// A uniform rectilinear grid of density (scalar) values.
///
/// Data is stored in `[iz * ny * nx + iy * nx + ix]` order (C/row-major,
/// z slowest).
#[derive(Debug, Clone)]
pub struct VolumeGrid {
/// Flat density array, length `nx * ny * nz`.
pub data: Vec<f32>,
/// Number of voxels along X.
pub nx: usize,
/// Number of voxels along Y.
pub ny: usize,
/// Number of voxels along Z.
pub nz: usize,
/// World-space position of the min corner (voxel `[0,0,0]` centre minus
/// half a voxel).
pub origin: [f32; 3],
/// Physical size of each voxel along each axis.
pub voxel_size: [f32; 3],
}
impl VolumeGrid {
/// Create an all-zero grid.
pub fn new(nx: usize, ny: usize, nz: usize, origin: [f32; 3], voxel_size: [f32; 3]) -> Self {
let n = nx.saturating_mul(ny).saturating_mul(nz);
Self {
data: vec![0.0_f32; n],
nx,
ny,
nz,
origin,
voxel_size,
}
}
/// Create a grid populated by evaluating `f(x, y, z)` at every voxel
/// centre (world-space coordinates).
pub fn from_fn(
nx: usize,
ny: usize,
nz: usize,
origin: [f32; 3],
voxel_size: [f32; 3],
f: impl Fn(f32, f32, f32) -> f32,
) -> Self {
let mut g = Self::new(nx, ny, nz, origin, voxel_size);
for iz in 0..nz {
for iy in 0..ny {
for ix in 0..nx {
let wx = origin[0] + (ix as f32 + 0.5) * voxel_size[0];
let wy = origin[1] + (iy as f32 + 0.5) * voxel_size[1];
let wz = origin[2] + (iz as f32 + 0.5) * voxel_size[2];
g.data[iz * ny * nx + iy * nx + ix] = f(wx, wy, wz);
}
}
}
g
}
/// Convert a world-space point to continuous voxel coordinates.
///
/// The returned value is centred so that `(0.5, 0.5, 0.5)` corresponds to
/// the centre of voxel `[0, 0, 0]`.
#[inline]
pub fn world_to_voxel(&self, p: [f32; 3]) -> [f32; 3] {
[
(p[0] - self.origin[0]) / self.voxel_size[0] - 0.5,
(p[1] - self.origin[1]) / self.voxel_size[1] - 0.5,
(p[2] - self.origin[2]) / self.voxel_size[2] - 0.5,
]
}
/// Convert continuous voxel coordinates back to world space.
#[inline]
pub fn voxel_to_world(&self, vi: [f32; 3]) -> [f32; 3] {
[
(vi[0] + 0.5) * self.voxel_size[0] + self.origin[0],
(vi[1] + 0.5) * self.voxel_size[1] + self.origin[1],
(vi[2] + 0.5) * self.voxel_size[2] + self.origin[2],
]
}
/// Returns `true` if world-space point `p` is inside the grid AABB.
#[inline]
pub fn in_bounds(&self, p: [f32; 3]) -> bool {
let max = [
self.origin[0] + self.nx as f32 * self.voxel_size[0],
self.origin[1] + self.ny as f32 * self.voxel_size[1],
self.origin[2] + self.nz as f32 * self.voxel_size[2],
];
p[0] >= self.origin[0]
&& p[1] >= self.origin[1]
&& p[2] >= self.origin[2]
&& p[0] <= max[0]
&& p[1] <= max[1]
&& p[2] <= max[2]
}
/// Returns `true` if any dimension is zero (an empty grid). `VolumeGrid::new`
/// permits zero dimensions (some call sites construct a grid before its
/// final size is known), so every sampling method must check this rather
/// than assume `nx`/`ny`/`nz` are all positive.
#[inline]
pub fn is_empty(&self) -> bool {
self.nx == 0 || self.ny == 0 || self.nz == 0
}
/// Direct integer-indexed density lookup; clamps indices to valid range.
///
/// Returns `0.0` for an empty grid (see [`Self::is_empty`]) rather than
/// indexing an empty `data` array.
#[inline]
pub fn density_at(&self, ix: usize, iy: usize, iz: usize) -> f32 {
if self.is_empty() {
return 0.0;
}
let ix = ix.min(self.nx.saturating_sub(1));
let iy = iy.min(self.ny.saturating_sub(1));
let iz = iz.min(self.nz.saturating_sub(1));
self.data[iz * self.ny * self.nx + iy * self.nx + ix]
}
/// Nearest-neighbour sample at world-space position.
///
/// Returns `0.0` for an empty grid (see [`Self::is_empty`]) rather than
/// panicking in `f32::clamp` (whose `(0.0, (nx as f32) - 1.0)` range is
/// invalid, `min > max`, when `nx == 0`).
pub fn sample_nearest(&self, x: f32, y: f32, z: f32) -> f32 {
if self.is_empty() {
return 0.0;
}
let vx = ((x - self.origin[0]) / self.voxel_size[0] - 0.5).round();
let vy = ((y - self.origin[1]) / self.voxel_size[1] - 0.5).round();
let vz = ((z - self.origin[2]) / self.voxel_size[2] - 0.5).round();
let ix = vx.clamp(0.0, (self.nx as f32) - 1.0) as usize;
let iy = vy.clamp(0.0, (self.ny as f32) - 1.0) as usize;
let iz = vz.clamp(0.0, (self.nz as f32) - 1.0) as usize;
self.density_at(ix, iy, iz)
}
/// Trilinear interpolation at world-space position, clamping at boundaries.
///
/// Returns `0.0` for an empty grid (see [`Self::is_empty`]) rather than
/// panicking in the `i64::clamp(0, max - 1)` below (invalid, `min > max`,
/// when a dimension is 0).
pub fn sample_trilinear(&self, x: f32, y: f32, z: f32) -> f32 {
if self.is_empty() {
return 0.0;
}
let vx = (x - self.origin[0]) / self.voxel_size[0] - 0.5;
let vy = (y - self.origin[1]) / self.voxel_size[1] - 0.5;
let vz = (z - self.origin[2]) / self.voxel_size[2] - 0.5;
let x0 = vx.floor() as i64;
let y0 = vy.floor() as i64;
let z0 = vz.floor() as i64;
let fx = vx - vx.floor();
let fy = vy - vy.floor();
let fz = vz - vz.floor();
let nx = self.nx as i64;
let ny = self.ny as i64;
let nz = self.nz as i64;
let ci = |v: i64, max: i64| v.clamp(0, max - 1) as usize;
let c000 = self.density_at(ci(x0, nx), ci(y0, ny), ci(z0, nz));
let c100 = self.density_at(ci(x0 + 1, nx), ci(y0, ny), ci(z0, nz));
let c010 = self.density_at(ci(x0, nx), ci(y0 + 1, ny), ci(z0, nz));
let c110 = self.density_at(ci(x0 + 1, nx), ci(y0 + 1, ny), ci(z0, nz));
let c001 = self.density_at(ci(x0, nx), ci(y0, ny), ci(z0 + 1, nz));
let c101 = self.density_at(ci(x0 + 1, nx), ci(y0, ny), ci(z0 + 1, nz));
let c011 = self.density_at(ci(x0, nx), ci(y0 + 1, ny), ci(z0 + 1, nz));
let c111 = self.density_at(ci(x0 + 1, nx), ci(y0 + 1, ny), ci(z0 + 1, nz));
let c00 = c000 * (1.0 - fx) + c100 * fx;
let c10 = c010 * (1.0 - fx) + c110 * fx;
let c01 = c001 * (1.0 - fx) + c101 * fx;
let c11 = c011 * (1.0 - fx) + c111 * fx;
let c0 = c00 * (1.0 - fy) + c10 * fy;
let c1 = c01 * (1.0 - fy) + c11 * fy;
c0 * (1.0 - fz) + c1 * fz
}
/// Central-difference gradient at world-space position (in density/unit).
pub fn gradient(&self, x: f32, y: f32, z: f32) -> [f32; 3] {
let h = [self.voxel_size[0], self.voxel_size[1], self.voxel_size[2]];
let dx = (self.sample_trilinear(x + h[0], y, z) - self.sample_trilinear(x - h[0], y, z))
/ (2.0 * h[0]);
let dy = (self.sample_trilinear(x, y + h[1], z) - self.sample_trilinear(x, y - h[1], z))
/ (2.0 * h[1]);
let dz = (self.sample_trilinear(x, y, z + h[2]) - self.sample_trilinear(x, y, z - h[2]))
/ (2.0 * h[2]);
[dx, dy, dz]
}
}
/// Volumetric integration algorithm.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VolumetricIntegration {
/// Front-to-back alpha compositing with early termination.
FrontToBack,
/// Back-to-front (Porter-Duff) compositing (no early termination).
BackToFront,
/// Maximum Intensity Projection — track peak density only.
Mip,
/// Average Intensity Projection — accumulate all samples equally.
Avg,
}
/// Piecewise-linear transfer function mapping density → (colour, opacity).
#[derive(Debug, Clone)]
pub struct TransferFunction {
/// Control points, guaranteed non-empty and sorted ascending by `density`.
pub points: Vec<TransferPoint>,
}
impl TransferFunction {
/// Construct from a list of control points.
///
/// # Errors
///
/// - [`VolumetricRenderError::EmptyTransferFunction`] if `points` is empty.
/// - [`VolumetricRenderError::UnsortedTransferFunction`] if densities are
/// not *strictly* increasing (two points at the same density would
/// make [`Self::evaluate`]'s interpolation ill-defined there).
/// - [`VolumetricRenderError::InvalidTransferPoint`] if any point's
/// opacity is outside `[0, 1]` or has a non-finite colour component.
pub fn new(points: Vec<TransferPoint>) -> Result<Self, VolumetricRenderError> {
if points.is_empty() {
return Err(VolumetricRenderError::EmptyTransferFunction);
}
for w in points.windows(2) {
if w[0].density >= w[1].density {
return Err(VolumetricRenderError::UnsortedTransferFunction);
}
}
for (index, p) in points.iter().enumerate() {
if !(0.0..=1.0).contains(&p.opacity) {
return Err(VolumetricRenderError::InvalidTransferPoint {
index,
reason: "opacity must be in [0, 1]",
});
}
if !p.color.iter().all(|c| c.is_finite()) || !p.density.is_finite() {
return Err(VolumetricRenderError::InvalidTransferPoint {
index,
reason: "density and colour components must be finite",
});
}
}
Ok(Self { points })
}
/// Evaluate the transfer function at `density` via piecewise linear interpolation.
/// Clamps to the first / last control point outside the range.
pub fn evaluate(&self, density: f32) -> ([f32; 3], f32) {
let pts = &self.points;
if density <= pts[0].density {
return (pts[0].color, pts[0].opacity);
}
if density >= pts[pts.len() - 1].density {
let p = &pts[pts.len() - 1];
return (p.color, p.opacity);
}
let mut lo = 0usize;
let mut hi = pts.len() - 1;
while hi - lo > 1 {
let mid = (lo + hi) / 2;
if pts[mid].density <= density {
lo = mid;
} else {
hi = mid;
}
}
// `new` rejects equal-density control points, but `points` is a
// public field, so guard defensively against a caller constructing
// a `TransferFunction` directly with a near-zero-width interval
// here rather than let it produce +-inf / NaN.
let span = pts[hi].density - pts[lo].density;
let t = if span.abs() > f32::EPSILON {
(density - pts[lo].density) / span
} else {
0.0
};
let lerp3 = |a: [f32; 3], b: [f32; 3]| {
[
a[0] + t * (b[0] - a[0]),
a[1] + t * (b[1] - a[1]),
a[2] + t * (b[2] - a[2]),
]
};
let color = lerp3(pts[lo].color, pts[hi].color);
let opacity = pts[lo].opacity + t * (pts[hi].opacity - pts[lo].opacity);
(color, opacity)
}
/// Simple grayscale: density 0 → transparent black, `density_max` → opaque white.
pub fn grayscale(density_max: f32) -> Self {
Self {
points: vec![
TransferPoint {
density: 0.0,
color: [0.0; 3],
opacity: 0.0,
},
TransferPoint {
density: density_max.max(f32::EPSILON),
color: [1.0; 3],
opacity: 1.0,
},
],
}
}
/// Classic heat colormap: transparent-blue → cyan → green → yellow → red-opaque.
pub fn heat(density_max: f32) -> Self {
let d = density_max.max(f32::EPSILON);
Self {
points: vec![
TransferPoint {
density: 0.0,
color: [0.0, 0.0, 1.0],
opacity: 0.0,
},
TransferPoint {
density: d * 0.25,
color: [0.0, 1.0, 1.0],
opacity: 0.25,
},
TransferPoint {
density: d * 0.5,
color: [0.0, 1.0, 0.0],
opacity: 0.5,
},
TransferPoint {
density: d * 0.75,
color: [1.0, 1.0, 0.0],
opacity: 0.75,
},
TransferPoint {
density: d,
color: [1.0, 0.0, 0.0],
opacity: 1.0,
},
],
}
}
}
/// Errors produced by the volumetric rendering subsystem.
#[derive(Debug, Error)]
pub enum VolumetricRenderError {
/// Volume grid has zero extent in at least one dimension.
#[error("Zero-size volume: nx={nx} ny={ny} nz={nz}")]
ZeroSizeVolume { nx: usize, ny: usize, nz: usize },
/// Transfer function point list is empty.
#[error("Transfer function has no points")]
EmptyTransferFunction,
/// Transfer function control points are not strictly increasing in
/// density (this includes equal-density points: two control points at
/// the same density make `TransferFunction::evaluate`'s interpolation
/// ill-defined at that density).
#[error("Transfer function points are not sorted by density ascending")]
UnsortedTransferFunction,
/// A transfer function control point has an opacity outside `[0, 1]` or
/// a non-finite colour component.
#[error("Transfer function point {index} is invalid: {reason}")]
InvalidTransferPoint {
/// Index of the offending point in the input list.
index: usize,
/// What was wrong with it.
reason: &'static str,
},
/// Input slice lengths are inconsistent with `n_gaussians`.
#[error("Buffer length mismatch: expected {expected}, got {got} for '{field}'")]
BufferLengthMismatch {
field: &'static str,
expected: usize,
got: usize,
},
/// Invalid camera parameters.
#[error("Invalid camera: {0}")]
InvalidCamera(String),
}
/// A single control point in a piecewise-linear transfer function.
#[derive(Debug, Clone, PartialEq)]
pub struct TransferPoint {
/// Input density value (non-negative).
pub density: f32,
/// RGB colour output at this density.
pub color: [f32; 3],
/// Opacity (alpha) at this density, in `[0, 1]`.
pub opacity: f32,
}
/// Configuration for the ray-marching integrator.
#[derive(Debug, Clone)]
pub struct VolumetricRenderConfig {
/// World-space step size between samples.
pub step_size: f32,
/// Maximum number of steps per ray (safety limit).
pub max_steps: usize,
/// Front-to-back: stop accumulating when alpha exceeds this value.
pub early_termination_alpha: f32,
/// Integration algorithm.
pub integration: VolumetricIntegration,
/// Add sub-step jitter to reduce wood-grain banding.
pub jitter: bool,
/// Seed for the xorshift64 PRNG used for jitter.
pub jitter_seed: u64,
}
/// Result of marching a single ray through the volume.
#[derive(Debug, Clone)]
pub struct RayMarchResult {
/// Accumulated colour (RGB).
pub color: [f32; 3],
/// Accumulated opacity.
pub alpha: f32,
/// Number of integration steps taken.
pub n_steps: usize,
/// Ray parameter at volume entry.
pub t_entry: f32,
/// Ray parameter at volume exit.
pub t_exit: f32,
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
//
// This file's own regression tests. The sibling `tests.rs` (a separate
// module, `super::tests`, not this one) holds the broader existing test
// suite for the whole `volumetric_render` module.
#[cfg(test)]
mod tests {
use super::*;
// ── Zero-size VolumeGrid: no panics ─────────────────────────────────────
#[test]
fn test_zero_size_grid_is_empty() {
let g = VolumeGrid::new(0, 4, 4, [0.0; 3], [1.0; 3]);
assert!(g.is_empty());
let g = VolumeGrid::new(4, 4, 4, [0.0; 3], [1.0; 3]);
assert!(!g.is_empty());
}
#[test]
fn test_zero_size_grid_density_at_no_panic() {
// Regression test: `density_at` used to index an empty `data` Vec
// and panic for any zero-size dimension.
for (nx, ny, nz) in [(0, 4, 4), (4, 0, 4), (4, 4, 0), (0, 0, 0)] {
let g = VolumeGrid::new(nx, ny, nz, [0.0; 3], [1.0; 3]);
assert_eq!(g.density_at(0, 0, 0), 0.0, "nx={nx} ny={ny} nz={nz}");
assert_eq!(g.density_at(5, 5, 5), 0.0, "nx={nx} ny={ny} nz={nz}");
}
}
#[test]
fn test_zero_size_grid_sample_nearest_no_panic() {
// Regression test: `sample_nearest` used to call
// `f32::clamp(0.0, (nx as f32) - 1.0)`, which panics (min > max)
// when nx == 0.
let g = VolumeGrid::new(0, 4, 4, [0.0; 3], [1.0; 3]);
assert_eq!(g.sample_nearest(0.5, 0.5, 0.5), 0.0);
}
#[test]
fn test_zero_size_grid_sample_trilinear_no_panic() {
// Regression test: `sample_trilinear` used to call
// `i64::clamp(0, (nx as i64) - 1)`, which panics (min > max) when
// nx == 0.
let g = VolumeGrid::new(4, 0, 4, [0.0; 3], [1.0; 3]);
assert_eq!(g.sample_trilinear(0.5, 0.5, 0.5), 0.0);
}
#[test]
fn test_zero_size_grid_gradient_no_panic() {
// `gradient` is built entirely on `sample_trilinear`, so it should
// inherit the fix automatically.
let g = VolumeGrid::new(4, 4, 0, [0.0; 3], [1.0; 3]);
let grad = g.gradient(0.5, 0.5, 0.5);
assert_eq!(grad, [0.0, 0.0, 0.0]);
}
// ── TransferFunction validation ──────────────────────────────────────────
#[test]
fn test_transfer_function_rejects_duplicate_density() {
// Regression test: `new` used to accept equal (not just decreasing)
// adjacent densities, which made `evaluate`'s interpolation
// ill-defined at that density.
let pts = vec![
TransferPoint {
density: 0.5,
color: [0.0; 3],
opacity: 0.0,
},
TransferPoint {
density: 0.5,
color: [1.0; 3],
opacity: 1.0,
},
];
let err = TransferFunction::new(pts).expect_err("duplicate density must be rejected");
assert!(matches!(
err,
VolumetricRenderError::UnsortedTransferFunction
));
}
#[test]
fn test_transfer_function_rejects_opacity_out_of_range() {
let pts = vec![
TransferPoint {
density: 0.0,
color: [0.0; 3],
opacity: 0.0,
},
TransferPoint {
density: 1.0,
color: [1.0; 3],
opacity: 1.5, // out of [0, 1]
},
];
let err = TransferFunction::new(pts).expect_err("out-of-range opacity must be rejected");
assert!(matches!(
err,
VolumetricRenderError::InvalidTransferPoint { index: 1, .. }
));
}
#[test]
fn test_transfer_function_rejects_non_finite_color() {
let pts = vec![
TransferPoint {
density: 0.0,
color: [f32::NAN, 0.0, 0.0],
opacity: 0.0,
},
TransferPoint {
density: 1.0,
color: [1.0; 3],
opacity: 1.0,
},
];
let err = TransferFunction::new(pts).expect_err("non-finite colour must be rejected");
assert!(matches!(
err,
VolumetricRenderError::InvalidTransferPoint { index: 0, .. }
));
}
#[test]
fn test_transfer_function_evaluate_zero_span_no_nan() {
// Defensive check on `evaluate` itself: a `TransferFunction` with
// duplicate-density points constructed directly (bypassing `new`,
// since `points` is a public field) must not produce NaN or +-inf
// when evaluated near those densities. The `t` computation now
// guards its denominator with an epsilon check specifically for
// this, even though this interpolation's `lo`/`hi` search happens
// to land past any interior duplicate run in every configuration
// this test could construct (only 2-point all-duplicate inputs are
// fully absorbed by the domain-clamp checks above the binary
// search) -- the guard stays as defense in depth against future
// changes to that search.
let tf = TransferFunction {
points: vec![
TransferPoint {
density: 0.0,
color: [0.0; 3],
opacity: 0.0,
},
TransferPoint {
density: 0.5,
color: [0.2, 0.4, 0.6],
opacity: 0.5,
},
TransferPoint {
density: 0.5,
color: [1.0; 3],
opacity: 1.0,
},
TransferPoint {
density: 1.0,
color: [1.0; 3],
opacity: 1.0,
},
],
};
let (color, opacity) = tf.evaluate(0.5);
assert!(color.iter().all(|c| c.is_finite()), "color = {color:?}");
assert!(opacity.is_finite(), "opacity = {opacity}");
}
}